编写一个程序实现LR(1)项目集及状态转换图构造、LR(1)分析表构造、并实现在利用LR(1)分析表分析字符串同时生成逆波兰式

时间: 2023-09-15 08:24:31 浏览: 45
以下是一个基于Java实现的LR(1)语法分析程序,包括LR(1)项目集及状态转换图构造、LR(1)分析表构造和利用LR(1)分析表分析字符串同时生成逆波兰式的功能。程序中使用了JavaCC工具生成LR(1)语法分析器。 LR1Parser.jj: ``` options { STATIC = false; } PARSER_BEGIN(LR1Parser) package com.example.lr1parser; import java.util.*; PARSER_END(LR1Parser) // Define terminals TOKEN : { <PLUS: "+"> | <MINUS: "-"> | <TIMES: "*"> | <DIV: "/"> | <LPAREN: "("> | <RPAREN: ")"> | <NUM: (["0"-"9"])+> } // Define non-terminals void start() : {} { expression() } void expression() : {} { term() ( <PLUS> term() )* } void term() : {} { factor() ( <TIMES> factor() )* } void factor() : {} { <NUM> | <LPAREN> expression() <RPAREN> } // Define LR(1) items List<Item> items = new ArrayList<Item>(); Item startItem = new Item(new Production("S", "E"), 0, "$"); items.add(startItem); // Define LR(1) item set Set<ItemSet> itemSetSet = new HashSet<ItemSet>(); // Define LR(1) transition table Map<ItemSet, Map<String, ItemSet>> transitionTable = new HashMap<ItemSet, Map<String, ItemSet>>(); // Define LR(1) action table Map<ItemSet, Map<String, Action>> actionTable = new HashMap<ItemSet, Map<String, Action>>(); // Define LR(1) goto table Map<ItemSet, Map<String, ItemSet>> gotoTable = new HashMap<ItemSet, Map<String, ItemSet>>(); // Define stack for parsing Stack<ItemSet> stack = new Stack<ItemSet>(); Stack<String> input = new Stack<String>(); // Define output queue for reverse polish notation Queue<String> outputQueue = new LinkedList<String>(); // Define state counter for generating state IDs int stateCounter = 0; // Define action types enum ActionType { SHIFT, REDUCE, ACCEPT, ERROR } // Define action class Action { ActionType type; int stateOrProduction; public Action(ActionType type, int stateOrProduction) { this.type = type; this.stateOrProduction = stateOrProduction; } } // Define item class Item { Production production; int dot; String lookahead; public Item(Production production, int dot, String lookahead) { this.production = production; this.dot = dot; this.lookahead = lookahead; } public boolean isReduceItem() { return dot == production.getRight().size(); } public String getNextSymbol() { if (isReduceItem()) { return null; } return production.getRight().get(dot); } public Item getNextItem() { if (isReduceItem()) { return null; } return new Item(production, dot + 1, lookahead); } public String toString() { StringBuilder sb = new StringBuilder(); sb.append(production.getLeft()); sb.append(" ->"); for (int i = 0; i < production.getRight().size(); i++) { if (i == dot) { sb.append(" ."); } sb.append(" "); sb.append(production.getRight().get(i)); } if (dot == production.getRight().size()) { sb.append(" ."); } sb.append(", "); sb.append(lookahead); return sb.toString(); } } // Define item set class ItemSet { int id; Set<Item> items = new HashSet<Item>(); public ItemSet() { this.id = stateCounter++; } public ItemSet(Set<Item> items) { this.id = stateCounter++; this.items = items; } public void addItem(Item item) { items.add(item); } public Set<String> getLookaheads(String symbol) { Set<String> lookaheads = new HashSet<String>(); for (Item item : items) { if (!item.isReduceItem() && item.getNextSymbol().equals(symbol)) { lookaheads.add(item.lookahead); } } return lookaheads; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("I" + id + ":\n"); for (Item item : items) { sb.append(" " + item + "\n"); } return sb.toString(); } } // Define production class Production { String left; List<String> right; public Production(String left, String... right) { this.left = left; this.right = Arrays.asList(right); } public String getLeft() { return left; } public List<String> getRight() { return right; } public boolean isNullable() { for (String symbol : right) { if (!isNullable(symbol)) { return false; } } return true; } public static boolean isNullable(String symbol) { return symbol.equals("$") || symbol.equals("ε"); } public String toString() { StringBuilder sb = new StringBuilder(); sb.append(left); sb.append(" ->"); for (String symbol : right) { sb.append(" "); sb.append(symbol); } return sb.toString(); } } // Generate LR(1) items void generateItems() { for (Production production : Productions.productions) { for (int i = 0; i <= production.getRight().size(); i++) { for (String lookahead : Productions.first(production.getRight().subList(i, production.getRight().size()))) { Item item = new Item(production, i, lookahead); items.add(item); } } } } // Generate LR(1) item set closure ItemSet closure(ItemSet itemSet) { ItemSet closure = new ItemSet(itemSet.items); boolean changed = true; while (changed) { changed = false; Set<Item> newItems = new HashSet<Item>(); for (Item item : closure.items) { String nextSymbol = item.getNextSymbol(); if (nextSymbol != null) { for (Item i : items) { if (i.production.getLeft().equals(nextSymbol) && Productions.first(i.production.getRight()).contains(item.lookahead)) { Item newItem = new Item(i.production, 0, item.lookahead); if (!closure.items.contains(newItem)) { newItems.add(newItem); } } } } } if (!newItems.isEmpty()) { closure.items.addAll(newItems); changed = true; } } return closure; } // Generate LR(1) item set goto ItemSet goTo(ItemSet itemSet, String symbol) { Set<Item> newItems = new HashSet<Item>(); for (Item item : itemSet.items) { String nextSymbol = item.getNextSymbol(); if (nextSymbol != null && nextSymbol.equals(symbol)) { newItems.add(item.getNextItem()); } } return closure(new ItemSet(newItems)); } // Generate LR(1) item set family void generateItemSetFamily() { ItemSet startItemSet = closure(new ItemSet(Collections.singleton(startItem))); itemSetSet.add(startItemSet); boolean changed = true; while (changed) { changed = false; Set<ItemSet> newSets = new HashSet<ItemSet>(); for (ItemSet itemSet : itemSetSet) { for (String symbol : Productions.getAllSymbols()) { ItemSet newItemSet = goTo(itemSet, symbol); if (!newItemSet.items.isEmpty() && !itemSetSet.contains(newItemSet)) { newSets.add(newItemSet); changed = true; } } } if (!newSets.isEmpty()) { itemSetSet.addAll(newSets); } } } // Generate LR(1) transition table void generateTransitionTable() { for (ItemSet itemSet : itemSetSet) { Map<String, ItemSet> transitionMap = new HashMap<String, ItemSet>(); for (String symbol : Productions.getAllSymbols()) { ItemSet newItemSet = goTo(itemSet, symbol); if (!newItemSet.items.isEmpty()) { transitionMap.put(symbol, newItemSet); } } transitionTable.put(itemSet, transitionMap); } } // Generate LR(1) action table void generateActionTable() { for (ItemSet itemSet : itemSetSet) { Map<String, Action> actionMap = new HashMap<String, Action>(); for (Item item : itemSet.items) { if (item.isReduceItem()) { if (item.production.getLeft().equals("S")) { actionMap.put("$", new Action(ActionType.ACCEPT, 0)); } else { for (String lookahead : Productions.follow(item.production.getLeft())) { actionMap.put(lookahead, new Action(ActionType.REDUCE, Productions.getProductionIndex(item.production))); } } } else { String nextSymbol = item.getNextSymbol(); if (nextSymbol != null) { ItemSet nextStateSet = transitionTable.get(itemSet).get(nextSymbol); actionMap.put(nextSymbol, new Action(ActionType.SHIFT, nextStateSet.id)); } } } for (String symbol : Productions.getAllSymbols()) { if (!actionMap.containsKey(symbol)) { actionMap.put(symbol, new Action(ActionType.ERROR, -1)); } } actionTable.put(itemSet, actionMap); } } // Generate LR(1) goto table void generateGotoTable() { for (ItemSet itemSet : itemSetSet) { Map<String, ItemSet> gotoMap = new HashMap<String, ItemSet>(); for (String symbol : Productions.getAllNonTerminals()) { ItemSet newItemSet = goTo(itemSet, symbol); if (!newItemSet.items.isEmpty()) { gotoMap.put(symbol, newItemSet); } } gotoTable.put(itemSet, gotoMap); } } // Parse input string and generate reverse polish notation void parse(String inputStr) { stack.clear(); input.clear(); outputQueue.clear(); stack.push(itemSetSet.iterator().next()); input.push("$"); for (int i = inputStr.length() - 1; i >= 0; i--) { input.push(String.valueOf(inputStr.charAt(i))); } while (true) { ItemSet state = stack.peek(); String symbol = input.peek(); Action action = actionTable.get(state).get(symbol); switch (action.type) { case SHIFT: stack.push(transitionTable.get(state).get(symbol)); input.pop();

相关推荐

最新推荐

recommend-type

编译原理课程设计 LR(0)分析表和分析器的构造和程序实现

1. 对任意给定的文法 ,完成识别文法活前缀的 、 的状态转化矩阵及 项目集规范族的构造; 2. 判断该文法是否为 文法,实现 分析表的构造,并输出到指定文件中; 3. 实现 分析器总控程序,对输入的表达式进行文法分析...
recommend-type

LR(1)语法分析 编译器 项目集构造课程设计

LR(1)语法分析 编译器 项目集构造……不错的程序,可以实现的语法分析……
recommend-type

编译原理LR(1)自动构造,自动分析输入语句

LR(1)分析表自动构造程序的实现,对...设计内容及要求:对任意给定的文法G构造LR(1)项目集规范族(要求实现CLOSURE(I)、GO(I,X)、FIRST;然后实现LR(1)分析表构造算法。构造并输出其LR(1)分析表。由分析表分析输入语句
recommend-type

编译原理课程设计-LR(1)语法分析模拟构造器的设计

其中LR(0)分析器是在分析过程中不需要向右查看输入符号的,因而它对文法的限制较大,但是它是构造LR类分析器的基础。对于是否是LR(0)文法,可以通过查看是否存在两类冲突来判定,而需要的是判定功能,所以用项目集...
recommend-type

4 实验四:LR分析程序的设计与实现

1、了解LR(0)分析方法是严格的从左向右扫描,和自底向上的语法分析方法。 2、掌握LR(0)语法分析方法。
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

2. 通过python绘制y=e-xsin(2πx)图像

可以使用matplotlib库来绘制这个函数的图像。以下是一段示例代码: ```python import numpy as np import matplotlib.pyplot as plt def func(x): return np.exp(-x) * np.sin(2 * np.pi * x) x = np.linspace(0, 5, 500) y = func(x) plt.plot(x, y) plt.xlabel('x') plt.ylabel('y') plt.title('y = e^{-x} sin(2πx)') plt.show() ``` 运行这段
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。