1

I am making a parser for a simple grammar to learn about parsing technique.

For example if I have the following grammar:

exp    := if-exp ...
if-exp := if bool-exp then exp else exp
....

In languages which support algebraic data types, I can do:

type exp = 
| If-exp of bool-exp * exp * exp
| ....

A Java example I found creates a class for every sub-expression:

Class If_exp
  @bool_exp
  @then_exp
  @else_exp

 ...

end

"How to manually construct an AST?" uses a hash to construct an AST.

Which way is better? What is the Ruby way?

Community
  • 1
  • 1
齐天大圣
  • 1,169
  • 5
  • 15
  • 36

2 Answers2

0

I don't think there neccesarily is an 'idiomatic way'. Using just Hashes vs custom domain objects each has pro's and con's. Custom domain objects (a class to represent each node type) are probably better, but take more work to implement.

Parslet is one easy to use ruby library for parsing and creating AST's. Although beware Parslet is kind of slow, and shouldn't be used where performance matters. I think Parslet by default will give you an AST as hashes, but if you set it up right you can get custom domain objects.

Hashes are mostly just used because they are easy to implement, I think in all other regards they are probably worse. Hashes are just a shortcut. But one often used in ruby, sure.

There isn't neccesarily any consensus "ruby" way to do it. Using a separate class for every type of sub-expression would be considered 'more object oriented'. It may or may not be faster or slower performance than using hashes. It will probably take more work to implement, but may not either.

jrochkind
  • 22,799
  • 12
  • 59
  • 74
0

Ruby 2.6 adds RubyVM::AST module

https://blog.bigbinary.com/2018/10/02/ruby-2-6-adds-rubyvm-ast-module.html

  • 1
    Welcome to StackOverflow. You should improve your answer. SO aims to collect high quality answers that can be a long term help for the community and this kind of answer does not really help. You can look at [How do I write a good answer](https://stackoverflow.com/help/how-to-answer) to try to improve your answer. – Alain Merigot Jan 28 '19 at 22:03
  • Good morning, welcome too! The blog is pretty great, I recommend reading it through - there’s lots of goodies to learn :) – Edward Withers Apr 17 '20 at 07:57