实验一表达式翻译器一、实验目的构造一个中缀表达式到后缀表达式的翻译器,初步了解递归下降语法分析原理及语法制导翻译的过程。二、实验内容1.表达式文法及其翻译模式定义如下:exprexpr+term{print(‘+’)}|expr-term{print(‘-’)}|termtermterm*factor{print(‘*’)}|term/factor{print(‘/’)}|factorfactor(expr)|id{print(id.lexeme)}|num{print(num.value)}2.说明:1)num为无符号整数;2)在后缀形式输出时,为了能区分每个单词,单词之间用空格间隔。例如,输入a+18*b输出:a18b*+3)考虑简单的报错,包括:id名非法、num非法、非法字符、缺少操作数、括号不匹配等。三、算法思想主要使用递归下降法,为了避免左递归,要进行消除左递归1、根据表达式文法,建立三个非终止符的函数四、源代码importjava.io.IOException;importjava.io.PushbackInputStream;publicclassPostfix{/***@paramargs*@throwsIOException*/publicstaticvoidmain(String[]args)throwsIOException{//TODOAuto-generatedmethodstubExpressionexpression=newExpression();expression.tran();}}classExpression{staticintlookahead;PushbackInputStreampushbackInputStream=newPushbackInputStream(newPushbackInputStream(System.in));publicExpression()throwsIOException{lookahead=pushbackInputStream.read();}publicvoidtran()throwsIOException{expr();if(lookahead!=13){thrownewError((char)lookahead+syntaxerror);}}publicvoidexpr()throwsIOException{term();expr_rest();}publicvoidexpr_rest()throwsIOException{if(lookahead=='+'){match('+');term();System.out.print(+);expr_rest();}elseif(lookahead=='-'){match('-');term();System.out.print(-);expr_rest();}else{}}publicvoidterm()throwsIOException{factor();term_rest();}publicvoidterm_rest()throwsIOException{if(lookahead=='*'){match('*');factor();System.out.print(*);term_rest();}elseif(lookahead=='/'){match('/');factor();System.out.print(/);term_rest();}else{}}publicvoidfactor()throwsIOException{intnum=0;if(Character.isDigit((char)lookahead)){while(Character.isDigit((char)lookahead)){num=num*10+lookahead-'0';match(lookahead);}if(lookahead!='+'&&lookahead!='-'&&lookahead!='*'&&lookahead!='/'&&lookahead!=13&&lookahead!=')'){thrownewError(num非法);}System.out.print(num+);}elseif((lookahead='a'&&lookahead='z')||(lookahead='A'&&lookahead='Z')){Stringstr=;while((lookahead='a'&&lookahead='z')||(lookahead='A'&&lookahead='Z')||(lookahead='1'&&lookahead='9')||(lookahead=='_')){str=str+(char)lookahead;match(lookahead);}if(lookahead!='+'&&lookahead!='-'&&lookahead!='*'&&lookahead!='/'&&lookahead!=13&&lookahead!=')'){thrownewError(id名非法);}System.out.print(str+);}elseif((char)lookahead=='('){match(lookahead);expr();if(!match(')')){thrownewError(括号不匹配);}}elseif((char)lookahead==')'){thrownewError(括号不匹配);}else{thrownewError((char)lookahead+syntaxerror);}}publicbooleanmatch(intt)throwsIOException{if(lookahead==t){lookahead=pushbackInputStream.read();returntrue;}else{returnfalse;}}}