Skip to content

Instantly share code, notes, and snippets.

@kellypleahy
Forked from anonymous/prefix parser.cs
Created November 14, 2009 23:52
Show Gist options
  • Select an option

  • Save kellypleahy/234866 to your computer and use it in GitHub Desktop.

Select an option

Save kellypleahy/234866 to your computer and use it in GitHub Desktop.
// field _LookAhead
Node Operand()
{
Node ret;
if(matches(TokenId.Identifier))
{
ret = new Node()
{
Value = _LookAhead.TokenText,
// no Children
};
match(TokenId.Identifier);
}
else
ret = Expr();
return ret;
}
Node Expr()
{
Node ret;
if(matches(TokenId.Plus, TokenId.Minus, TokenId.Star, TokenId.Slash))
{
ret = new Node()
{
Value = _LookAhead.TokenText,
};
match(TokenId.Plus, TokenId.Minus, ...);
ret.Children.Add(Operand());
ret.Children.Add(Operand());
}
else if(matches(TokenId.Sqrt))
{
ret = new Node()
{
Value = _LookAhead.TokenText,
};
match(TokenId.Sqrt);
ret.Children.Add(Operand());
}
else
match(TokenId.Plus, TokenId.Minus, ..., TokenId.Sqrt); // just to get a good error message!
// NOTE! we won't get here if match we didn't find one of +,-,*,/,r - match will throw.
return ret;
}
// "matches" should verify that the lookahead is one of the list provided
// as its argument. If it is, it should return true. otherwise false.
// "match" should verify that the lookahead is one of the list provided
// as its argument. It should consume the token if it matches, and set
// the lookahead to the next token from the string. If it doesn't match
// it should throw and give a message that the parse failed while expecting
// one of the tokens passed as the argument (in a normal parser).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment