bambooflow Note

始めの一歩

最終更新:

bambooflow

- view
メンバー限定 登録/ログイン

ANTLR 始めの一歩(C++)


パーサジェネレータの1つであるANTLRの使いはじめをメモ。

ANTLRのバージョンは、C++出力をサポートするv2.7.7を使います。


コード

  • test.g

options {
    language="Cpp";
}
 
{
#include <iostream>
}
 
class P extends Parser;
 
startRule
    : n:NAME
        { std::cout << "Hello, " << n->getText() << std::endl; }
    ;
 
class L extends Lexer;
 
NAME: ( 'a'..'z' | 'A'..'Z' )+ NEWLINE
    ;
 
NEWLINE
    : '\r' '\n'    // DOS
    | '\n'         // UNIX
    ;
 


  • main.cpp
#include <iostream>
#include <fstream>
#include "L.hpp"
#include "P.hpp"
 
using namespace std;
 
int main( int argc, char* argv[] )
{
    if ( argc > 1) {
 
        cout << "file name is " << argv[1] << endl;
 
        try {
            ifstream file( argv[1] );
 
            L lexer( file );
 
            P parser( lexer );
 
            parser.startRule();
        }
        catch (exception& e) {
            cerr << "parser exception: " << e.what() << endl;
        }
 
        cout << " --- complete --- " << endl;
    }
    return 0;
}
 

コンパイル

次のコマンドを実行します。
% antlr test.g

すると、つぎのようなファイルが生成されます。
% ls
L.cpp
L.hpp
P.cpp
P.hpp
PTokenTypes.hpp
PTokenTypes.txt

ここで、L(.cpp.hpp)は字句解析クラスで、P(.cpp.hpp)はパーサクラスです。

% g++ -c -I/antlrインストール先/include/antlr L.cpp
% g++ -c -I/antlrインストール先/include/antlr P.cpp
% g++ -c -I/antlrインストール先/include/antlr main.cpp
% g++ -o run.x L.o P.o main.o -L/ntlrインストール先/lib -lantlr

ここで、"antlrインストール先"は、わたしの場合"/usr/local/"とかです。

実行


適当なテキストファイルを準備します。
% vi aaa.txt
abcdefg

次のように実行します。
% ./run.x aaa.txt
file -- aaa.txt
Hello, abcdefg

 --- complete --- 
記事メニュー
ウィキ募集バナー