Advertisement
Guest User

Untitled

a guest
May 22nd, 2015
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.11 KB | None | 0 0
  1. require 'treetop'
  2.  
  3. class MyPP
  4. def initialize(ast)
  5. @ast = ast
  6. @indentation = ''
  7. end
  8.  
  9. def inspect
  10. @inspected ||= pretty_print @ast
  11. end
  12.  
  13. private
  14.  
  15. def pretty_print(ast)
  16. if !ast.terminal?
  17. ast.elements.inject('') { |printed, child| printed << pretty_print(child) }
  18. else
  19. case val = ast.text_value
  20. when /\A\d+\Z/ then val
  21. when '(' then indent!; "("
  22. when ')' then outdent!; ")"
  23. when '+' then "\n#{@indentation}#{val} "
  24. end
  25. end
  26. end
  27.  
  28. def indent!
  29. @indentation << ' '
  30. end
  31.  
  32. def outdent!
  33. @indentation.chomp! ' '
  34. end
  35. end
  36.  
  37.  
  38. Treetop.load_from_string <<GRAMMAR
  39. grammar A
  40. rule operator_sequence
  41. lhs:single_element rest:(operator operator_sequence)*
  42. end
  43.  
  44. rule single_element
  45. '(' operator_sequence ')' / num
  46. end
  47.  
  48. rule num
  49. [0-9]+
  50. end
  51.  
  52. rule operator
  53. "+"
  54. end
  55. end
  56. GRAMMAR
  57.  
  58. ast = AParser.new.parse '1+(1)+(2+2)+3+(1+2+3+((4+5)+(6+7)))+8'
  59. p MyPP.new ast
  60.  
  61. # >> 1
  62. # >> + (1)
  63. # >> + (2
  64. # >> + 2)
  65. # >> + 3
  66. # >> + (1
  67. # >> + 2
  68. # >> + 3
  69. # >> + ((4
  70. # >> + 5)
  71. # >> + (6
  72. # >> + 7)))
  73. # >> + 8
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement