1 /* 2 * LR(1) 语法分析 3 */ 4 #include <stdio.h> 5 #include <stdlib.h> 6 #include <string.h> 7 8 #include "Common.h" 9 #include "LRCal.h" 10 #include "LRMigrate.h" 11 #include "Stack.h" 12 13 #define NEXTWORD(s) ((*(s)==0)?SYM_EOF:*((s)++)) 14 15 extern char *Grammer[]; 16 17 void LRParse(struct LRElement **LRTable, unsigned char *InputString) 18 { 19 printf("-------- Parse --------\n"); 20 struct Stack *SymbolStack = BuildStack(1024); 21 Push(SymbolStack, 0); // push $; 22 Push(SymbolStack, 0); // push start state s0; 23 int Word = NEXTWORD(InputString); // word <- NextWord(); 24 int State = 0; 25 while (true) // while (true) 26 { 27 State = Top(SymbolStack); // state <- top of stack; 28 printf("State: %d\tWord: %c \t", State, Word); 29 if (LRTable[State][Word].Action == Reduce) // if (Action[state, word] = "reduce A->β") 30 { 31 printf("reduce %d", (int)LRTable[State][Word].ActionValue); 32 33 char *Production = Grammer[LRTable[State][Word].ActionValue - 1]; 34 int ProductSize = strlen(Production) - 1; 35 // pop 2*|β| symbols; 36 ProductSize *= 2; 37 while (ProductSize--) 38 { 39 Pop(SymbolStack); 40 } 41 // state <- top of stack; 42 State = Top(SymbolStack); 43 // push A; 44 int LeftUnterminal = (int)Production[0]; 45 Push(SymbolStack, LeftUnterminal); 46 // push Goto[State, A]; 47 Push(SymbolStack, (int)LRTable[State][LeftUnterminal].ActionValue); 48 } 49 else if (LRTable[State][Word].Action == Shift) // else if (Action[state, word] = "shift si") 50 { 51 printf("shift %d", (int)LRTable[State][Word].ActionValue); 52 // push word; 53 Push(SymbolStack, Word); 54 // push si; 55 Push(SymbolStack, LRTable[State][Word].ActionValue); 56 // word <- NextWord(); 57 Word = NEXTWORD(InputString); 58 } 59 else if (LRTable[State][Word].Action == Accept) // else if (Action[state, word] = "accept") 60 { 61 printf("accept\n"); 62 break; 63 } 64 else 65 { 66 printf("Syntax Error!\n"); 67 exit(3); 68 } 69 printf("\n"); 70 } 71 printf("Grammer Parse Success!\n"); 72 }
全部代码文件:https://files.cnblogs.com/rexfield/LR.zip