Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require 'treetop'
- class MyPP
- def initialize(ast)
- @ast = ast
- @indentation = ''
- end
- def inspect
- @inspected ||= pretty_print @ast
- end
- private
- def pretty_print(ast)
- if !ast.terminal?
- ast.elements.inject('') { |printed, child| printed << pretty_print(child) }
- else
- case val = ast.text_value
- when /\A\d+\Z/ then val
- when '(' then indent!; "("
- when ')' then outdent!; ")"
- when '+' then "\n#{@indentation}#{val} "
- end
- end
- end
- def indent!
- @indentation << ' '
- end
- def outdent!
- @indentation.chomp! ' '
- end
- end
- Treetop.load_from_string <<GRAMMAR
- grammar A
- rule operator_sequence
- lhs:single_element rest:(operator operator_sequence)*
- end
- rule single_element
- '(' operator_sequence ')' / num
- end
- rule num
- [0-9]+
- end
- rule operator
- "+"
- end
- end
- GRAMMAR
- ast = AParser.new.parse '1+(1)+(2+2)+3+(1+2+3+((4+5)+(6+7)))+8'
- p MyPP.new ast
- # >> 1
- # >> + (1)
- # >> + (2
- # >> + 2)
- # >> + 3
- # >> + (1
- # >> + 2
- # >> + 3
- # >> + ((4
- # >> + 5)
- # >> + (6
- # >> + 7)))
- # >> + 8
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement