语法分析器 Java版

想了解更多内容,移步至编译原理专栏​​​​​​​

编译原理实验二,语法分析器

本文章中用到的代码中缺失的部分需要参考我的上一篇文章,词法分析器 Java版,

因为语法分析器是建立在词法分析器的基础之上的

原文链接https://blog.csdn.net/godelgnis/article/details/83218139

package codescanner;

import java.util.ArrayList;

public class IrParser {

	private Analyzer analyzer;
	private ArrayList list = new ArrayList<>();
	private Word word;
	private int index = 0; // 从列表中获取单词的下标
	private boolean error = false;

	public IrParser() {
		analyzer = new Analyzer("input.txt", "output.txt");
		analyzer.analyze(analyzer.getContent());
		list = analyzer.getList();
	}

	public void parse() {
		word = getNext(list);
		if (word.getTypenum() == 1) {
			word = getNext(list);
			pretreatment();
			if (word.getTypenum() == 6) {
				word = getNext(list);
				if (word.getTypenum() == 0 && !error) {
					System.out.println("success");
				}

			} else {
				if (!error) {
					error = true;
					System.out.println("缺end错误");
				}
			}
		}else {
			error = true;
			System.out.println("begin错误");
		}
	}

	public void pretreatment() {
		statement();
		while (word.getTypenum() == 26) {
			word = getNext(list);
			statement();
		}
	}

	public void statement() {
		if (word.getTypenum() == 10) {
			word = getNext(list);
			if (word.getTypenum() == 18) {
				word = getNext(list);
				expression();
			} else {
				error = true;
				System.out.println("赋值号错误");
			}
		} else {
			error = true;
			System.out.println("语句错误");
		}
	}

	public void expression() {
		term();
		while (word.getTypenum() == 13 || word.getTypenum() == 14) {
			word = getNext(list);
			term();
		}
	}

	public void term() {
		factor();
		while (word.getTypenum() == 15 || word.getTypenum() == 16) {
			word = getNext(list);
			factor();
		}
	}

	public void factor() {
		if (word.getTypenum() == 10 || word.getTypenum() == 11) {
			word = getNext(list);
		} else if (word.getTypenum() == 27) {
			word = getNext(list);
			expression();
			if (word.getTypenum() == 28) {
				word = getNext(list);
			} else {
				error = true;
				System.out.println("')'错误");
			}
		} else {
			error = true;
			System.out.println("表达式错误");
		}
	}

	public Word getNext(ArrayList list) {
		if (index < list.size()) {
			return list.get(index++);
		} else {
			return null;
		}
	}

	public int getIndex() {
		return index;
	}

	public void setIndex(int index) {
		this.index = index;
	}

	public static void main(String[] args) {
		IrParser parser = new IrParser();
		parser.parse();
	}
}

测试数据

//正确测试例子
//begin a:=9; x:=2*3; b:=a+x end #

//缺begin错误
//x:=a+b*c end #

//缺end错误
//begin x:=a+b*c #

//表达式错误
//begin a:=; x:=2*3; b:=a+x end #

//赋值符号错误
//begin a==9; x:=2*3; b:=a+x end #

//')'错误
//begin a:=9; x:=2*3; b:=(a+x*c end #

//语句错误
//begin if a>0 then a:=1 end #

一次只能测试一个错误,测试之前需要先把对应代码的注释去掉

词法分析起有去除注释的功能

本语法分析器分析的是以begin开头,以end结尾,以#作为文件结束符号的赋值语句

如果赋值语句错误,会给出相应的错误依据

各位看官我觉得写得还阔以,可以给我点个赞呀

你可能感兴趣的:(编译原理)