LLVM( http://llvm.org )의 clang라이브러리를 사용해서 C++코드를 파싱할 수 있다.
libclang은 python바인딩이 있어서 python에서도 활용가능하다^^
준비:
- python 2.7이상 32비트버젼 (windows 7에서 테스트했을때 64비트버젼은 호환하지 않는거같음. clang dll을 로드하지 못함)
-> http://python.org/download/ - pip (python 모듈들을 손쉽게 설치할 수 있음)
-> http://www.pip-installer.org/en/latest/installing.html
(설치후 python설치폴더의 Scripts폴더를 PATH에 추가해야함) - python clang 모듈 설치 (pip로 설치)
-> 명령프롬프트에서 “pip install clang” 입력
샘플코드:
from clang.cindex import Index def clang_test(s): tu = Index.create().parse( 'xxx.cpp', unsaved_files=[('xxx.cpp', s)] ) for d in tu.diagnostics: if d.severity >= 3: print 'Error:', d.spelling, d.location print for c in tu.cursor.get_children(): print c.spelling, ':', c.kind if __name__ == '__main__': clang_test(''' Xyz123 x; // syntax error. int myFunc(int a, int b) { return a + b; } ''')
출력:
Error: unknown type name 'Xyz123' <SourceLocation file 'xxx.cpp', line 2, column 2> __builtin_va_list : CursorKind.TYPEDEF_DECL type_info : CursorKind.CLASS_DECL x : CursorKind.VAR_DECL myFunc : CursorKind.FUNCTION_DECL
정상적으로 문법적인 에러 위치와 소스내의 변수, 함수들을 출력했음^^