简体   繁体   English

在ANTLR语法中定义关键字

[英]Define Keywords in ANTLR grammar

I want to build a simple lexical analyzer for a specific language which has reserved words like (if, else, etc.) using ANTLR. 我想为特定语言构建一个简单的词法分析器,它使用ANTLR保留像(if,else等)这样的单词。 I went through several tutorials and was able to find the ways of defining all the options except reserved keywords. 我经历了几个教程,并且能够找到定义除保留关键字之外的所有选项的方法。 How to define reserved keywords in the grammar file in ANTLR ? 如何在ANTLR中的语法文件中定义保留关键字?

Thanks in advance Shamika 在此先感谢Shamika

Define them before a rule that can possibly match those keywords. 在可能与这些关键字匹配的规则之前定义它们。

For example, you have a rule that matches identifiers, where an identifier consists of one ore more letters, then your reserved if keyword should be places before the identifier rule in your lexer: 例如,您有一个匹配标识符的规则,其中标识符由一个或多个字母组成,那么您的reserved if关键字应该位于词法分析器中的标识符规则之前:

grammar T;

// parser rules here

IF
  :  'if'
  ;

IDENTIFIER
  :  ('a'..'z')+
  ;

That way, an if will always become a IF token and not an IDENTIFIER . 这样, if将始终成为IF令牌而不是IDENTIFIER

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

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