2017-10-16 6 views
2

を解析してantlr4とプリプロセッサ行を取得します私はCコードを解析するAntlr4を使用していますが、私が解析し、次の文法を使用しています:Cコード

​​

デフォルトで上記の文法は、任意の解析規則を提供していません。プリプロセッサステートメントを取得します。

私は次の行に

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

少なくとも#1から始まる解析行を入力してください。 – 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) 
    ; 

実行:ファイルCMyListener.java

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

(私の前の回答から)私が追加しました:

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

ありがとうございました。 –