当前位置: 首页>>代码示例>>Python>>正文


Python Index.create方法代码示例

本文整理汇总了Python中clang.cindex.Index.create方法的典型用法代码示例。如果您正苦于以下问题:Python Index.create方法的具体用法?Python Index.create怎么用?Python Index.create使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在clang.cindex.Index的用法示例。


在下文中一共展示了Index.create方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: ParseCurrentFile

# 需要导入模块: from clang.cindex import Index [as 别名]
# 或者: from clang.cindex.Index import create [as 别名]
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)
开发者ID:SkidanovAlex,项目名称:CtrlK,代码行数:61,代码来源:ctrlk_plugin.py

示例2: skip_if_no_clang

# 需要导入模块: from clang.cindex import Index [as 别名]
# 或者: from clang.cindex.Index import create [as 别名]
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))
开发者ID:kaushikmit,项目名称:coala,代码行数:11,代码来源:__init__.py

示例3: clang_available

# 需要导入模块: from clang.cindex import Index [as 别名]
# 或者: from clang.cindex.Index import create [as 别名]
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)
开发者ID:Asnelchristian,项目名称:coala-bears,代码行数:13,代码来源:ClangBear.py

示例4: clang_available

# 需要导入模块: from clang.cindex import Index [as 别名]
# 或者: from clang.cindex.Index import create [as 别名]
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)
开发者ID:Anmolbansal1,项目名称:coala-bears,代码行数:16,代码来源:ClangBear.py

示例5: test_code_complete

# 需要导入模块: from clang.cindex import Index [as 别名]
# 或者: from clang.cindex.Index import create [as 别名]
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)
开发者ID:plotnikovanton,项目名称:dotfiles,代码行数:37,代码来源:test_code_completion.py

示例6: test_location

# 需要导入模块: from clang.cindex import Index [as 别名]
# 或者: from clang.cindex.Index import create [as 别名]
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)
开发者ID:ACSOP,项目名称:android_external_clang,代码行数:29,代码来源:test_location.py

示例7: __init__

# 需要导入模块: from clang.cindex import Index [as 别名]
# 或者: from clang.cindex.Index import create [as 别名]
    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 = {}
开发者ID:Allen76,项目名称:Embroidermodder,代码行数:36,代码来源:astwrapper.py

示例8: get_tu

# 需要导入模块: from clang.cindex import Index [as 别名]
# 或者: from clang.cindex.Index import create [as 别名]
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
开发者ID:shaochuan,项目名称:clang-tools,代码行数:9,代码来源:v8_inherit_graph_demo.py

示例9: main

# 需要导入模块: from clang.cindex import Index [as 别名]
# 或者: from clang.cindex.Index import create [as 别名]
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)
开发者ID:john-tornblom,项目名称:playground,代码行数:37,代码来源:incdeps.py

示例10: test_file

# 需要导入模块: from clang.cindex import Index [as 别名]
# 或者: from clang.cindex.Index import create [as 别名]
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>"
开发者ID:4ntoine,项目名称:clang,代码行数:9,代码来源:test_file.py

示例11: parse

# 需要导入模块: from clang.cindex import Index [as 别名]
# 或者: from clang.cindex.Index import create [as 别名]
 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
开发者ID:chmod007,项目名称:ctypeslib,代码行数:31,代码来源:clangparser.py

示例12: main

# 需要导入模块: from clang.cindex import Index [as 别名]
# 或者: from clang.cindex.Index import create [as 别名]
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)))
开发者ID:5432935,项目名称:crossbridge,代码行数:30,代码来源:cindex-dump.py

示例13: __init__

# 需要导入模块: from clang.cindex import Index [as 别名]
# 或者: from clang.cindex.Index import create [as 别名]
    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 = []
开发者ID:Samsung,项目名称:iotjs,代码行数:30,代码来源:clang_translation_unit_visitor.py

示例14: main

# 需要导入模块: from clang.cindex import Index [as 别名]
# 或者: from clang.cindex.Index import create [as 别名]
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))
开发者ID:jack-karamanian,项目名称:autocmt.py,代码行数:31,代码来源:autocmt.py

示例15: __init__

# 需要导入模块: from clang.cindex import Index [as 别名]
# 或者: from clang.cindex.Index import create [as 别名]
  def __init__(self):
    self.index = Index.create()
    self.ast = Object()
    self.mapping = {

    }
    super(Parser, self).__init__()
开发者ID:ViciousPotato,项目名称:ClangDOM,代码行数:9,代码来源:clangdom.py


注:本文中的clang.cindex.Index.create方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。