编译原理——赋值语句和简单表达式(四)

来源:互联网 发布:高仿商城javaweb源码 编辑:程序博客网 时间:2024/06/05 10:19

词法分析。

Lexical.java:

package per.eyuan.compile;import per.eyuan.util.*;public class Lexical {String statement;//输入的待分析的语句String word="";//保存识别出的字符ConstantTable cont;//常数表,存放Num对象实例TwoItemStack tis;//二元式栈IdentifierTable idt;//标志符表public boolean isDigit(char ch){if((ch>='0')&&(ch<='9'))return true;elsereturn false;}public boolean isLetter(char ch){if(((ch>='A')&&(ch<='Z'))||((ch>='a')&&(ch<='z')))return true;elsereturn false;}//标志符处理,识别关键字,普通标志符入栈public void letter(String id){int j=0;for(;j<idt.getCount();j++){if(idt.getId(j).getName().equals(id)){//标识符表中已有//加入到二元式tis.push(new TwoItem("id",j+""));//跳出循环j=idt.getCount();}}if(j==idt.getCount()){//标识符表中没有System.out.println("错误:标志符为声明");}}public void digit(String num){//常数处理,常数入栈int j=0;for(;j<cont.getCount();j++){if(cont.getConstant(j).getValue().equals(num)){//常数表中已有tis.push(new TwoItem("num",j+""));j=cont.getCount();}}if(j==cont.getCount()){//常数表中没有cont.addConstant(num);tis.push(new TwoItem("num",cont.getCount()+""));}}public void analyse(){//转换for(int i=0;i<statement.length();i++){char ch=statement.charAt(i);if(isDigit(ch)){//num,整型数据,不考虑小数点word="";word+=ch;for(int j=i+1;j<statement.length()-i;j++){if(!isDigit(statement.charAt(j))){//不是数字i=j-1;j=statement.length();}else{//是数字word+=statement.charAt(j);}}digit(word);}else if(isLetter(ch)){//id,字母开头,包含字母或者数字word="";//清空wordword=word+ch;int j=i+1;while(isLetter(statement.charAt(j))||isDigit(statement.charAt(j))){word=word+statement.charAt(j);j++;}letter(word);i=j-1;}else if(ch=='='){tis.push(new TwoItem("=","-"));}else if(ch=='+'){tis.push(new TwoItem("+","-"));}else if(ch=='*'){tis.push(new TwoItem("*","-"));}else if(ch=='('){tis.push(new TwoItem("(","-"));}else if(ch==')'){tis.push(new TwoItem("-",")"));}else if(ch==','){tis.push(new TwoItem(",","-"));}else if(ch==';'){tis.push(new TwoItem(";","-"));}}}//获取待分析句子public void setStatement(String statement) {this.statement = statement;}public void setIdt(IdentifierTable idt) {//设定标识符表this.idt = idt;}public void setTis(TwoItemStack tis) {this.tis = tis;}}


 

原创粉丝点击