How to write simple parser for if and while statements? [closed]

你说的曾经没有我的故事 提交于 2019-12-02 14:22:51

问题


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?


回答1:


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();
}


来源:https://stackoverflow.com/questions/7294238/how-to-write-simple-parser-for-if-and-while-statements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!