📄 parser.java
字号:
/* * To change this template, choose Tools | Templates * and open the template in the editor. */package parser;import exceptions.*;import scanner.*;import symbols.*;import java.util.*;import java.io.*;/** * * @author Beeven */public class parser { scanner sc=new scanner(); Token token; Terminal lookahead; ArrayList<Expr> stack=new ArrayList<Expr>(); String Input; public parser(String in) { Input=in; } Terminal getTopMostTerminal() { int post=stack.size()-1; while(true) { Expr e=stack.get(post); if(e instanceof Terminal) return (Terminal)e; else post--; } } double accept() throws TypeMismatchedException { Expr e=stack.get(stack.size()-1); if(e instanceof BoolExpr) throw new TypeMismatchedException(); return ((ArithExpr)e).value; } void reduce() throws ExpressionException { Terminal t=getTopMostTerminal(); TerminalReduce tr; switch(t.type) { case Type.num: tr=new T_NUM(); tr.reduce(stack); break; case Type.bool: tr=new T_BOOL(); tr.reduce(stack); break; case Type.addminus: tr=new T_ADDMINUS(); tr.reduce(stack); break; case Type.muldiv: tr=new T_MULDIV(); tr.reduce(stack); break; case Type.not: tr=new T_NOT(); tr.reduce(stack); break; case Type.neg: tr=new T_NEG(); tr.reduce(stack); break; case Type.power: tr=new T_POWER(); tr.reduce(stack); break; case Type.and: case Type.or: tr=new T_ANDOR(); tr.reduce(stack); break; case Type.relation: tr=new T_RELATION(); tr.reduce(stack); break; case Type.colon: tr=new T_COLON(); tr.reduce(stack); break; case Type.rp: tr=new T_RP(); tr.reduce(stack); break; } } /** * Parse the token list get from scanner * @return the parsing result. * @throws java.io.IOException * @throws exceptions.ExpressionException */ public double parse() throws IOException,ExpressionException{ if(Input.isEmpty()) throw new EmptyExpressionException(); stack.add(new Terminal()); // put a $ in the stack ByteArrayInputStream bin=new ByteArrayInputStream(Input.getBytes()); System.setIn(bin); token=sc.scan(); lookahead=new Terminal(token); while(true) { Terminal topMostTerminal=getTopMostTerminal(); switch(OPPTable.table[topMostTerminal.type][lookahead.type]) { case 2: // accept System.setIn(new FileInputStream(FileDescriptor.in)); return accept(); case 1: //reduce reduce(); break; case 0: // shift stack.add(lookahead); token=sc.scan(); lookahead=new Terminal(token); break; case -1: throw new MissingOperatorException(); case -2: throw new MissingRightParenthesisException(); case -3: throw new MissingLeftParenthesisException(); case -4: throw new FunctionCallException(); case -5: throw new TypeMismatchedException(); case -6: throw new MissingOperandException(); case -7: throw new TrinaryOperationException(); } } } }
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -