中间代码生成-编译原理-Java实现

这篇博客探讨了如何使用Java实现编译原理中的中间代码生成过程,包括四元式、三元式和逆波兰式的详细解释,并提供了主函数的示例。程序运行结果良好,欢迎对代码进行测试和提出问题。
摘要由CSDN通过智能技术生成

四元式:

class Four {
	public Four(String text) {
		sb = new StringBuffer();
		this.text = text;
		str = this.text.toCharArray();
		
		toBeSolute = str;
	}
	String getResult () {
		return sb.toString() ;
	}

	StringBuffer getStringBuffer() {
		return sb;
		
	}
	public static final int MAX = 100;
	
	StringBuffer sb;

	int m = 0, sum = 0;// sum用于计算运算符的个数

	// m用于标记输入表达式中字符的个数
	String text = new String("");

	char JG = 'A';

	char[] toBeSolute;

	char[] str = new char[MAX];// 用于存输入表达式

	int token = 0;// 左括号的标志

	/** *********用于更改计算后数组中的值************* */
	void change(int e) {

		int f = e + 2;
		char ch = str[f];
		if (ch >= 'A' && ch <= 'Z') {
			for (int l = 0; l < str.length; l++) {
				if (str[l] == ch)
					str[l] = JG;
			}
		}

		if (str[e] >= 'A' && str[e] <= 'Z') {
			for (int i = 0; i < m; i++) {
				if (str[i] == str[e])
					str[i] = JG;
			}
		}

	}

	void chengchuchuli(int i, int m) {

		i++;
		for (; i <= m - 1; i++)// 处理乘除运算
		{
			if (str[i] == '*' || str[i] == '/') {

				System.out.println("("+(char)(JG+32)+")"+"(" + str[i] + ",  " + str[i - 1] + ",  "
						+ str[i + 1] + ",  " + JG + ")");
				sb.append("("+(char)(JG+32)+")"+"(" + str[i] + ",  " + str[i - 1] + ",  "
						+ str[i + 1] + ",  " + JG + ")"+"\n");
				change(i - 1);
				str[i - 1] = str[i] = str[i + 1] = JG;
				sum--;
				JG++;
			}
		}
	}

	void jiajianchuli(int j, int m) {
		j++;
		for (; j <= m - 1; j++)// 处理加减运算
		{
			if (str[j] == '+' || str[j] == '-') {
				System.out.println("("+(char)(JG+32)+")"+"(" + str[j] + ",  " + str[j - 1] + ",  "
						+ str[j + 1] + ",  " + JG + ")");
				sb.append("("+(char)(JG+32)+")"+"(" + str[j] + ",  " + str[j - 1] + ",  "
						+ str[j + 1] + ",  " + JG + ")"+"\n");
				change(j - 1);
				str[j - 1] = str[j] = str[j + 1] = JG;
				sum--;
				JG++;
			}

		}
	}

	/* 扫描一遍从文件中读入表达式 */
	void scan() {
		int[] p = new int[MAX];
		char ch = 'a';
		int c = -1, q = 0;
		for (int i = 0; i < toBeSolute.length; i++) {
			
			ch = toBeSolute[i];

			str[m++] = ch;

			if (ch == '=' || ch == '+' || ch == '-' || ch == '*' || ch == '/')
				sum++;

			else if (ch == '(') {
				p[++c] = m - 1;

			} else if (ch == ')') {
				q = m - 1;
				chengchuchuli(p[c], q);// 从左括号处理到又括号
				jiajianchuli(p[c], q);
				JG--;
				str[p[c]] = str[m - 1] = JG;
				c--;
				JG++;

			}
		}
	}

	/* 对表达是进行处理并输出部分四元式 */
	void siyuanshi() {

		for (int i = 0; i <= m - 1; i++)// 处理乘除运算
		{
			if (str[i] == '*' || str[i] == '/') {

				System.out.println("("+(char)(JG+32)+")"+"(
  • 3
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值