Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/joomla/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Antlr4从错误中恢复并继续解析,直到EOF_Antlr_Grammar_Antlr4_Antlr4cs - Fatal编程技术网

Antlr4从错误中恢复并继续解析,直到EOF

Antlr4从错误中恢复并继续解析,直到EOF,antlr,grammar,antlr4,antlr4cs,Antlr,Grammar,Antlr4,Antlr4cs,我正在使用Antlr4.5用Java编写C#语法。 当我处理带有预处理器指令的C#源代码时。 示例代码 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Hansa { class Program { public static void Main()

我正在使用Antlr4.5用Java编写C#语法。 当我处理带有预处理器指令的C#源代码时。 示例代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Hansa
{
    class Program
    {
        public static void Main()
        {
            int b = 5;
            #if true
                int c = 0;
                #if false
                            union {
                                internal struct {
                                    uint    pmclass;
                                    ushort  pmenum;
                                };
                                ushort  bseg;
                                byte[]  Sym;
                                internal struct  {
                                    uint index;
                                    string name;
                                } btype;
                            } pbase;
                #endif
                printMe(c);
            #endif
            printMe(b);
            Console.ReadLine();
        }

        public static void printMe(int val)
        {
            Console.WriteLine(val);
        }
    }
}
在上面的代码示例中,“#if false”和“next”#endif”之间的代码生成一个错误,即“在输入'union{'处没有可行的替代方案”

我需要在代码级别忽略这个错误,或者通过语法忽略行

在上面的代码中,如果没有任何错误,我可以获得名称空间名称、类名、方法名称、方法签名和语句行。 当我在“union{”附近遇到错误时,我可以访问名称空间名称、类名、Main()方法名称,但无法访问printMe()方法声明

我的要求是,当发生错误时,语法分析不应该终止。它应该从下一行继续到EOF


如何实现这一点?

您必须重写ANTLR4错误恢复。
DefaultErrorStrategy
将报告
NoViableAlternativeException
,然后恢复。它不会中断解析。因此,如果您的程序在第一个错误时中断:

  • 可能您使用了另一个
    antlErrorStrategy
    。然后调整它,使其恢复为
    DefaultErrorStrategy
  • 或者您的
    antlErrorListener
    中断程序,然后您必须调整此程序,使其跳过故障

如果你想让错误恢复从下一行开始,你必须调整方法
ErrorStrategy.recoverXXX
。默认情况下,错误恢复会尝试删除/插入魔法标记,以达到一个干净的状态。

非常感谢CoronA。你是对的@CoronA。我创建了一个扩展DefaultErrorStrategy的类。然后我有了erride类似这样的“recover”方法。super.recover(识别器,e);CommonTokenStream令牌=(CommonTokenStream)识别器。getTokenStream();//如果(tokens.LA(1)!=CSharpParser.EOF){//移动到下一个令牌。consume();},请验证当前令牌不是EOF你能提供一个例子吗?我不知道它是如何工作的。我应该覆盖consumUntil方法吗?发布你的实际问题。并指出为什么你认为错误策略可能是一个好的解决方案。