ANTLR4-从非文件输入生成代码? [英] ANTLR4 - Generate code from non-file inputs?

查看:64
本文介绍了ANTLR4-从非文件输入生成代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们从哪里开始从头开始手动构建CST?还是ANTLR4始终需要lex/parse流程作为我们的输入步骤?

程序中有一些视觉元素表示代码结构.

I have some visual elements in my program that represent code structures.

例如正方形代表类,而嵌入该正方形的圆圈代表方法.

e.g. a square represents a class, while a circle embedded within that square represents a method.

现在,我想将它们转换为代码.如何在运行时使用ANTLR4做到这一点(使用ANTLR4.js)?大多数ANTLR示例似乎都依赖于词法分析和现有代码解析来到达语法树.因此,而不是:

Now I want to turn those into code. How do I use ANTLR4 to do this, at runtime (using ANTLR4.js)? Most of the ANTLR examples seem to rely on lexing and parsing existing code to get to a syntax tree. So rather than:

input code->lex->parse->syntax tree->output code (1)

我想要

manually create syntax tree->output code (2)

(稍后,当用户向该类及其方法添加代码时,则将像(1)中一样使用ANTLR.)

(Later, as the user adds code to that class and its methods, then ANTLR will be used as in (1).)

编辑也许我误会了这一点.是否创建一些自定义数据结构,然后在其上运行解析器?即write structures to some in-memory format->parse->output code (3)?

EDIT Maybe I'm misunderstanding this. Do I create some custom data structure and then run the parser over it? i.e. write structures to some in-memory format->parse->output code (3)?

推荐答案

IIUC,您可以直接使用StringTemplate.

IIUC, you could use StringTemplate directly.

通过背景方式,Antlr本身会构建一个内存中的解析树,然后对其进行遍历,以增量方式调用StringTemplate来输出由相应的解析树节点数据限定的代码段. Antlr使用内部解析树只是简化步行的一种方便(因为Antlr是使用Antlr构建的).

By, way of background, Antlr itself builds an in-memory parse-tree and then walks it, incrementally calling StringTemplate to output code snippets qualified by corresponding parse-tree node data. That Antlr uses an internal parse-tree is just a convenience for simplifying walking (since Antlr is built using Antlr).

如果您有自己的数据结构,则不管其具体实现如何,都按程序对其进行处理,以逐步调用ST模板以发出相应的代码.而且,您可以直接使用与Antlr使用的模板相同的模板( JavaScript.stg ),如果它们符合您的要求.

If you have your own data structure, regardless of its specific implementation, procedurally process it to progressively call ST templates to emit the corresponding code. And, you can directly use the same templates that Antlr uses (JavaScript.stg), if they meet your requirements.

当然,如果您的数据结构具有可以被词法分析/解析为标准Antlr解析树的性质,则可以使用标准Antlr访问者来调用和填充特定于节点的模板.

Of course, if your data structure is of a nature that can be lex'd/parsed into a standard Antlr parse-tree, you can then use a standard Antlr visitor to call and populate node-specific templates.

这篇关于ANTLR4-从非文件输入生成代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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