简体   繁体   English

如何从antlr词法分析器中提取关键字

[英]How to extract keywords from antlr lexer

I am building a text-editor in Java for a grammar that I did not write and I would like to support syntax highlighting.我正在用 Java 为我没有编写的语法构建一个文本编辑器,我想支持语法突出显示。 I have a lexer file with keywords in it (the following is a subset):我有一个包含关键字的词法分析器文件(以下是一个子集):

DATABASE: 'DATABASE';
NATIVE: 'NATIVE' -> mode(NATIVE_QUERY);
SOURCE: 'SOURCE';
CHECK: 'CHECK';
ACTION: 'ACTION';
EXECUTE: 'EXECUTE';
USING: 'USING';
ON: 'ON';
EACH: 'EACH';
FROM: 'FROM';

I would like to dynamically read these keywords to use for syntax highlighting of those keywords in the text-editor I am making.我想动态读取这些关键字,以用于在我正在制作的文本编辑器中突出显示这些关键字的语法。 I currently am doing this manually but I want the text-editor to do it dynamically in case the authors change the lexer.我目前正在手动执行此操作,但我希望文本编辑器动态执行此操作,以防作者更改词法分析器。 How do I do this?我该怎么做呢? Is this the right way to go about it?这是正确的方法吗?

I don't think there's an attribution mechanism in Antlr itself to tag "keywords", but that's what you should read up on.我不认为 Antlr 本身有一个归因机制来标记“关键字”,但这是您应该阅读的内容。 In lieu of that, you could apply a hack that assumes an order within the grammar whereby you define the first and last rules for keywords "DATABASE" and "FROM".取而代之的是,您可以应用假设语法中的顺序的 hack,从而为关键字“DATABASE”和“FROM”定义第一个和最后一个规则。 Then, write a method to go through the ruleNames[] array which you can call anytime to accumulating all the keyword names between the first and last rule names you defined above.然后,编写一个方法来遍历 ruleNames[] 数组,您可以随时调用该数组来累积上面定义的第一个和最后一个规则名称之间的所有关键字名称。 To make this work you would have to write some comments that say something like "// On severe penalty, only add keyword productions in rules between "DATABASE" and "FROM". However, Antlr lexer rules are ordered for matching preference, so this hack may not work.要完成这项工作,您必须编写一些注释,例如“// 在严厉惩罚下,仅在“DATABASE”和“FROM”之间的规则中添加关键字产生式。但是,Antlr 词法分析器规则是按匹配偏好排序的,所以这hack 可能不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM