コード例 #1
0
ファイル: Parser.java プロジェクト: djherold0/Compiler
 /**
  * This is the reduce implementation
  *
  * @param rule the rule to reduce by
  */
 private void reduce(int rule) throws SyntaxError {
   // get the rule number to reduce by
   int num = Math.abs(rule);
   // this section is for generating code
   if (num == 27 || num == 28 || num == 29 || num == 30 || num == 31 || num == 32 || num == 33
       || num == 37 || num == 39 || num == 41) {
     gen.reduce(num);
   }
   // popping empty from the stack, just push
   if (GrammarTable.grammar[num].length != 1) {
     // start popping and matching stuff
     int input = 0;
     for (int i = GrammarTable.grammar[num].length - 1; i > 0; i--) {
       stack.pop();
       input = stack.pop();
       if (GrammarTable.grammar[num][i] == input) {
         continue;
       } else {
         throw new SyntaxError("Syntax error in source file on line " + scanner.getLine());
       }
     }
   }
   // push the LHS
   curState = stack.peek();
   // push the left hand side
   stack.push(GrammarTable.getRule(num)[0]);
   curState = pTable.getNextState(curState, GrammarTable.getRule(num)[0]);
   stack.push(curState);
 }
コード例 #2
0
ファイル: Parser.java プロジェクト: djherold0/Compiler
 /**
  * Parse the input file
  *
  * @return true if the input is a part of the language, false if it is not
  */
 public boolean parse() {
   pTable = new ParseTable();
   boolean notFound = true;
   curState = stack.peek();
   Token next = null;
   int nextState;
   String name = "";
   try {
     while (notFound) {
       next = scanner.scan();
       nextState = pTable.getNextState(curState, next.getP());
       if (nextState == 9999) {
         System.err.println("Error in parsing on line " + scanner.getLine());
         return false;
       } // next state is negative, reduce
       else if (nextState < 0) {
         while (nextState < 0) {
           reduce(nextState);
           nextState = pTable.getNextState(curState, next.getP());
         }
         shift(nextState, next.getP());
         curState = nextState;
       } // next state is positive and not a goto, shift
       else if (nextState > 0) { // took out && nextState < 100
         shift(nextState, next.getP());
         curState = nextState;
       } // next state is accept (only happens in state 6)
       if (nextState == 6) {
         gen.reduce(0);
         return true;
       }
       if (curState == 9999) {
         System.err.println("Error state reached while parsing.");
         System.err.println("Error on line: " + scanner.getLine());
         return false;
       }
     }
   } catch (java.io.IOException ie) {
     ie.printStackTrace();
   } catch (SyntaxError ex) {
     System.err.println("Syntax Error on line " + scanner.getLine() + " while parsing.");
     return false;
   } catch (compiler.CScanner.MaxIDSizeError me) {
     System.err.println(me.getMessage());
     return false;
   }
   return false;
 }