编译原理—小型(简化)高级语言分析器前端(Java)

实现一个一遍扫描的编译前端,将简化高级语言的部分语法成分(含赋值语句、分支语句、循环语句等)翻译成四元式(或三地址代码),还要求有合理的语法出错报错和错误恢复功能。

测试样例

beginwhile a<b doif c<5beginwhile x>ybeginz:=x+1;enda:=2; b:=4;c:=c-1;area:=3.14*a*a;s:=2*3.1416*r*(h+r);end
endend
#

测试结果
词法分析程序
从文件中读取程序

(1, begin)
(4, while)
(10, a)
(20, <)
(10, b)
(5, do)
(2, if)
(10, c)
(20, <)
(11, 5)
(1, begin)
(4, while)
(10, x)
(23, >)
(10, y)
(1, begin)
(10, z)
(18, :=)
(10, x)
(13, +)
(11, 1)
(26, ; )
(6, end)
(10, a)
(18, :=)
(11, 2)
(26, ; )
(10, b)
(18, :=)
(11, 4)
(26, ; )
(10, c)
(18, :=)
(10, c)
(14, -)
(11, 1)
(26, ; )
(10, area)
(18, :=)
(11, 3.14)
(15, *)
(10, a)
(15, *)
(10, a)
(26, ; )
(10, s)
(18, :=)
(11, 2)
(15, *)
(11, 3.1416)
(15, *)
(10, r)
(15, *)
(27, ()
(10, h)
(13, +)
(10, r)
(28, ))
(26, ; )
(6, end)
(6, end)
(6, end)
(0, #)
=词法分析完成=
语法分析中…,请稍候
error!--------缺少开头符号begin,程序第4行出现语法错误
error!--------不是符号then,程序第5行出现语法错误
error!--------不是符号do,程序第7行出现语法错误
=词法分析完成=
语法分析完成,共检查出3个语法错误

=中间代码生成结果=
0:if a < b goto 2
1:goto 22
2:if c < 5 goto 4
3:goto 21
4:if x > y goto 6
5:goto 9
6:t1 = x + 1
7:z = t1
8:goto 4
9:a = 2
10:b = 4
11:t2 = c - 1
12:c = t2
13:t3 = 3.14 * a
14:t4 = t3 * a
15:area = t4
16:t5 = 2 * 3.1416
17:t6 = t5 * r
18:t7 = h + r
19:t8 = t6 * t7
20:s = t8
21:goto 0

语义分析

public class Element {String times;String data1;String op;String data2;String type;public void setInteger(Integer integer) {this.integer = integer;}Integer integer;Element(String times,String data1,String op,String data2) {//=this.times = times;this.data1 = data1;this.op = op;this.data2 = data2;}Element(String times,String data1,String op,String data2,Integer integer) {//if gotothis.times = times;this.data1 = data1;this.op = op;this.data2 = data2;this.integer=integer;}Element(Integer integer) {//if gotothis.integer=integer;}Element() {//if goto}
}

public class SemanticAnalysis {static  int j=0,t=1;static List<Element> elements = new ArrayList<Element>();static void memset(String times,String data1,String op,String data2) {Element e = new Element(times,data1,op,data2);elements.add(e);}public static String expression() { // 表达式String times,data1,op,data2;data1 = term();while(analyzer.llist.get(j).equals("+") || analyzer.llist.get(j).equals("-")) {// 当前单词为+、-if(analyzer.llist.get(j).equals("+")) // +op = "+";else // -op = "-";j++;data2 = term();times = "t" + (t++);memset(times,data1,op,data2);data1 = times;}return data1;}private static String term() { // 项String times,data1,op,data2;data1 = factor();while(analyzer.llist.get(j).equals("*") || analyzer.llist.get(j).equals("/") ) { // 当前单词为*、/if(analyzer.llist.get(j).equals("*")) // *op = "*";else // /op = "/";j++;data2 = factor();times = "t" + (t++);memset(times,data1,op,data2);data1 = times;}return data1;}private static String factor() { // 因子String data = "";if(analyzer.map2.get(analyzer.llist.get(j)) == 10) { // IDdata = analyzer.llist.get(j);j++;} else if(analyzer.map2.get(analyzer.llist.get(j)) == 11) { // NUMdata = analyzer.llist.get(j);j++;}else if(analyzer.llist.get(j).equals("(")) { // 左括号j++;data = expression();if(analyzer.llist.get(j).equals(")"))j++;} else {System.out.println("Error,表达式错误");}return data;}}

语法分析


public class GrammarAnalysis {static char[] s = new char[100];static int sing;static int i; //用来记录数组s中的下标;static int error = 0;static void P() {if (Objects.equals(analyzer.llist.get(i), "begin")) {++i;int cur = analyzer.map.get(i);S();
//处理if (Objects.equals(analyzer.llist.get(i), "end")) {++i;} else {System.out.println("error!--------不是结尾符号end," + "程序第" + analyzer.map.get(i) + "行出现语法错误");error++;++i;}} else {System.out.println("error!--------缺少开头符号begin," + "程序第" + analyzer.map.get(i) + "行出现语法错误");error++;S();
//处理if (Objects.equals(analyzer.llist.get(i), "end")) {++i;} else {System.out.println("error!--------不是结尾符号end," + "程序第" + analyzer.map.get(i) + "行出现语法错误");error++;++i;}}}static void B() {i++;D();int cur = SemanticAnalysis.elements.size();SemanticAnalysis.elements.add(new Element());//thenif (!analyzer.llist.get(i).equals("then")) {System.out.println("error!--------不是符号then," + "程序第" + analyzer.map.get(i) + "行出现语法错误");error++;} elsei++;P();SemanticAnalysis.elements.get(cur).setInteger(SemanticAnalysis.elements.size());//elsei--;}static void C() {i++;D();int cur = SemanticAnalysis.elements.size();SemanticAnalysis.elements.add(new Element());//doif (!analyzer.llist.get(i).equals("do")) {System.out.println("error!--------不是符号do," + "程序第" + analyzer.map.get(i) + "行出现语法错误");error++;} elsei++;P();SemanticAnalysis.elements.add(new Element(cur - 1));SemanticAnalysis.elements.get(cur).setInteger(SemanticAnalysis.elements.size());i--;}static void D() {String data1, data2, op;SemanticAnalysis.j = i;;data1 = SemanticAnalysis.expression();//表达式E();op = analyzer.llist.get(i);//<|<=....i++;SemanticAnalysis.j = i;data2 = SemanticAnalysis.expression();//表达式SemanticAnalysis.elements.add(new Element("if", data1, op, data2, SemanticAnalysis.elements.size() + 2));E();}static void S() {if (analyzer.map2.get(analyzer.llist.get(i)) == 10)A();else if (analyzer.llist.get(i).equals("while"))C();else if (analyzer.llist.get(i).equals("if")) {B();}i++;S1();// if(s[i]!='e') {// }
/*                if(Objects.equals(analyzer.llist.get(i), ";")) {}else {System.out.println("error!-----------缺少结尾符号;"+",程序第"+analyzer.map.get(i)+"行出现语法错误");error++;++i;S1();}*/}static void S1() {if (i < analyzer.llist.size() && !Objects.equals(analyzer.llist.get(i), "end")) {// ++i;S();}}static void A() {if (i + 1 < analyzer.llist.size() && Objects.equals(analyzer.llist.get(i + 1), ":=")) {String times = analyzer.llist.get(i), data1;SemanticAnalysis.j = i;SemanticAnalysis.j += 2;data1 = SemanticAnalysis.expression();//表达式SemanticAnalysis.memset(times, data1, "", "");++i;++i;E();if (Objects.equals(analyzer.llist.get(i), ")") || Objects.equals(analyzer.llist.get(i), ";")) {if (Objects.equals(analyzer.llist.get(i), ")")) {++i;}} else {System.out.println("error!--------不是结尾符号;或者)" + ",程序第" + analyzer.map.get(i) + analyzer.llist.get(i) + "行出现语法错误");error++;++i;}} else {System.out.println("error!---------不是赋值语句" + ",程序第" + analyzer.map.get(i) + "行出现语法错误");error++;++i;++i;E();if (Objects.equals(analyzer.llist.get(i), ")") || Objects.equals(analyzer.llist.get(i), ";")) {if (Objects.equals(analyzer.llist.get(i), ")")) {++i;}} else {System.out.println("error!--------不是结尾符号;或者)" + ",程序第" + analyzer.map.get(i) + "行出现语法错误");error++;++i;}}}static void E() {T();/*  if(Objects.equals(analyzer.llist.get(i), "+") || Objects.equals(analyzer.llist.get(i), "-") || Objects.equals(analyzer.llist.get(i), ";") || Objects.equals(analyzer.llist.get(i), ")")) {*/E1();/*            }else {System.out.println("error!-----------不是结尾符号+或者-或者;或者)"+",程序第"+analyzer.map.get(i)+"行出现语法错误"); error++;E1();}*/}static void T() {F();if (Objects.equals(analyzer.llist.get(i), "+") || Objects.equals(analyzer.llist.get(i), "-") || Objects.equals(analyzer.llist.get(i), ";") || Objects.equals(analyzer.llist.get(i), ")") || Objects.equals(analyzer.llist.get(i), "*") || Objects.equals(analyzer.llist.get(i), "/")) {T1();}}static void F() {if (Objects.equals(analyzer.llist.get(i), "(")) {++i;E();} else {++i;}}static void T1() {if (Objects.equals(analyzer.llist.get(i), "*")) {++i;F();T1();} else if (Objects.equals(analyzer.llist.get(i), "/")) {++i;F();T1();}}static void E1() {if (Objects.equals(analyzer.llist.get(i), "+")) {++i;T();E1();} else if (Objects.equals(analyzer.llist.get(i), "-")) {++i;T();E1();}}public static void main(String[] args) {Scanner sc = new Scanner(System.in);System.out.println("==词法分析程序==");System.out.println("从文件中读取程序");System.out.println("==============");analyzer.initToken();analyzer.ReadFile1();System.out.println("语法分析中....,请稍候");i = 0;sing = 0;if (Objects.equals(analyzer.llist.get(0), "#")) System.exit(-1);P();if (Objects.equals(analyzer.llist.get(i), "#")) {} else {System.out.println("error!-------不是结尾符号#" + analyzer.llist.get(i) + i);error++;}System.out.println("===词法分析完成===");System.out.println("语法分析完成,共检查出" + error + "个语法错误");System.out.println("\n===中间代码生成结果===");for (int i = 0; i < SemanticAnalysis.elements.size(); i++) {Element e = SemanticAnalysis.elements.get(i);if (e.times == null)System.out.println(i + ":" + "goto  " + e.integer);else if (e.times.equals("if"))System.out.println(i + ":" + e.times + " " + e.data1 + " " + e.op + " " + e.data2 + "  goto  " + e.integer);elseSystem.out.println(i + ":" + e.times + " = " + e.data1 + " " + e.op + " " + e.data2);}}}

词法分析

public class analyzer {public static List<String> llist=new ArrayList<>();static  Map<Integer,Integer> map=new HashMap<>();static  Map<String,Integer> map2=new HashMap<>();final static String ID = "\\p{Alpha}(\\p{Alpha}|\\d)*";static  int countLine=1;/** 整形常数 NUM >> 正则表达式*/final static String NUM = "\\d\\d*";final static  String regex = "^-?([1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*|0?\\.0+|0)$";/** token 词法单元* <词符号, 种别码> *//** 关键字 token*/static Map<String, Integer> TOKEN_KEYWORDS;/** 运算符/界符 token */static Map<String, Integer> TOKEN_OPERATOR_BOUNDARY;/** 其他单词 token*/static Map<String, Integer> TOKEN_ID_SUM;/** 文件根目录*/static final String ROOT_DIRECTORY = "program.txt";/*** 初始化 token 单元*/public static void initToken(){//种别码创建TOKEN_KEYWORDS = new HashMap<String, Integer>(){//关键字{put("begin", 1);put("if", 2);put("then", 3);put("while", 4);put("do", 5);put("end", 6);}};TOKEN_OPERATOR_BOUNDARY= new HashMap<String, Integer>(){//运算符和界符{put("+", 13);put("-", 14);put("*", 15);put("/", 16);put(":", 17);put(":=", 18);put("<", 20);put("<>", 21);put("<=", 22);put(">", 23);put(">=", 24);put("=", 25);put(";", 26);put("(", 27);put(")", 28);put("#", 0);}};TOKEN_ID_SUM= new HashMap<String, Integer>(){//标识符和整型常数{put(ID, 10);put(NUM, 11);}};}/*** 读 源程序 文件*/public static void ReadFile1() {FileInputStream fis = null;InputStreamReader isr = null;BufferedReader br = null;try {fis = new FileInputStream(ROOT_DIRECTORY);isr = new InputStreamReader(fis, "UTF-8"); // 转化类br = new BufferedReader(isr); // 装饰类String line;/** 记录 程序 行数 */while ((line = br.readLine()) != null) {  // 每次读取一行,分析一行boolean answer = lexicalAnalysis(line);if(answer == false){System.out.printf("ERROR 编译错误=== 第 %d 行出现 词法错误 \n", countLine);break;}countLine++;}System.out.printf("===词法分析完成===\n");} catch (Exception ex) {ex.printStackTrace();} finally {try {br.close(); // 关闭最后一个类,会将所有的底层流都关闭} catch (Exception ex) {ex.printStackTrace();}}}/** 判断key是否是其他单词*/private static boolean isIDOrSUM(String key){if (key.matches(ID) ) {llist.add(key);map.put(llist.size()-1,countLine);map2.put(key,TOKEN_ID_SUM.get(ID));System.out.printf("(%d, %s)\n", TOKEN_ID_SUM.get(ID), key);}else if (key.matches(NUM)||key.matches(regex)) {llist.add(key);map.put(llist.size()-1,countLine);map2.put(key,TOKEN_ID_SUM.get(NUM));System.out.printf("(%d, %s)\n", TOKEN_ID_SUM.get(NUM), key);}else {return false;}return true;}/*** 进行 词法分析* @param word 要分析的字符串* @return 结果*/public static boolean  lexicalAnalysis(String word){word = word.trim(); // 去首尾空格String[] strings = word.split("\\p{Space}+"); // 分割字符串,保证处理的字符串没有空格for (String string : strings) {/** 3种情况:*      1. 关键字 == end (关键字的后面一定是空格 )*      2. 运算符/ 分界符 == continue*      3. 其他单词 == continue*/String key = "";for (int i = 0; i < string.length(); i++){String indexChar = String.valueOf(string.charAt(i)) ;if(i+1<string.length()){if((indexChar+string.charAt(i+1)).equals("//"))return true;}/** 是 运算符 或者 关键字*/if (TOKEN_OPERATOR_BOUNDARY.containsKey(indexChar) ||TOKEN_KEYWORDS.containsKey(string.substring(i, string.length()))){if (key.length() > 0) {if (isIDOrSUM(key) == false) {/** 词法错误 */return false;}key = "";}if(TOKEN_OPERATOR_BOUNDARY.containsKey(indexChar)) {/**  1. 是 运算符/分界符 */key += indexChar;if(i + 1 < string.length() && TOKEN_OPERATOR_BOUNDARY.containsKey(indexChar + string.charAt(i+1))){ // 运算分界符key += string.charAt(++i);}llist.add(key);map.put(llist.size()-1,countLine);map2.put(key,TOKEN_OPERATOR_BOUNDARY.get(key));System.out.printf("(%d, %s)\n",TOKEN_OPERATOR_BOUNDARY.get(key),key);key = "";}else if(TOKEN_KEYWORDS.containsKey(key = string.substring(i, string.length()))) {/** 2. 是关键字*/llist.add(key);map.put(llist.size()-1,countLine);map2.put(key,TOKEN_KEYWORDS.get(key));System.out.printf("(%d, %s)\n",TOKEN_KEYWORDS.get(key),key);key = "";break;}}else {/** 是其他单词*/key += indexChar;/** 其他单词后面是 1. 换行,2. 运算符/界符 3. 其他单词*/if(i+1 >= string.length()){if (isIDOrSUM(key) == false) {/** 词法错误 */return false;}}}}}return true;}public analyzer() {}public static void main(String[] args) {initToken();System.out.println("==词法分析程序==");System.out.println("从文件中读取程序");System.out.println("==============");ReadFile1(); for(String s:llist) System.out.println(s);System.out.println();}}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/392125.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

linux boot菜单列表,Bootstrap 下拉菜单(Dropdowns)简介

Bootstrap 下拉菜单是可切换的&#xff0c;是以列表格式显示链接的上下文菜单。这可以通过与 下拉菜单(Dropdown) JavaScript 插件 的互动来实现。如需使用下拉菜单&#xff0c;只需要在 class .dropdown 内加上下拉菜单即可。下面的实例演示了基本的下拉菜单&#xff1a;实例主…

dynamodb管理ttl_如何使用DynamoDB TTL和Lambda安排临时任务

dynamodb管理ttlby Yan Cui崔燕 如何使用DynamoDB TTL和Lambda安排临时任务 (How to schedule ad-hoc tasks with DynamoDB TTL and Lambda) CloudWatch Events let you easily create cron jobs with Lambda. However, it’s not designed for running lots of ad-hoc tasks,…

5g创业的构想_数据科学项目的五个具体构想

5g创业的构想Do you want to enter the data science world? Congratulations! That’s (still) the right choice.您想进入数据科学世界吗&#xff1f; 恭喜你&#xff01; 那(仍然)是正确的选择。 The market currently gets tougher. So, you must be mentally prepared f…

Microsoft Windows Phone 7 Toolkit Silverlight SDK XNA Game Studio 4.0 开发工具套件正式版下载...

Windows Phone 7开发工具套件包括Visual Studio 2010 Express for Windows Phone、Windows Phone模拟器、Expression Blend 4 for Windows Phone、XNA Game Studio 4.0和新增加的必应地图SDK。 英文版的光盘镜像&#xff1a;点击下载 文档中心&#xff1a;Windows Phone develo…

数据挖掘—Apriori算法(Java实现)

算法描述 &#xff08;1&#xff09;扫描全部数据&#xff0c;产生候选1-项集的集合C1&#xff1b; &#xff08;2&#xff09;根据最小支持度&#xff0c;由候选1-项集的集合C1产生频繁1-项集的集合L1&#xff1b; &#xff08;3&#xff09;对k>1&#xff0c;重复执行步骤…

怎么汇报一周开发工作情况_如何在没有经验的情况下获得第一份开发人员工作

怎么汇报一周开发工作情况Whether you’ve done a coding bootcamp or taught yourself, getting your first developer job with only a few months of coding under your belt is hard.无论您是完成了编码训练营还是自学了&#xff0c;仅靠几个月的编码就很难拿到第一份开发人…

vue.js的认知

Vue.js&#xff08;读音 /vjuː/, 类似于 view&#xff09; 是一套构建用户界面的渐进式框架。 Vue 只关注视图层&#xff0c; 采用自底向上增量开发的设计。 Vue 的目标是通过尽可能简单的 API 实现响应的数据绑定和组合的视图组件。 Vue 学习起来非常简单&#xff0c;。转载于…

c语言中的无符号字节,C语言之有符号数和无符号数

我们知道&#xff0c;在C语言中存在无符号数和有符号数(一些高级语言如Java里面是没有无符号数的)&#xff0c;但是对于计算机而言&#xff0c;其本身并不区别有符号数和无符号数&#xff0c;因为在计算机里面都是0或者1&#xff0c;但是在我们的实际使用中有时候需要使用有符号…

8种排序算法比较

8种排序算法&#xff0c;各算法名称见下表或见源码。运行程序时&#xff0c;将需要你输入一数值&#xff0c;以确定对多少随机数进行排序。然后将会显示各排序算法的耗时。并且你可选择时否进行正序和反序测试。 由于水平有限&#xff0c;可能存在一些错误&#xff0c;还请各位…

两个问题,关于XP进程优化及SVSP虚拟存储平台

这两个问题让我有点头痛&#xff0c;是Boss这阵子布置给我的&#xff0c;都一段时间了&#xff0c;我还是没找出合适的解决方案来答复Boss.第一个问题是&#xff1a;查查X200或X61中的进程&#xff0c;看哪些是可以不要的&#xff0c;停掉&#xff0c;但又不影响用户使用。&…

数据挖掘—朴素贝叶斯分类算法(Java实现)

算法描述 &#xff08;1&#xff09;扫描训练样本数据集&#xff0c;分别统计训练集中类别 Ci 的个数 Di 和属于类别Ci 的样本中属性Ak取值Xk为 Dik 的实例样本个数&#xff0c;构成统计表&#xff1b; &#xff08;2&#xff09;计算先验概率和条件概率&#xff0c;构成概率表…

net core 获取网站目录

AppContext.BaseDirectory 获取项目的根目录转载于:https://www.cnblogs.com/zxs-onestar/p/7147265.html

泰晤士报下载_《泰晤士报》和《星期日泰晤士报》新闻编辑室中具有指标的冒险活动-第1部分:问题

泰晤士报下载TLDR: Designing metrics that help you make better decisions is hard. In The Times and The Sunday Times newsrooms, we have spent a lot of time trying to tackle three particular problems.TLDR &#xff1a;设计度量标准以帮助您做出更好的决策非常困难…

速度一半永远追不上_您将永远不会知道自己应该怎么做的一半-没关系。

速度一半永远追不上by Ken Gilb肯吉尔伯(Ken Gilb) 您将永远不会知道自己应该怎么做的一半-没关系。 (You will never know half of what you think you should — and that’s ok.) Impostor syndrome is a real thing in software development. After 20 years in the indus…

c语言自学门槛,初学C语言的人最常问的几个问题

初学C语言的人最常问的几个问题C语言是一门通用计算机编程语言&#xff0c;应用广泛。对于新手来说学习C语言并不是那么容易&#xff0c;下面是C语言初学者最常问的几个问题&#xff0c;欢迎阅读!1.多久能学会编程?这是一个没有答案的问题。每个人投入的时间、学习效率和基础都…

背景消除的魔力

图片的功能非常强大&#xff0c;有一图胜千言的效果&#xff0c;所以在文档或演示文稿中使用图片来增加趣味性是一种很棒的想法。但问题是&#xff0c;图片通常会变为文字中间的独立矩形&#xff0c;而不是真正与内容融合在一起。您可以在图片中放置边框或效果&#xff0c;使其…

Puppet 之 模板和模块

1 概述模板文件是在puppet模块下面templates目录中以”.erb”结尾的文件&#xff0c;puppet模板主要用于文件&#xff0c;例如各种服务的配置文件&#xff0c;相同的服务&#xff0c;不同的配置就可以考虑使用模板文件。模块是Puppet自包含的代码和数据集合。绝大多数的清单都…

java异步io_Java中的异步IO与异步请求处理

java异步ioIn this article, I am trying to explain the difference between Async-IO and Async-Request processing in the HTTP request in the Java world.在本文中&#xff0c;我试图解释Java世界中HTTP请求中Async-IO和Async-Request处理之间的区别。 In the pre-Java …

异常检测机器学习_使用机器学习检测异常

异常检测机器学习什么是异常检测&#xff1f; (What is Anomaly Detection?) The anomaly detection problem has been a problem that has been frequently explored in the field of machine learning and has become a classic problem. Anomalies are any unusual sequenc…

数据挖掘—BP神经网络(Java实现)

public class Test {public static void main(String args[]) throws Exception {ArrayList<ArrayList<Double>> alllist new ArrayList<ArrayList<Double>>(); // 存放所有数据ArrayList<String> outlist new ArrayList<String>(); // …