将 Antlr 语法树转换为有用的对象 [英] Converting Antlr syntax tree into useful objects

查看:38
本文介绍了将 Antlr 语法树转换为有用的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在考虑如何最好地获取使用 Antlr 生成的 AST 并将其转换为我可以在我的程序中使用的有用对象.

I'm currently pondering how best to take an AST generated using Antlr and convert it into useful objects which I can use in my program.

我的语法(除了学习)的目的是创建一种可执行(运行时解释)语言.

The purpose of my grammar (apart from learning) is to create an executable (runtime interpretted) language.

例如,我将如何获取属性子树并实例化特定的 Attribute 类.例如.

For example, how would I take an attribute sub-tree and have a specific Attribute class instanciated. E.g.

以下代码是我的语言:

Print(message:"Hello stackoverflow")

将产生以下 AST:

我目前的想法是,工厂类可以读取树,提取名称(message),并输入(STRING) value(">Hello stackoverflow").现在,知道类型我可以实例化正确的类(例如 StringAttribute 类)并传入所需的属性数据 - namevalue.

My current line of thinking is that a factory class could read the tree, pull out the name (message), and type(STRING) value("Hello stackoverflow"). Now, knowing the type I could instanciate the correct class (e.g. A StringAttribute class) and pass in the required attribute data - the name and value.

同样的方法可用于定义工厂,提取定义名称(Print),实例化 Print 类,然后传入从属性工厂生成的属性.

The same approach could be used for a definition factory, pulling out the definition name (Print), instanciating the Print class, and then passing in the attributes generated from the attribute factory.

使用更复杂的程序会使事情变得更复杂:

Things do get a bit more complicated with a more complicated program:

Program(args:[1,2,3,4,5])
{
    If(isTrue:IsInArray(array:{Program.args} value:5))
    {
        Then {
            Print(message:"5 is in the array")
        } Else {
            Print(message:"More complex " + "message")
        }
    }
}

非常欢迎任何/所有帮助或想法.非常感谢.

ANY/ALL help or thoughts are very welcome. Many thanks.

我以前的相关问题(可能有用):

Previous related questions by me (Could be useful):

  1. 如何制作一棵树解析器
  2. 解决 LL 递归问题
  3. Antrl3 条件树重写

推荐答案

我建议阅读 语言实现模式 作者:Terence Parr.

I recommend reading chapter 9, Building High-Level Interpreters, from Language Implementation Patterns by Terence Parr.

编辑

好的,为了让您度过等待那本书的时间,以下是您(至少)需要的:

Okay, to get you through the time waiting for that book, here's what you're (at least) going to need:

  • 全局内存空间;
  • 函数空间(每个函数空间也会有一个(本地)内存空间);

和脑海中浮现的类(以UML 风格 风格):

and classes that spring to mind (in UML-ish style):

  • 类解释器
    • 全局:内存空间
    • 函数:堆栈<函数>
    • ...

    • 变量:映射<字符串,对象>
    • ...

    • 本地:内存空间
    • execute(): void
    • ...

    这篇关于将 Antlr 语法树转换为有用的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆