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.
Well, you could collapse all of the
errormethod calls into one call by doing anextorreturnafter 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
includesome constant-definition modules to get rid of the scope qualifiers.