如何编写简单的解析器if和while语句? [英] How to write simple parser for if and while statements?

查看:176
本文介绍了如何编写简单的解析器if和while语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要写一个简单的解析器,将令牌转换为​​分析器树。
我已经写了LexicalAnalyzer返回令牌。现在,我想
编写规则if和while语句(开头),这样我就可以通过这个规则解析器和它会创建一个树。
,所以我需要写的方式解析器,所以我可以写新的规则。

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.

您可以告诉我我怎么能在C#中实现它?你能给我一些例子吗?

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

推荐答案

在一个递归下降解析器很容易,如果你有正常的块来执行这些语句和表达分析器。在伪代码,他们基本上是:

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

void ParseWhile()
{
  Parse("while");
  Parse("(");
  ParseExpression();
  Parse(")");
  ParseBlock();
}

这篇关于如何编写简单的解析器if和while语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆