本文整理汇总了Python中clang.cindex.Index类的典型用法代码示例。如果您正苦于以下问题:Python Index类的具体用法?Python Index怎么用?Python Index使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Index类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ParseCurrentFile
def ParseCurrentFile():
global parseLock
global parseFile
global parseContent
global parseNeeded
global parseLastFile
global parseTus
global parseScopeNames
global parsingCurrentState
with parseLock:
if not parseNeeded:
return
fileToParse = parseFile
contentToParse = parseContent
parseNeeded = False
parsingCurrentState = "Parsing %s" % fileToParse
command = None
try:
if g_api is not None:
command = g_api.get_file_args(fileToParse)
except Exception as e:
with parseLock:
parsingCurrentState = str(e)
return
parsingStatePrefix = ""
unsaved_files = [(fileToParse, contentToParse)]
if command == None:
if fileToParse.endswith(".h") or fileToParse.endswith(".hpp"):
unsaved_files.append(("temporary_source.cpp", "#include \"%s\"\n#include <stdint.h>\nint main() { return 0; }\n" % fileToParse))
command = ["g++", "temporary_source.cpp"]
parsingStatePrefix = "[HEADER] "
elif fileToParse.endswith(".cpp") or fileToParse.endswith(".cc") or fileToParse.endswith(".c") or fileToParse.endswith(".cxx"):
command = ["g++", fileToParse]
parsingStatePrefix = "[SOURCE] "
else:
with parseLock:
parsingCurrentState = "Can't find command line arguments"
return
index = Index.create()
tu = index.parse(None, command + ["-I%s" % g_builtin_header_path], unsaved_files=unsaved_files, options = TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD)
with parseLock:
parseTus[fileToParse] = tu
parsingCurrentState = "%sPartially parsed %s" % (parsingStatePrefix, fileToParse)
scopeNames = []
scopeDepths = []
# create a new tu so that we don't walk it from two different threads
index = Index.create()
tu = index.parse(None, command + ["-I%s" % g_builtin_header_path], unsaved_files=unsaved_files, options = TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD)
PopulateScopeNames(GetCursorForFile(tu, os.path.abspath(fileToParse)), scopeNames, scopeDepths)
with parseLock:
parseScopeNames[fileToParse] = scopeNames
parsingCurrentState = "%sFully parsed %s" % (parsingStatePrefix, fileToParse)
示例2: skip_if_no_clang
def skip_if_no_clang():
"""
Decorate your test with this to skip it if clang isn't present.
"""
try:
Index.create()
return skipIf(False, '')
except LibclangError as error:
return skip(str(error))
示例3: clang_available
def clang_available(cls):
"""
Checks if Clang is available and ready to use.
:return: True if Clang is available, a description of the error else.
"""
try:
Index.create()
return True
except LibclangError as error: # pragma: no cover
return str(error)
示例4: clang_available
def clang_available(cls):
"""
Checks if Clang is available and ready to use.
:return: True if Clang is available, a description of the error else.
"""
if get_distribution('libclang-py3').version != '3.4.0':
return ClangBear.name + ' requires clang 3.4.0'
try: # pragma nt: no cover
Index.create()
return True
except LibclangError as error: # pragma: no cover
return str(error)
示例5: test_code_complete
def test_code_complete():
index = Index.create()
files = [
(
"fake.c",
"""
/// Aaa.
int test1;
/// Bbb.
void test2(void);
void f() {
}
""",
)
]
tu = TranslationUnit.from_source(
"fake.c",
["-std=c99"],
unsaved_files=files,
options=TranslationUnit.PARSE_INCLUDE_BRIEF_COMMENTS_IN_CODE_COMPLETION,
index=index,
)
cr = tu.codeComplete("fake.c", 9, 1, unsaved_files=files, include_brief_comments=True)
expected = [
"{'int', ResultType} | {'test1', TypedText} || Priority: 50 || Availability: Available || Brief comment: Aaa.",
"{'void', ResultType} | {'test2', TypedText} | {'(', LeftParen} | {')', RightParen} || Priority: 50 || Availability: Available || Brief comment: Bbb.",
"{'return', TypedText} || Priority: 40 || Availability: Available || Brief comment: None",
]
check_completion_results(cr, expected)
示例6: test_location
def test_location():
index = Index.create()
tu = index.parse('t.c', unsaved_files = [('t.c',baseInput)])
for n in tu.cursor.get_children():
if n.spelling == 'one':
assert_location(n.location,line=1,column=5,offset=4)
if n.spelling == 'two':
assert_location(n.location,line=2,column=5,offset=13)
# adding a linebreak at top should keep columns same
tu = index.parse('t.c', unsaved_files = [('t.c',"\n"+baseInput)])
for n in tu.cursor.get_children():
if n.spelling == 'one':
assert_location(n.location,line=2,column=5,offset=5)
if n.spelling == 'two':
assert_location(n.location,line=3,column=5,offset=14)
# adding a space should affect column on first line only
tu = index.parse('t.c', unsaved_files = [('t.c'," "+baseInput)])
for n in tu.cursor.get_children():
if n.spelling == 'one':
assert_location(n.location,line=1,column=6,offset=5)
if n.spelling == 'two':
assert_location(n.location,line=2,column=5,offset=14)
示例7: __init__
def __init__(self,
srcdir, files=None, filespattern="*.h",
clangargs=('-x', 'c++'), pythonify_types=True):
"""
Default class constructor.
:param `srcdir`: C/C++/ObjC source files directory path.
:type `srcdir`: str
:param `files`: C/C++/ObjC source files paths.
:type `files`: str
:param `clangargs`: Agruments passed to clang.
:type `clangargs`: Sequence[str]
:param `filespattern`: Unix shell like pattern for soure files
:type `filespattern`: str
:param `pythonify_types`: If set to True replace clang types
with their python alternatives.
:type `pythonify_types`: bool
"""
self.srcdir = srcdir
self.clangargs = clangargs
self.pythonify_types = pythonify_types
if files is not None:
self.fileslist = list(files)
else:
self.fileslist = glob_recursive(srcdir, filespattern)
self._index = Index.create()
self._pool = {}
self._searchindex = {}
示例8: get_tu
def get_tu(cpp_basename):
cpp_file_path = os.path.join(kInputsDir, cpp_basename)
print 'clang++ -c ' + ' '.join(extra_args) + \
' ' + ' '.join(include_args) + ' ' + cpp_file_path
index = Index.create()
tu = index.parse(cpp_file_path, args=extra_args+include_args)
return tu
示例9: main
def main():
if len(sys.argv) < 2:
sys.stderr.write('missing arguments (see -h for help)\n')
sys.exit(1)
if '-h' in sys.argv:
sys.stderr.write('%s\n\n' % __doc__.strip())
sys.stderr.write('usage example: %s /usr/include/stdio.h | dot -Txlib\n' % sys.argv[0])
sys.exit(1)
logging.basicConfig(level=logging.INFO)
index = Index.create()
tu = index.parse(None, sys.argv[1:])
rc = 0
if tu:
emit_graph(sys.stdout, tu)
log_map = {
0: logger.debug,
1: logger.info,
2: logger.warning,
3: logger.error,
4: logger.fatal
}
rc = 0
for d in tu.diagnostics:
rc = max(d.severity, rc)
log = log_map[d.severity]
log('in file %s, line %d:%s' % (d.location.file.name,
d.location.line,
d.spelling))
else:
rc = 1
sys.exit(rc)
示例10: test_file
def test_file():
index = Index.create()
tu = index.parse('t.c', unsaved_files = [('t.c', "")])
file = File.from_name(tu, "t.c")
assert str(file) == "t.c"
assert file.name == "t.c"
assert repr(file) == "<File: t.c>"
示例11: parse
def parse(self, filename):
"""
. reads 1 file
. if there is a compilation error, print a warning
. get root cursor and recurse
. for each STRUCT_DECL, register a new struct type
. for each UNION_DECL, register a new union type
. for each TYPEDEF_DECL, register a new alias/typdef to the underlying type
- underlying type is cursor.type.get_declaration() for Record
. for each VAR_DECL, register a Variable
. for each TYPEREF ??
"""
index = Index.create()
self.tu = index.parse(filename, self.flags, options=self.tu_options)
if not self.tu:
log.warning("unable to load input")
return
if len(self.tu.diagnostics) > 0:
for x in self.tu.diagnostics:
log.warning(x.spelling)
if x.severity > 2:
log.warning("Source code has some error. Please fix.")
log.warning(x.spelling)
# code.interact(local=locals())
break
root = self.tu.cursor
for node in root.get_children():
self.startElement(node)
return
示例12: main
def main():
from clang.cindex import Index
from pprint import pprint
from optparse import OptionParser, OptionGroup
global opts
parser = OptionParser("usage: %prog [options] {filename} [clang-args*]")
parser.add_option("", "--show-ids", dest="showIDs",
help="Don't compute cursor IDs (very slow)",
default=False)
parser.add_option("", "--max-depth", dest="maxDepth",
help="Limit cursor expansion to depth N",
metavar="N", type=int, default=None)
parser.disable_interspersed_args()
(opts, args) = parser.parse_args()
if len(args) == 0:
parser.error('invalid number arguments')
index = Index.create()
tu = index.parse(None, args)
if not tu:
parser.error("unable to load input")
pprint(('diags', map(get_diag_info, tu.diagnostics)))
pprint(('nodes', get_info(tu.cursor)))
示例13: __init__
def __init__(self, lang, header, api_headers, check_all, args, verbose):
index = Index.create()
self.is_cpp = True if lang == 'c++' else False
self.clang_args = ['-x', lang]
self.translation_unit = index.parse(header, args + self.clang_args,
options=1)
if verbose:
for diag in self.translation_unit.diagnostics:
if diag.severity == 2:
msg = '\033[93mWARNING : '
elif diag.severity == 3:
msg = '\033[91mERROR : '
elif diag.severity == 4:
msg = '\033[91mFATAL : '
msg += '{} at {} line {}, column {}\033[00m'
print (msg.format(diag.spelling, diag.location.file,
diag.location.line, diag.location.column))
self.api_headers = api_headers
self.check_all = check_all
self.enum_constant_decls = []
self.function_decls = []
self.var_decls = []
self.macro_defs = []
self.record_decls = []
self.namespaces = []
示例14: main
def main():
import sys
from clang.cindex import Index, Config
from io import open
# TODO: Don't hard code the clang library path
Config.set_library_path("/usr/lib/llvm-3.3/lib")
if len(sys.argv) == 1 or len(sys.argv) > 3:
usage()
sys.exit(1)
cppFile = str()
overwrite = False
if "-o" in sys.argv:
overwrite = True
cppFile = sys.argv[len(sys.argv) - 1]
index = Index.create()
transUnit = index.parse(cppFile)
docBlocks = get_doc_comments(transUnit.cursor, cppFile)
source = source_with_doc_blocks(cppFile, docBlocks)
if overwrite:
with open(cppFile, "w") as file:
file.write(unicode(source))
else:
sys.stdout.write(unicode(source))
示例15: __init__
def __init__(self):
self.index = Index.create()
self.ast = Object()
self.mapping = {
}
super(Parser, self).__init__()