Created
April 2, 2014 16:23
-
-
Save tanakamura/9937494 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <clang-c/Index.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
struct FindState { | |
bool find; | |
int target_line; | |
CXCursor loop; | |
}; | |
CXChildVisitResult | |
findLoopVisitor(CXCursor cursor, | |
CXCursor parent, | |
CXClientData client_data) | |
{ | |
FindState *st = (FindState*)client_data; | |
CXSourceRange range = clang_getCursorExtent(cursor); | |
CXSourceLocation start = clang_getRangeStart(range); | |
CXSourceLocation end = clang_getRangeEnd(range); | |
CXFile file; | |
unsigned line_start, line_end, column, offset; | |
clang_getSpellingLocation(start, &file, &line_start, &column, &offset); | |
clang_getSpellingLocation(end, &file, &line_end, &column, &offset); | |
bool in_range = st->target_line>=line_start && st->target_line<=line_end; | |
if (cursor.kind == CXCursor_ForStmt || | |
cursor.kind == CXCursor_WhileStmt) | |
{ | |
if (in_range) { | |
st->loop = cursor; | |
st->find = true; | |
} | |
} | |
if (in_range) { | |
return CXChildVisit_Recurse; | |
} else { | |
return CXChildVisit_Continue; | |
} | |
} | |
int | |
main(int argc, char **argv) | |
{ | |
if (argc < 3) { | |
puts("usage <lineno> <clang options> <source>"); | |
return 1; | |
} | |
int line = atoi(argv[1]); | |
int num_opt = argc - 3; | |
const char *source = argv[argc-1]; | |
CXIndex clang_idx = clang_createIndex(1,1); | |
CXTranslationUnit TU = clang_createTranslationUnitFromSourceFile( | |
clang_idx, | |
source, | |
num_opt, | |
argv + 2, | |
0,0); | |
CXFile file = clang_getFile(TU, source); | |
CXSourceLocation loc = clang_getLocation(TU, file, 1, 1); | |
CXCursor cursor = clang_getCursor(TU, loc); | |
FindState st; | |
st.find = false; | |
st.target_line = line; | |
clang_visitChildren(cursor, findLoopVisitor, &st); | |
if (st.find) { | |
CXSourceRange range = clang_getCursorExtent(st.loop); | |
CXSourceLocation start = clang_getRangeStart(range); | |
CXSourceLocation end = clang_getRangeEnd(range); | |
CXFile file; | |
unsigned line_start, line_end, column, offset; | |
clang_getSpellingLocation(start, &file, &line_start, &column, &offset); | |
clang_getSpellingLocation(end, &file, &line_end, &column, &offset); | |
CXString str = clang_getCursorKindSpelling(st.loop.kind); | |
printf("%s: %d-%d\n", clang_getCString(str), line_start, line_end); | |
clang_disposeString(str); | |
} | |
clang_disposeTranslationUnit(TU); | |
clang_disposeIndex(clang_idx); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment