public static void Analysis(ref AST ast, List <Token> tokenList, bool showStageResult) { List <Grammar> grammarList = getGrammer(); //获取语法 //获取非终结符List List <string> unterminatorList = getUntermiatorList(grammarList); //获取可空的非终结符List List <string> nullableUnterminatorList = getNullableUnTerminatorList(grammarList, unterminatorList); //获取First字典 Dictionary <string, List <string> > firstDicForUnterminator = getFirstDicForUnterminator(grammarList, nullableUnterminatorList); //非终结符 Dictionary <Grammar, List <string> > firstDicForGrammar = getFirstDicForGrammar(grammarList, nullableUnterminatorList, firstDicForUnterminator); //语法 //获取Follow字典 Dictionary <string, List <string> > followDic = getFollowDic(grammarList, unterminatorList, nullableUnterminatorList, firstDicForUnterminator); //根据first字典和follow字典获取语法分析表 SyntacticTbl syntacticTbl = new SyntacticTbl(firstDicForGrammar, followDic, unterminatorList); //输出结果 if (showStageResult) { showResult(grammarList, unterminatorList, nullableUnterminatorList, firstDicForUnterminator, firstDicForGrammar, followDic); } //主处理 try { process(ast, tokenList, syntacticTbl); } catch (MccBaseException e) { throw e; } }
/// <summary> /// 主处理程序 /// </summary> /// <param name="ast"></param> /// <param name="tokenList"></param> /// <param name="syntacticTbl"></param> private static void process(AST ast, List <Token> tokenList, SyntacticTbl syntacticTbl) { Stack <string> analysisStack = new Stack <string>(); //分析栈 analysisStack.Push("$"); //语法结束符号入栈 tokenList.Add(new SystemWordToken("$", 0)); //向token串的尾部添加语法结束符号 analysisStack.Push("program"); int i = 0; //输入缓冲区指向当前符号的指针 Token curToken = tokenList[i]; string stackPeak; while ((analysisStack.Count != 0) && (i != tokenList.Count)) { curToken = tokenList[i]; stackPeak = analysisStack.Pop(); if (isTerminator(stackPeak)) { if (stackPeak == curToken.Name) { i++; } else { throw (new SyntacticAnalysisException(curToken.Name, curToken.LineNo, new Exception())); } } else { if (stackPeak == "$") { if (stackPeak == curToken.Name) { i++; Console.WriteLine(); Console.WriteLine("语法分析完成,未发现语法错误!"); break; } else { throw (new SyntacticAnalysisException(curToken.Name, curToken.LineNo, new Exception())); } } else { Grammar grammar = syntacticTbl.getGrammar(stackPeak, curToken.Name); if (grammar != null) { if (!(grammar.Right.Count == 1 && grammar.Right[0] == "EMPTY")) { for (int j = grammar.Right.Count - 1; j >= 0; j--) { analysisStack.Push(grammar.Right[j]); } } } else { throw (new SyntacticAnalysisException(curToken.Name, curToken.LineNo, new Exception())); } } } } if ((analysisStack.Count != 0) || (i != tokenList.Count)) { throw (new SyntacticAnalysisException(curToken.Name, curToken.LineNo, new Exception())); } }