请生成LR(0)语法分析,可以输入压缩了的上下文无关文法,符号串以#结束,可以输出相应的LR(0)分析表,然后输出识别符号串的过程,并输出符号串是否是所输入文法的句子,含主函数,用Python实现

时间: 2024-03-18 14:38:47 浏览: 67
好的,下面是实现的代码,使用了Python的ply库来实现LR(0)语法分析器: ```python import ply.yacc as yacc import ply.lex as lex # 定义文法规则 grammar = """ S : E E : E '+' T | T T : T '*' F | F F : '(' E ')' | 'id' """ # 定义压缩的文法字符串 compressed_grammar = 'S:E;E:E+T|T;T:T*F|F;F:(E)|id' # 定义词法分析器的词汇表 tokens = ['ID', 'PLUS', 'TIMES', 'LPAREN', 'RPAREN'] # 定义词法分析器的正则表达式规则 t_PLUS = r'\+' t_TIMES = r'\*' t_LPAREN = r'\(' t_RPAREN = r'\)' t_ignore = ' \t\n' # ID的规则为字母或下划线开头,后面可以跟字母、下划线或数字 def t_ID(t): r'[a-zA-Z_][a-zA-Z0-9_]*' return t # 定义错误处理函数 def t_error(t): print("Illegal character '%s'" % t.value[0]) t.lexer.skip(1) # 构建词法分析器 lexer = lex.lex() # 解析压缩的文法字符串,生成LR分析表 def build_parser(grammar): # 构建语法分析器 parser = yacc.yacc(method='SLR') # 解析文法规则,生成语法树 grammar_tree = parser.parse(grammar) # 生成LR(0)分析表 lr_table = parser.lr_table return lr_table, grammar_tree # 解析压缩的文法字符串,生成LR分析表和语法树 lr_table, grammar_tree = build_parser(compressed_grammar) # 定义LR分析器的状态类 class LRState: def __init__(self, state_num, items): self.state_num = state_num self.items = items def __hash__(self): return hash(str(self.items)) def __eq__(self, other): return str(self.items) == str(other.items) def __str__(self): return f"I{self.state_num}: {str(self.items)}" # 定义LR分析器的项类 class LRItem: def __init__(self, production, dot_pos): self.production = production self.dot_pos = dot_pos def __eq__(self, other): return self.production == other.production and self.dot_pos == other.dot_pos def __str__(self): prod = self.production.copy() prod.insert(self.dot_pos, ".") return f"{prod}" # 定义LR分析器的项集类 class LRItemSet: def __init__(self, items): self.items = items def __iter__(self): return iter(self.items) def __len__(self): return len(self.items) def __hash__(self): return hash(str(self.items)) def __eq__(self, other): return str(self.items) == str(other.items) def __str__(self): return f"{str(item)}" for item in self.items # 定义LR分析器的文法类 class LRGrammar: def __init__(self, productions): self.productions = productions def __str__(self): return "\n".join(str(p) for p in self.productions) # 获取文法的终结符和非终结符集合 def get_symbols(self): nonterminals = set() terminals = set() for production in self.productions: nonterminals.add(production[0]) for symbol in production[1]: if symbol.islower(): terminals.add(symbol) return nonterminals, terminals # 获取文法的开始符号 def get_start_symbol(self): return self.productions[0][0] # 获取某个符号的FIRST集合 def get_first(self, symbol, nonterminals, terminals): first = set() if symbol in terminals: first.add(symbol) elif symbol in nonterminals: for production in self.productions: if production[0] == symbol: if len(production[1]) == 0: first.add("") elif production[1][0] in terminals: first.add(production[1][0]) else: first.update(self.get_first(production[1][0], nonterminals, terminals)) i = 1 while "" in first and i < len(production[1]): first.remove("") if production[1][i] in terminals: first.add(production[1][i]) break else: first.update(self.get_first(production[1][i], nonterminals, terminals)) i += 1 if "" in first: first.remove("") first.add("") return first # 获取某个符号串的FIRST集合 def get_first_set(self, symbol_str, nonterminals, terminals): first_set = set() i = 0 while i < len(symbol_str): if symbol_str[i] in terminals: first_set.add(symbol_str[i]) break elif symbol_str[i] in nonterminals: first = self.get_first(symbol_str[i], nonterminals, terminals) if "" not in first: first_set.update(first) break else: first_set.update(first - {""}) i += 1 else: break if i == len(symbol_str): first_set.add("") return first_set # 获取某个符号的FOLLOW集合 def get_follow(self, symbol, nonterminals, terminals, first_sets, follow_sets): follow_set = set() if symbol == self.get_start_symbol(): follow_set.add("#") for production in self.productions: for i in range(len(production[1])): if production[1][i] == symbol: if i == len(production[1]) - 1: if symbol != production[0]: if production[0] in follow_sets: follow_set.update(follow_sets[production[0]]) else: follow_set.update(self.get_follow(production[0], nonterminals, terminals, first_sets, follow_sets)) else: first = self.get_first_set(production[1][i+1:], nonterminals, terminals) if "" in first: if symbol != production[0]: if production[0] in follow_sets: follow_set.update(follow_sets[production[0]]) else: follow_set.update(self.get_follow(production[0], nonterminals, terminals, first_sets, follow_sets)) follow_set.update(first - {""}) else: follow_set.update(first) return follow_set # 获取所有符号的FOLLOW集合 def get_follow_sets(self, nonterminals, terminals, first_sets): follow_sets = {} for nonterminal in nonterminals: follow_sets[nonterminal] = set() follow_sets[self.get_start_symbol()].add("#") while True: follow_sets_new = follow_sets.copy() for production in self.productions: for i in range(len(production[1])): if production[1][i] in nonterminals: first = self.get_first_set(production[1][i+1:], nonterminals, terminals) follow = follow_sets[production[1][i]] if "" in first: follow_sets_new[production[1][i]].update(follow) follow_sets_new[production[1][i]].update(first - {""}) if follow_sets_new == follow_sets: break follow_sets = follow_sets_new return follow_sets # 获取某个状态的闭包 def get_closure(self, item_set): closure = item_set.copy() while True: closure_new = closure.copy() for item in closure: if item.dot_pos < len(item.production[1]) and item.production[1][item.dot_pos] in nonterminals: for production in self.productions: if production[0] == item.production[1][item.dot_pos]: closure_new.add(LRItem(production, 0)) if closure_new == closure: break closure = closure_new return closure # 获取某个状态的GOTO集合 def get_goto(self, item_set, symbol): goto = set() for item in item_set: if item.dot_pos < len(item.production[1]) and item.production[1][item.dot_pos] == symbol: goto.add(LRItem(item.production, item.dot_pos+1)) return self.get_closure(goto) # 获取所有状态和GOTO集合 def get_states(self): states = [] start_item = LRItem(self.productions[0], 0) start_state = LRState(0, self.get_closure({start_item})) states.append(start_state) i = 0 while i < len(states): state = states[i] i += 1 for symbol in all_symbols: goto = self.get_goto(state.items, symbol) if len(goto) > 0 and goto not in [s.items for s in states]: new_state = LRState(len(states), goto) states.append(new_state) lr_table[new_state.state_num] = {} for s in goto: if s.dot_pos == len(s.production[1]): if s.production == self.productions[0]: lr_table[state.state_num][s.production[0]] = ("acc", None) else: for j in range(len(self.productions)): if self.productions[j] == s.production: lr_table[state.state_num][s.production[0]] = ("r", j) break elif s.production[1][s.dot_pos] in terminals: next_state = self.get_goto(goto, s.production[1][s.dot_pos]) for j in range(len(states)): if states[j].items == next_state: lr_table[state.state_num][s.production[1][s.dot_pos]] = ("s", j) break elif s.production[1][s.dot_pos] in nonterminals: next_state = self.get_goto(goto, s.production[1][s.dot_pos]) for j in range(len(states)): if states[j].items == next_state: lr_table[state.state_num][s.production[1][s.dot_pos]] = ("g", j) break return states # 解析输入的符号串,输出语法分析过程和是否是该文法的句子 def parse(self, input_str): input_str += "#" stack = [0] input_pos = 0 output = [] while True: state = stack[-1] symbol = input_str[input_pos] if symbol not in lr_table[state]: output.append("Error") break action = lr_table[state][symbol] if action[0] == "s": stack.append(symbol) stack.append(action[1]) input_pos += 1 output.append(f"Shift {symbol} and go to state {action[1]}") elif action[0] == "r": production = self.productions[action[1]] for i in range(2 * len(production[1])): stack.pop() state = stack[-1] stack.append(production[0]) stack.append(lr_table[state][production[0]][1]) output.append(f"Reduce using {production[0]} -> {' '.join(production[1])}") elif action[0] == "g": stack.append(symbol) stack.append(action[1]) output.append(f"Go to state {action[1]}") elif action[0] == "acc": output.append("Accept") break return output, output[-1] == "Accept" # 解压缩文法字符串,生成文法规则列表 productions = [] for rule in compressed_grammar.split(";"): head, body = rule.split(":") productions.append((head, body.split("|"))) # 创建文法实例 grammar = LRGrammar(productions) # 获取文法的终结符和非终结符集合 nonterminals, terminals = grammar.get_symbols() all_symbols = nonterminals | terminals # 获取所有符号的FIRST集合和FOLLOW集合 first_sets = {} for symbol in all_symbols: first_sets[symbol] = grammar.get_first(symbol, nonterminals, terminals) follow_sets = grammar.get_follow_sets(nonterminals, terminals, first_sets) # 获取所有状态和GOTO集合 states = grammar.get_states() # 测试语法分析器 input_str = "id + id * id" output, is_valid = grammar.parse(input_str) print(f"Input string: {input_str}") print("".join(f"{s}\n" for s in output)) print(f"Is valid: {is_valid}")
阅读全文

相关推荐

大家在看

recommend-type

Mellanox IB交换机用户手册

这篇文档包含了完整的Mellanox IB安装流程、配置方法和一系列维护和管理的方法。
recommend-type

主生產排程員-SAP主生产排程

主生產排程員 比較實際需求與預測需求,提出預測與MPS的修訂建議。 把預測與訂單資料轉成MPS。 使MPS能配合出貨與庫存預算、行銷計畫、與管理政策。 追蹤MPS階層產品安全庫存的使用、分析MPS項目生產數量和FAS消耗數量之間的差異、將所有的改變資料輸入MPS檔案,以維護MPS。 參加MPS會議、安排議程、事先預想問題、備好可能的解決方案、將可能的衝突搬上檯面。 評估MPS修訂方案。 提供並監控對客戶的交貨承諾。
recommend-type

信息几何-Information Geometry

信息几何是最近几年新的一个研究方向,主要应用于统计分析、控制理论、神经网络、量子力学、信息论等领域。本书为英文版,最为经典。阅读需要一定的英文能力。
recommend-type

FPGBA:FPGA上的GBA

FPGBA FPGA上的GBA 从零开始在FPGA的VHDL中实现GBA。 在适用范围: 所有视频模式,包括仿射和特效 所有声道 另存为GBA 快进(2-4x速度取决于游戏) 使用帧缓冲区进行像素完美缩放 CPU Turbo模式 保存状态 倒带 色彩优化 秘籍引擎 超出范围: 多人游戏功能,例如串行 GBA模块功能(例如,Boktai阳光传感器) 在硬件上调试(VHDL仿真就足够了) 所有外围设备,例如VGA / HDMI,SDRAM,控制器等。 目标板 Terasic DE2-115(完成) Terasic DE-10 Nano(Mister)(完成) Nexys视频(完成) 类比口袋(如果可能越狱的话)-未来的工作 状态: 约1600款游戏经过测试,直到进入游戏: 99%没有重大问题(无崩溃,可玩) FPGA资源使用情况(仅GBA,不带帧缓冲) 37000
recommend-type

Mud Pulse Telemetry Signal Decoding Manual

泥浆脉冲遥传信号编码技术手册

最新推荐

recommend-type

LR(0)语法分析的设计与实现.doc

LR(0)语法分析是一种自底向上的解析技术,用于确定性上下文无关文法(DCFG)。在本实验报告中,重点讲述了LR(0)分析程序的设计与实现,包括了核心概念、算法和分析表的构造。 首先,LR(0)分析的核心在于判断文法...
recommend-type

无人机巡检利器-YOLOv11电力设备缺陷检测与定位优化.pdf

想深入掌握目标检测前沿技术?Yolov11绝对不容错过!作为目标检测领域的新星,Yolov11融合了先进算法与创新架构,具备更快的检测速度、更高的检测精度。它不仅能精准识别各类目标,还在复杂场景下展现出卓越性能。无论是学术研究,还是工业应用,Yolov11都能提供强大助力。阅读我们的技术文章,带你全方位剖析Yolov11,解锁更多技术奥秘!
recommend-type

COMSOL模拟土石混合体孔隙渗流中的细颗粒迁移运动:多场多相介质耦合分析,基于COMSOL模拟的土石混合体孔隙渗流中的细颗粒迁移运动研究,COMSOL孔隙渗流下的细颗粒迁移运动 对土石混合体进行了

COMSOL模拟土石混合体孔隙渗流中的细颗粒迁移运动:多场多相介质耦合分析,基于COMSOL模拟的土石混合体孔隙渗流中的细颗粒迁移运动研究,COMSOL孔隙渗流下的细颗粒迁移运动。 对土石混合体进行了数值仿真,考虑了土石混合体孔隙变化,细颗粒侵蚀,骨架结构变形,此问题是一个多场(渗流场、变形场、应力场、损伤场)多相介质(土颗粒集合体,块石,空隙,孔隙)耦合的复杂问题。 ,COMSOL; 细颗粒迁移; 孔隙渗流; 土石混合体; 多场多相介质耦合。,COMSOL模拟土石混合体多场多相介质渗流与变形耦合效应研究
recommend-type

电力系统11节点无功补偿仿真研究:功率因数和谐波观察,线路阻抗参数可调,基于Matlab2018b及以上版本,电力系统11节点无功补偿仿真研究:功率因数和谐波观察,线路阻抗参数化调整,基于Matlab

电力系统11节点无功补偿仿真研究:功率因数和谐波观察,线路阻抗参数可调,基于Matlab2018b及以上版本,电力系统11节点无功补偿仿真研究:功率因数和谐波观察,线路阻抗参数化调整,基于Matlab 2018b及以上版本,电力系统11个节点无功补偿仿真,功率因数和谐波可观察,线路阻抗参数可改,matlab2018b及以上(可改版) ,电力系统仿真; 无功补偿; 功率因数; 谐波观察; 线路阻抗参数可改; MATLAB2018b及以上,MATLAB仿真平台:电力系统节点无功补偿及功率因数、谐波观测研究
recommend-type

Spring Websocket快速实现与SSMTest实战应用

标题“websocket包”指代的是一个在计算机网络技术中应用广泛的组件或技术包。WebSocket是一种网络通信协议,它提供了浏览器与服务器之间进行全双工通信的能力。具体而言,WebSocket允许服务器主动向客户端推送信息,是实现即时通讯功能的绝佳选择。 描述中提到的“springwebsocket实现代码”,表明该包中的核心内容是基于Spring框架对WebSocket协议的实现。Spring是Java平台上一个非常流行的开源应用框架,提供了全面的编程和配置模型。在Spring中实现WebSocket功能,开发者通常会使用Spring提供的注解和配置类,简化WebSocket服务端的编程工作。使用Spring的WebSocket实现意味着开发者可以利用Spring提供的依赖注入、声明式事务管理、安全性控制等高级功能。此外,Spring WebSocket还支持与Spring MVC的集成,使得在Web应用中使用WebSocket变得更加灵活和方便。 直接在Eclipse上面引用,说明这个websocket包是易于集成的库或模块。Eclipse是一个流行的集成开发环境(IDE),支持Java、C++、PHP等多种编程语言和多种框架的开发。在Eclipse中引用一个库或模块通常意味着需要将相关的jar包、源代码或者配置文件添加到项目中,然后就可以在Eclipse项目中使用该技术了。具体操作可能包括在项目中添加依赖、配置web.xml文件、使用注解标注等方式。 标签为“websocket”,这表明这个文件或项目与WebSocket技术直接相关。标签是用于分类和快速检索的关键字,在给定的文件信息中,“websocket”是核心关键词,它表明该项目或文件的主要功能是与WebSocket通信协议相关的。 文件名称列表中的“SSMTest-master”暗示着这是一个版本控制仓库的名称,例如在GitHub等代码托管平台上。SSM是Spring、SpringMVC和MyBatis三个框架的缩写,它们通常一起使用以构建企业级的Java Web应用。这三个框架分别负责不同的功能:Spring提供核心功能;SpringMVC是一个基于Java的实现了MVC设计模式的请求驱动类型的轻量级Web框架;MyBatis是一个支持定制化SQL、存储过程以及高级映射的持久层框架。Master在这里表示这是项目的主分支。这表明websocket包可能是一个SSM项目中的模块,用于提供WebSocket通讯支持,允许开发者在一个集成了SSM框架的Java Web应用中使用WebSocket技术。 综上所述,这个websocket包可以提供给开发者一种简洁有效的方式,在遵循Spring框架原则的同时,实现WebSocket通信功能。开发者可以利用此包在Eclipse等IDE中快速开发出支持实时通信的Web应用,极大地提升开发效率和应用性能。
recommend-type

电力电子技术的智能化:数据中心的智能电源管理

# 摘要 本文探讨了智能电源管理在数据中心的重要性,从电力电子技术基础到智能化电源管理系统的实施,再到技术的实践案例分析和未来展望。首先,文章介绍了电力电子技术及数据中心供电架构,并分析了其在能效提升中的应用。随后,深入讨论了智能化电源管理系统的组成、功能、监控技术以及能
recommend-type

通过spark sql读取关系型数据库mysql中的数据

Spark SQL是Apache Spark的一个模块,它允许用户在Scala、Python或SQL上下文中查询结构化数据。如果你想从MySQL关系型数据库中读取数据并处理,你可以按照以下步骤操作: 1. 首先,你需要安装`PyMySQL`库(如果使用的是Python),它是Python与MySQL交互的一个Python驱动程序。在命令行输入 `pip install PyMySQL` 来安装。 2. 在Spark环境中,导入`pyspark.sql`库,并创建一个`SparkSession`,这是Spark SQL的入口点。 ```python from pyspark.sql imp
recommend-type

新版微软inspect工具下载:32位与64位版本

根据给定文件信息,我们可以生成以下知识点: 首先,从标题和描述中,我们可以了解到新版微软inspect.exe与inspect32.exe是两个工具,它们分别对应32位和64位的系统架构。这些工具是微软官方提供的,可以用来下载获取。它们源自Windows 8的开发者工具箱,这是一个集合了多种工具以帮助开发者进行应用程序开发与调试的资源包。由于这两个工具被归类到开发者工具箱,我们可以推断,inspect.exe与inspect32.exe是用于应用程序性能检测、问题诊断和用户界面分析的工具。它们对于开发者而言非常实用,可以在开发和测试阶段对程序进行深入的分析。 接下来,从标签“inspect inspect32 spy++”中,我们可以得知inspect.exe与inspect32.exe很有可能是微软Spy++工具的更新版或者是有类似功能的工具。Spy++是Visual Studio集成开发环境(IDE)的一个组件,专门用于Windows应用程序。它允许开发者观察并调试与Windows图形用户界面(GUI)相关的各种细节,包括窗口、控件以及它们之间的消息传递。使用Spy++,开发者可以查看窗口的句柄和类信息、消息流以及子窗口结构。新版inspect工具可能继承了Spy++的所有功能,并可能增加了新功能或改进,以适应新的开发需求和技术。 最后,由于文件名称列表仅提供了“ed5fa992d2624d94ac0eb42ee46db327”,没有提供具体的文件名或扩展名,我们无法从这个文件名直接推断出具体的文件内容或功能。这串看似随机的字符可能代表了文件的哈希值或是文件存储路径的一部分,但这需要更多的上下文信息来确定。 综上所述,新版的inspect.exe与inspect32.exe是微软提供的开发者工具,与Spy++有类似功能,可以用于程序界面分析、问题诊断等。它们是专门为32位和64位系统架构设计的,方便开发者在开发过程中对应用程序进行深入的调试和优化。同时,使用这些工具可以提高开发效率,确保软件质量。由于这些工具来自Windows 8的开发者工具箱,它们可能在兼容性、效率和用户体验上都经过了优化,能够为Windows应用的开发和调试提供更加专业和便捷的解决方案。
recommend-type

如何运用电力电子技术实现IT设备的能耗监控

# 摘要 随着信息技术的快速发展,IT设备能耗监控已成为提升能效和减少环境影响的关键环节。本文首先概述了电力电子技术与IT设备能耗监控的重要性,随后深入探讨了电力电子技术的基础原理及其在能耗监控中的应用。文章详细分析了IT设备能耗监控的理论框架、实践操作以及创新技术的应用,并通过节能改造案例展示了监控系统构建和实施的成效。最后,本文展望了未来能耗监控技术的发展趋势,同时
recommend-type

2635.656845多位小数数字,js不使用四舍五入保留两位小数,然后把结果千分位,想要的结果是2,635.65;如何处理

在JavaScript中,如果你想要将2635.656845这个数字精确地保留两位小数,并且去掉多余的千分位,可以使用`toFixed()`函数结合字符串切片的方法来实现。不过需要注意的是,`toFixed()`会返回一个字符串,所以我们需要先转换它。 以下是一个示例: ```javascript let num = 2635.656845; // 使用 toFixed() 保留两位小数,然后去掉多余的三位 let roundedNum = num.toFixed(2).substring(0, 5); // 如果最后一个字符是 '0',则进一步判断是否真的只有一位小数 if (round