Hunter McMillen
Hunter McMillen

Reputation: 61512

Cleaning up Ruby code

I am writing a parser and throughout my code in various methods I have code very similar to this:

    if @sym.type == TokenType::IDENT_TOKEN
      next_token()
      if @sym.type == TokenType::EQUALS_TOKEN
        next_token()
        if @sym.type == TokenType::NUMERAL_TOKEN
          next_token()
          const_a(keys | ConstList.follow)
        else
          error(keys | ConstA.first)
        end
      else
        error(keys | ConstA.first)
      end
    else
      error(keys | ConstA.first)
    end 

This is hard to read in my opinion and looks very cluttered, it is not idiomatic Ruby code at all. Is there some way that I could condense this down and make it less cluttered?

Any help would be appreciated.

Upvotes: 2

Views: 188

Answers (2)

DigitalRoss
DigitalRoss

Reputation: 146063

Well, you could collapse all of the error method calls into one call by doing a next or return after the successful parse and then falling through to a single error.

I think also that you should just accept a certain amount of code explosion when writing a recursive descent parser. That's just kind of what they look like.

You could include some constant-definition modules to get rid of the scope qualifiers.

Upvotes: 2

tadman
tadman

Reputation: 211580

You would probably be able to clean this up immensely if you applied the state machine pattern. Not only would it be easier to read, but you could produce a diagram of the flow through your parser with the right tools.

That's how tools like Ragel build parsers.

Upvotes: 2

Related Questions