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

查看:19
本文介绍了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:

输入代码->lex->parse->syntax tree->输出代码(1)

我想要

手动创建语法树->输出代码(二)

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

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

编辑 也许我误解了这一点.我是否创建了一些自定义数据结构,然后在其上运行解析器?即将结构写入一些内存格式->解析->输出代码(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天全站免登陆