0

I need to write a simple parser that will convert the tokens to parser tree. I've already wrote LexicalAnalyzer that returns the tokens. Now, I want to write rules for "if and while" statements(for the beginning), so I could pass this rules to parser and it will create a tree. So i need to write the parser in the way, so I could write new rules.

Can you advise me how I can implement it in C#? Can you give me some example?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
theateist
  • 13,879
  • 17
  • 69
  • 109
  • I read all kind pseudo, but have no idea how to start implement this. I saw the definition like a:b | c, c: terminal. If i understood this correctly, this means rules, but how to implement or maybe i am in wrong way – theateist Sep 03 '11 at 16:22

1 Answers1

4

In a recursive descent parser it's easy to implement these statements if you have the normal block and expression parsers. In pseudo-code, they are basically:

void ParseIf()
{
  Match("if");
  Match("(");
  ParseExpression();
  Match(")");
  ParseBlock();
}

and

void ParseWhile()
{
  Parse("while");
  Parse("(");
  ParseExpression();
  Parse(")");
  ParseBlock();
}
Blindy
  • 65,249
  • 10
  • 91
  • 131
  • Can you please specify what Match, MatchExpression,Parse, ParseBlock mean? – theateist Sep 03 '11 at 16:25
  • `Match` basically reads the token you give it and ignores it, it's to make sure it's there. The other two parse expressions and blocks respectively. – Blindy Sep 03 '11 at 16:25