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

词法分析。

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;
	}
	
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值