视频与PR:https://github.com/terrajobst/minsk/blob/master/docs/episode-01.md
作者是 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
原文:https://www.cnblogs.com/wqyu/p/10807005.html