2017-10-16 81 views
2

我使用Antlr4解析C代码,我使用下面的语法解析:获取预处理线与解析C代码antlr4

​​

默认情况下上面的语法不提供任何解析规则获得预处理器语句。

我改变了语法稍微得到通过添加以下行

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

}

+0

语法在给出的链接中。 –

+0

您能否提供至少一行您尝试解析的输入,从#开始? – BernardK

+1

#include int main(){ int a = 5; } –

回答

3

事实上,与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; 
... 
} 
+0

谢谢........ –