while (count <= txtList.size()) { var line = txtList.get(count - 1); int index = 0; // 这里是用index结合CharAt进行搭配,对每行的每个元素进行遍历 while (index < line.length()) { var ch = line.charAt(index); if (Character.isWhitespace(ch)) { index++; }
// 识别常量数字 elseif (Character.isDigit(ch)) { var startIndex = index++; ch = line.charAt(index); while (Character.isDigit(ch)) { index++; ch = line.charAt(index); } String s = line.substring(startIndex, index); var tokenKind = TokenKind.fromString("IntConst"); tokens.add(Token.normal(tokenKind, s)); }
elseif (Character.isAlphabetic(ch)) { // 先把串读进来,再去看是标识符还是关键字 var startIndex = index++; ch = line.charAt(index); while (Character.isAlphabetic(ch) | Character.isDigit(ch)) { index++; ch = line.charAt(index); } String s = line.substring(startIndex, index);
// 如果是关键字 if (TokenKind.isAllowed(s)) { var tokenKind = TokenKind.fromString(s); tokens.add(Token.simple(tokenKind)); // 在标识符表中 } else { var tokenKind = TokenKind.fromString("id"); tokens.add(Token.normal(tokenKind, s));
// 将id类型的变量存入到符号表中 if (!symbolTable.has(s)){ symbolTable.add(s); }
while(1): if(ACTION[s,a] = ActionKind.Shift t): push t-> status stack push a -> symbol stack a <- next input token callWhenInShift // output the grammar? elif(ACTION[s,a] = reduce(A->B)): status stackand symbol stack pop Production.body.size() 个元素 push GOTO[t, A] -> status stack a <- next input token callWhenInReduce elif(ACTION[s,a] = accept): callWhenInAccept break
publicvoidrun(){ // TODO: 实现驱动程序 // 你需要根据上面的输入来实现 LR 语法分析的驱动程序 // 请分别在遇到 Shift, Reduce, Accept 的时候调用上面的 callWhenInShift, callWhenInReduce, callWhenInAccept // 否则用于为实验二打分的产生式输出可能不会正常工作 Stack<Status> statusStack = new Stack<Status>(); Stack<Term> symbolStack = new Stack<Term>();
//初始化 Status s = lrtable.getInit(); Action ACTION = null; TokenKind a = null; NonTerminal A = null; List<Term> B = null; int count = 0; statusStack.push(s);
while(true){ if(count <= input_tokens.size()-1){ a = input_tokens.get(count); }else { a = input_tokens.get(input_tokens.size()-1); } s = statusStack.peek(); // 获取当前步骤的状态 ACTION = s.getAction(a);
if (ACTION.equals(Action.error())){ System.out.println("error!"); break; }