2017-10-16 67 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

謝謝........ –