词法分析。
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;
else
return false;
}
public boolean isLetter(char ch){
if(((ch>='A')&&(ch<='Z'))||((ch>='a')&&(ch<='z')))
return true;
else
return 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="";//清空word
word=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;
}
}