通过解析 C 代码获取带有 antlr4 的预处理器行

Get Preprocessor lines with antlr4 with parsing C Code

我正在使用 Antlr4 来解析 C 代码,我正在使用以下语法来解析:

Link to C.g4

以上语法默认不提供任何解析规则来获取预处理器语句。

我稍微更改了语法以通过添加以下行来获取预处理器行

externalDeclaration
:   functionDefinition
|   declaration
|   ';' // stray ;
|   preprocessorDeclaration
;

preprocessorDeclaration
:   PreprocessorBlock
;

PreprocessorBlock
:   '#' ~[\r\n]*
    -> channel(HIDDEN)
;

在 Java 中,我使用以下侦听器来获取预处理器行

@Override
public void enterPreprocessorDeclaration(PreprocessorDeclarationContext ctx) {
    System.out.println("Preprocessor Directive found");
    System.out.println("Preprocessor: " + parser.getTokenStream().getText(ctx));
}

该方法从未被触发。有人可以建议一种获取预处理器行的方法吗?

输入:

#include <stdio.h>

int k = 10;
int f(int a, int b){
int i;
for(i = 0; i < 5; i++){
    printf("%d", i);
}

}

实际上,对于 channel(HIDDEN),规则 preprocessorDeclaration 没有输出。

如果我删除 -> channel(HIDDEN),它会起作用:

preprocessorDeclaration
@after {System.out.println("Preprocessor found : " + $text);}
    :   PreprocessorBlock
    ;

PreprocessorBlock
    :   '#' ~[\r\n]*
//        -> channel(HIDDEN)
    ;

执行:

$ grun C compilationUnit -tokens -diagnostics t2.text
[@0,0:17='#include <stdio.h>',<PreprocessorBlock>,1:0]
[@1,18:18='\n',<Newline>,channel=1,1:18]
[@2,19:19='\n',<Newline>,channel=1,2:0]
[@3,20:22='int',<'int'>,3:0]
...
[@72,115:114='<EOF>',<EOF>,10:0]
C last update 1159
Preprocessor found : #include <stdio.h>
line 4:11 reportAttemptingFullContext d=83 (parameterDeclaration), input='int a,'
line 4:11 reportAmbiguity d=83 (parameterDeclaration): ambigAlts={1, 2}, input='int a,'
...
#include <stdio.h>

int k = 10;
int f(int a, int b) {
    int i;
    for(i = 0; i < 5; i++) {
        printf("%d", i);
    }
}

在文件 CMyListener.java 中(来自我之前的回答)我添加了:

public void enterPreprocessorDeclaration(CParser.PreprocessorDeclarationContext ctx) {
    System.out.println("Preprocessor Directive found");
    System.out.println("Preprocessor: " + parser.getTokenStream().getText(ctx));
}

执行:

$ java test_c t2.text 
...
parsing ended
>>>> about to walk
Preprocessor Directive found
Preprocessor: #include <stdio.h>
>>> in CMyListener
#include <stdio.h>

int k = 10;
...
}