public SyntaxTree Parse(TokenList tokenList) { LRParsingMap parsingMap = GetParsingMap(); RegulationList grammar = GetGrammar(); //TODO:这个convertor以后是可以配置的。 var tokenTypeConvertor = new TokenType2TreeNodeType(); var context = new ParsingContext(tokenList, grammar, parsingMap, tokenTypeConvertor); while (context.CurrentTokenIndex < context.TokenList.Count + 1) { PrintParsingProgress(context); TreeNodeType nodeType = context.CurrentNodeType(); int stateId = context.StateIdStack.Peek(); LRParsingAction action = parsingMap.GetAction(stateId, nodeType); int currentTokenIndex = action.Execute(context); context.CurrentTokenIndex = currentTokenIndex; } PrintLastState(context); if (context.TreeStack.Count > 0) { return(context.TreeStack.Peek()); } else { return(new SyntaxTree()); } }
public override int Execute(ParsingContext context) { Regulation regulation = context.Grammar[RegulationId - 1]; var newNode = new SyntaxTree(); int tokenCount = 0; int count = regulation.RightPart.Count(); for (int i = 0; i < count; i++) { var item = context.TreeStack.Pop(); context.StateIdStack.Pop();//只弹出,不再使用。 newNode.Children.Insert(0, item); item.Parent = newNode; tokenCount += item.MappedTokenLength; if (i == 0) { newNode.MappedTokenStartIndex = item.MappedTokenStartIndex; } } newNode.MappedTokenLength = tokenCount; newNode.MappedTotalTokenList = context.TokenList; newNode.NodeType = regulation.Left; context.TreeStack.Push(newNode); int stateId = context.StateIdStack.Peek(); LRParsingAction gotoAction = context.ParsingMap.GetAction(stateId, regulation.Left); gotoAction.Execute(context); return(context.CurrentTokenIndex); }