From 0c4382f31fefe6c5575842427c83e1c26fe00efa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Johann=20Kl=C3=A4hn?= <dev@jklaehn.de> Date: Fri, 28 Jul 2017 12:25:20 +0200 Subject: [PATCH 02/12] [libclang] Keep track of TranslationUnit instance when annotating tokens Previously the _tu was not propagated to the returned cursor, leading to errors when calling any method on that cursor (e.g. cursor.referenced). --- bindings/python/clang/cindex.py | 1 + bindings/python/tests/cindex/test_cursor.py | 22 ++++++++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/tools/clang/bindings/python/clang/cindex.py b/tools/clang/bindings/python/clang/cindex.py index 0f01d171ad..ecff13f7a5 100644 --- a/tools/clang/bindings/python/clang/cindex.py +++ b/tools/clang/bindings/python/clang/cindex.py @@ -3199,6 +3199,7 @@ class Token(Structure): def cursor(self): """The Cursor this Token corresponds to.""" cursor = Cursor() + cursor._tu = self._tu conf.lib.clang_annotateTokens(self._tu, byref(self), 1, byref(cursor)) diff --git a/tools/clang/bindings/python/tests/cindex/test_cursor.py b/tools/clang/bindings/python/tests/cindex/test_cursor.py index 85c455fd73..87fd76ed0e 100644 --- a/tools/clang/bindings/python/tests/cindex/test_cursor.py +++ b/tools/clang/bindings/python/tests/cindex/test_cursor.py @@ -406,6 +406,28 @@ def test_get_tokens(): assert tokens[0].spelling == 'int' assert tokens[1].spelling == 'foo' +def test_get_token_cursor(): + """Ensure we can map tokens to cursors.""" + tu = get_tu('class A {}; int foo(A var = A());', lang='cpp') + foo = get_cursor(tu, 'foo') + + for cursor in foo.walk_preorder(): + if cursor.kind.is_expression() and not cursor.kind.is_statement(): + break + else: + assert False, "Could not find default value expression" + + tokens = list(cursor.get_tokens()) + assert len(tokens) == 4, [t.spelling for t in tokens] + assert tokens[0].spelling == '=' + assert tokens[1].spelling == 'A' + assert tokens[2].spelling == '(' + assert tokens[3].spelling == ')' + t_cursor = tokens[1].cursor + assert t_cursor.kind == CursorKind.TYPE_REF + r_cursor = t_cursor.referenced # should not raise an exception + assert r_cursor.kind == CursorKind.CLASS_DECL + def test_get_arguments(): tu = get_tu('void foo(int i, int j);') foo = get_cursor(tu, 'foo') -- 2.13.0