1 | import os |
2 | from clang.cindex import Config |
3 | if 'CLANG_LIBRARY_PATH' in os.environ: |
4 | Config.set_library_path(os.environ['CLANG_LIBRARY_PATH']) |
5 | |
6 | from clang.cindex import CursorKind |
7 | from clang.cindex import Index |
8 | from clang.cindex import SourceLocation |
9 | from clang.cindex import SourceRange |
10 | from clang.cindex import TokenKind |
11 | |
12 | from .util import get_tu |
13 | |
14 | import unittest |
15 | |
16 | |
17 | class TestTokens(unittest.TestCase): |
18 | def test_token_to_cursor(self): |
19 | """Ensure we can obtain a Cursor from a Token instance.""" |
20 | tu = get_tu('int i = 5;') |
21 | r = tu.get_extent('t.c', (0, 9)) |
22 | tokens = list(tu.get_tokens(extent=r)) |
23 | |
24 | self.assertEqual(len(tokens), 4) |
25 | self.assertEqual(tokens[1].spelling, 'i') |
26 | self.assertEqual(tokens[1].kind, TokenKind.IDENTIFIER) |
27 | |
28 | cursor = tokens[1].cursor |
29 | self.assertEqual(cursor.kind, CursorKind.VAR_DECL) |
30 | self.assertEqual(tokens[1].cursor, tokens[2].cursor) |
31 | |
32 | def test_token_location(self): |
33 | """Ensure Token.location works.""" |
34 | |
35 | tu = get_tu('int foo = 10;') |
36 | r = tu.get_extent('t.c', (0, 11)) |
37 | |
38 | tokens = list(tu.get_tokens(extent=r)) |
39 | self.assertEqual(len(tokens), 4) |
40 | |
41 | loc = tokens[1].location |
42 | self.assertIsInstance(loc, SourceLocation) |
43 | self.assertEqual(loc.line, 1) |
44 | self.assertEqual(loc.column, 5) |
45 | self.assertEqual(loc.offset, 4) |
46 | |
47 | def test_token_extent(self): |
48 | """Ensure Token.extent works.""" |
49 | tu = get_tu('int foo = 10;') |
50 | r = tu.get_extent('t.c', (0, 11)) |
51 | |
52 | tokens = list(tu.get_tokens(extent=r)) |
53 | self.assertEqual(len(tokens), 4) |
54 | |
55 | extent = tokens[1].extent |
56 | self.assertIsInstance(extent, SourceRange) |
57 | |
58 | self.assertEqual(extent.start.offset, 4) |
59 | self.assertEqual(extent.end.offset, 7) |
60 | |