基于xtext的dsl实现元语言
textX的Python项目详细描述
textx是用python构建领域特定语言(dsl)的元语言。 它的灵感来自Xtext。
简而言之,textx将帮助您以一种简单的方式构建文本语言。 你可以发明你自己的语言或者为已经存在的语言建立支持。 文本语言或文件格式。
从单一语言描述(语法)中,textx将构建 语法分析器和语言的元模型(也称为抽象语法)。 详细信息请参见文档。
textx遵循xtext的语法和语义,但是differs in some places是 使用Arpeggiopeg语法分析器在python中100%实现-无语法 模棱两可,前景无限,翻译风格。
快速介绍
下面是一个完整的示例,显示了 画画。我们还展示了如何定义自定义类、解释模型和搜索 对于特定类型的实例。
fromtextximportmetamodel_from_str,get_children_of_typegrammar=""" Model: commands*=DrawCommand; DrawCommand: MoveCommand | ShapeCommand; ShapeCommand: LineTo | Circle; MoveCommand: MoveTo | MoveBy; MoveTo: 'move' 'to' position=Point; MoveBy: 'move' 'by' vector=Point; Circle: 'circle' radius=INT; LineTo: 'line' 'to' point=Point; Point: x=INT ',' y=INT; """# We will provide our class for Point.# Classes for other rules will be dynamically generated.classPoint(object):def__init__(self,parent,x,y):self.parent=parentself.x=xself.y=ydef__str__(self):return"{},{}".format(self.x,self.y)def__add__(self,other):returnPoint(self.parent,self.x+other.x,self.y+other.y)# Create meta-model from the grammar. Provide `Point` class to be used for# the rule `Point` from the grammar.mm=metamodel_from_str(grammar,classes=[Point])model_str=""" move to 5, 10 line to 10, 10 line to 20, 20 move by 5, -7 circle 10 line to 10, 10 """# Meta-model knows how to parse and instantiate models.model=mm.model_from_str(model_str)# At this point model is a plain Python object graph with instances of# dynamically created classes and attributes following the grammar.defcname(o):returno.__class__.__name__# Let's interpret the modelposition=Point(None,0,0)forcommandinmodel.commands:ifcname(command)=='MoveTo':print('Moving to position',command.position)position=command.positionelifcname(command)=='MoveBy':position=position+command.vectorprint('Moving by',command.vector,'to a new position',position)elifcname(command)=='Circle':print('Drawing circle at',position,'with radius',command.radius)else:print('Drawing line from',position,'to',command.point)position=command.pointprint('End position is',position)# Output:# Moving to position 5,10# Drawing line from 5,10 to 10,10# Drawing line from 10,10 to 20,20# Moving by 5,-7 to a new position 25,13# Drawing circle at 25,13 with radius 10# Drawing line from 25,13 to 10,10# Collect all points starting from the root of the modelpoints=get_children_of_type("Point",model)forpointinpoints:print('Point: {}'.format(point))# Output:# Point: 5,10# Point: 10,10# Point: 20,20# Point: 5,-7# Point: 10,10
文档和教程
完整的教程文档可在 http://textx.github.io/textX/stable/
IDE/编辑器中的支持
- textX-languageserver- 语言服务器协议支持任何基于textx的语言
- textX-extensions-语法 突出显示,Visual Studio代码的代码大纲
- textx.vim- textx语法的突出显示和大纲
- textx-mode- textx语法的emacs模式
许可证
麻省理工学院
python版本
测试2.7、3.4+