Skip to content

Instantly share code, notes, and snippets.

@whitequark
Created September 7, 2011 21:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whitequark/1201762 to your computer and use it in GitHub Desktop.
Save whitequark/1201762 to your computer and use it in GitHub Desktop.
Treetop AST quirks
require 'treetop'
Treetop.load 'ast_quirks.treetop'
parser = SimpleExpressionParser.new
ast = parser.parse %q{42}
p ast.to_code
grammar SimpleExpression
rule expression
( string / number ) {
def to_code
elements.first.to_code
end
}
end
rule string
'"' ( !'"' . / '\"' )* '"' {
def to_code; text_value; end
}
end
rule number
[0-9]+ {
def to_code; text_value.to_i; end
}
end
end
grammar SimpleExpression
rule expression
( string / number ) 1..1 {
def to_code
elements.first.to_code
end
}
end
rule string
'"' ( !'"' . / '\"' )* '"' {
def to_code; text_value; end
}
end
rule number
[0-9]+ {
def to_code; text_value.to_i; end
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment