Last active
August 29, 2015 14:07
-
-
Save ykst/ac33df4062716d01d95d to your computer and use it in GitHub Desktop.
method_missingと内部DSL ref: http://qiita.com/ykst/items/5b7b2903c71b43797a8e
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct(:data) { | |
int :x; | |
int :y; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Parser | |
def initialize | |
@env_stack = [[]] | |
end | |
def parse(program) | |
eval(program) | |
p @env_stack | |
end | |
private | |
def int(name) | |
var = { :id => name, :type => :int } | |
@env_stack.last.push var | |
end | |
def struct(name) | |
var = { :id => name, :type => :struct } | |
@env_stack.push [] | |
yield if block_given? | |
var.merge! :fields => @env_stack.pop | |
@env_stack.last.push var | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Parser.new.parse(%Q( | |
struct(:data) { | |
int :x; | |
int :y; | |
} | |
)) | |
=> | |
[[ | |
{ | |
:id => :data, :type => :struct, | |
:fields => [ | |
{ :id => :x, :type => :int }, | |
{ :id => :y, :type => :int }, | |
] | |
} | |
]] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def method_missing(name, *args) | |
name | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct(data) { | |
int x; | |
int y; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment