如何在ANTLR 4中创建一个可以捕获不同类型的词法错误的词法分析器 [英] How to create a lexical analyzer in ANTLR 4 that can catch different types of lexical errors

查看:601
本文介绍了如何在ANTLR 4中创建一个可以捕获不同类型的词法错误的词法分析器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ANTLR 4创建我的词法分析器,但我不知道如何创建一个词法分析器捕获不同类型的词法错误。

I am using ANTLR 4 to create my lexer, but I don't how to create a lexical analyzer that catches different types of lexical errors.

例如:


  1. 如果我有一个无法识别的符号,例如 ^

如果我有一个无效的标识符 2n 词汇分析器应报告此类错误identifier2n必须以字母

If I have an invalid identifier like 2n the lexical analyzer should report an error like this "identifier "2n" must begin with a letter"

推荐答案

为每个已知错误和catchall错误标记规则创建错误标记规则像这样:

Create an error token rule for each known error and an "catchall" error token rule at the end like this:

// valid tokens first!
Number : [0-9]+;
Identifier : [a-zA-Z] [a-zA-Z0-9]*;
//...

// "error" tokens
// don't use these tokens in your grammar; They will show up as extraneous tokens during parsing and can be handled if desired.
InvalidIdentifier : [0-9]([0-9a-zA-Z])+; 
ACommonInvalidToken : '^'; // if you want to be more specific for certain cases
// add more to address common mistakes

UnknownToken : . ; // the "catch-all" error token; be sure not to be too greedy...

这篇关于如何在ANTLR 4中创建一个可以捕获不同类型的词法错误的词法分析器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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