笔记 - C#从头开始构建编译器 - 1
程序员文章站
2022-04-09 18:01:00
视频与PR:https://github.com/terrajobst/minsk/blob/master/docs/episode-01.md 作者是 Immo Landwerth(https://twitter.com/terrajobst),微软 .NET 团队的项目经理。 这一集主要内容是一 ......
视频与pr:
作者是 immo landwerth(https://twitter.com/terrajobst),微软 .net 团队的项目经理。
这一集主要内容是一个原始的递归下降 parser。
思路:
1.lexer
(1) enum syntaxkind
(2) abstract class syntaxnode
(3) class syntaxtoken : syntaxnode
(4) class lexer
2.expression
(1) abstract class expressionsyntax : syntaxnode
(2) sealed class numberexpressionsyntax : expressionsyntax
(3) sealed class binaryepressionsyntax : expressionsyntax
(4) sealed class parenthesizedexpressionsyntax : expressionsyntax
3.parser
(1) sealed class syntaxtree
(2) class parser
处理优先级的技巧:
public expressionsyntax parseterm()
{
var left = parsefactor();
while (current.kind == syntaxkind.plustoken || current.kind == syntaxkind.minustoekn)
{
var operatortoken = nexttoken();
var right = parsefactor();
left = new binaryepressionsyntax(left, operatortoken, right);
}
return left;
}
public expressionsyntax parsefactor()
{
var left = parseprimaryexpression();
while (current.kind == syntaxkind.startoken || current.kind == syntaxkind.slashtoken)
{
var operatortoken = nexttoken();
var right = parseprimaryexpression();
left = new binaryepressionsyntax(left, operatortoken, right);
}
return left;
}
4.evaluator
(1) class evaluator
5. 其他
比如诊断信息等
c#语言点:
1.public override ienumerable<syntaxnode> getchildren() => enumerable.empty<syntaxnode>();
2.yield