視頻與PR:https://github.com/terrajobst/minsk/blob/master/docs/episode-01.md 作者是 Immo Landwerth(https://twitter.com/terrajobst),微軟 .NET 團隊的項目經理。 這一集主要內容是一 ...
視頻與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