使用antlr4获取预处理器行并解析C代码 [英] Get Preprocessor lines with antlr4 with parsing C Code

查看:448
本文介绍了使用antlr4获取预处理器行并解析C代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Antlr4解析C代码,我使用以下语法进行解析:

I am using Antlr4 to parse C code and I am using the following grammar to parse:

链接到C.g4

上述语法default没有提供任何解析规则来获取预处理器语句。

The above grammar by default does not provide any parsing rules to get preprocessor statements.

我通过添加以下行来稍微改变语法以获得预处理器行

I changed the grammar slightly to get the preprocessor lines by adding the following lines

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

preprocessorDeclaration
:   PreprocessorBlock
;

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

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

And in Java I am using the following listener to get the preprocessor lines

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

永远不会触发该方法。有人可以建议一种获取预处理器行的方法吗?

The method is never triggered. Can someone suggest a method to get the preprocessor lines?

输入:

#include <stdio.h>

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

}

推荐答案

实际上,使用频道(HIDDEN),规则 preprocessorDeclaration 不产生输出。

Actually, with channel(HIDDEN), the rule preprocessorDeclaration produces no output.

如果我删除 - >频道(隐藏),它有效:

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中(来自我之前的回答)我已添加:

In file CMyListener.java (from my previous answer) I have added :

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;
...
}

这篇关于使用antlr4获取预处理器行并解析C代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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