示例#1
0
def main(args):
    clang_args = None
    args_split = [i for i, arg in enumerate(args) if arg == "--"]
    if args_split:
        args, clang_args = args[:args_split[0]], args[args_split[0] + 1:]

    default_config = os.path.dirname(args[0]) + "/gmock.conf"

    parser = OptionParser(usage="usage: %prog [options] files...")
    parser.add_option("-c", "--config", dest="config", default=default_config, help="config FILE (default='gmock.conf')", metavar="FILE")
    parser.add_option("-d", "--dir", dest="path", default=".", help="dir for generated mocks (default='.')", metavar="DIR")
    parser.add_option("-e", "--expr", dest="expr", default="", help="limit to interfaces within expression (default='')", metavar="LIMIT")
    parser.add_option("-l", "--libclang", dest="libclang", default=None, help="path to libclang.so (default=None)", metavar="LIBCLANG")
    (options, args) = parser.parse_args(args)

    if len(args) == 1:
        parser.error("at least one file has to be given")

    config = {}
    with open(options.config, 'r') as file:
        exec(file.read(), config)

    if options.libclang:
      Config.set_library_file(options.libclang)

    return mock_generator(
        files = args[1:],
        args = clang_args,
        expr = options.expr,
        path = options.path,
        mock_file_hpp = config['mock_file_hpp'],
        file_template_hpp = config['file_template_hpp'],
        mock_file_cpp = config['mock_file_cpp'],
        file_template_cpp = config['file_template_cpp']
    ).generate()
示例#2
0
def _run_checker(checker, argv):
    global clang_library_file
    if argv.execution_mode == 'full':
        files = core.get_files(argv.location[0])
    else:
        files = core.get_files(argv.location[0], checker.get_pattern_hint())
    if not files:
        cnf = 'Could not find any problem related to '
        cnf += checker.get_problem_type().lower()
        sys.stderr.write(cnf + '\n')
    else:
        print(__current_wip(checker, files))
        visitor = Visitor(checker)
        if clang_library_file == '':
            clang_libraries = glob.glob('/usr/lib*/libclang.so*')
            reverse_list = list(reversed(clang_libraries))
            if reverse_list:
                clang_library_file = reverse_list[0]
                Config.set_library_file(clang_library_file)
        index = Index.create()
        for c_file in files:
            args = ["-ferror-limit=9999"] + _include_paths()
            root = index.parse(
                c_file,
                args=args,
                options=TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD)
            ReportBlocker.blocked_lines = []
            visitor.visit(root.cursor, c_file)
def sync_configure_path(libclangPath):
    mutex2 = threading.Lock()
    if Config.loaded == False:
        mutex2.acquire()
        if Config.loaded == False:
            Config.set_library_file(libclangPath)
        mutex2.release()
示例#4
0
def init_clang():

    global initialized, ix

    if not initialized:
        conda_prefix = Path(getenv('CONDA_PREFIX'))
        Config.set_library_file(conda_prefix / 'lib' / 'libclang.so')

        # Monkeypatch clang
        monkeypatch_cursor('is_virtual', 'clang_isVirtualBase', [Cursor],
                           c_uint)

        monkeypatch_cursor('is_inline', 'clang_Cursor_isFunctionInlined',
                           [Cursor], c_uint)

        monkeypatch_cursor('get_specialization',
                           'clang_getSpecializedCursorTemplate', [Cursor],
                           Cursor)

        monkeypatch_cursor('get_template_kind', 'clang_getTemplateCursorKind',
                           [Cursor], c_uint)

        monkeypatch_cursor('get_num_overloaded_decl',
                           'clang_getNumOverloadedDecls', [Cursor], c_uint)

        initialized = True
        ix = Index.create()
示例#5
0
    def run(self):
        Config.set_library_file(self.libClangPath)
        
        index = Index.create()
        tree = index.parse(self.path, args=self.args)

        self.walker.startWalk(tree.cursor, self.generator)
    def __init__(self, lang, header, api_headers, check_all, args):
        # TODO: Avoid hard-coding paths and args in general.
        Config.set_library_file('libclang-6.0.so.1')
        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)

        for diag in self.translation_unit.diagnostics:
            msg = '\033[91mERROR : {} 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 = []
示例#7
0
def initClangComplete(clang_complete_flags, clang_compilation_database,
                      library_path):
    global index

    debug = int(vim.eval("g:clang_debug")) == 1
    quiet = int(vim.eval("g:clang_quiet")) == 1

    if library_path:
        if os.path.isdir(library_path):
            Config.set_library_path(library_path)
        else:
            Config.set_library_file(library_path)

    Config.set_compatibility_check(False)

    try:
        index = Index.create()
    except Exception as e:
        if quiet:
            return 0
        if library_path:
            suggestion = "Are you sure '%s' contains libclang?" % library_path
        else:
            suggestion = "Consider setting g:clang_library_path."

        if debug:
            exception_msg = str(e)
        else:
            exception_msg = ''

        print('''Loading libclang failed, completion won't be available. %s
    %s
    ''' % (suggestion, exception_msg))
        return 0

    global builtinHeaderPath
    builtinHeaderPath = None
    if not canFindBuiltinHeaders(index):
        builtinHeaderPath = getBuiltinHeaderPath(library_path)

        if not builtinHeaderPath:
            print("WARNING: libclang can not find the builtin includes.")
            print("         This will cause slow code completion.")
            print("         Please report the problem.")

    global translationUnits
    translationUnits = dict()
    global complete_flags
    complete_flags = int(clang_complete_flags)
    global compilation_database
    if clang_compilation_database != '':
        compilation_database = CompilationDatabase.fromDirectory(
            clang_compilation_database)
    else:
        compilation_database = None
    global libclangLock
    libclangLock = threading.Lock()
    return 1
示例#8
0
文件: libclang.py 项目: looseyi/k-vim
def initClangComplete(clang_complete_flags, clang_compilation_database,
                      library_path):
  global index

  debug = int(vim.eval("g:clang_debug")) == 1
  quiet = int(vim.eval("g:clang_quiet")) == 1

  if library_path:
    if os.path.isdir(library_path):
      Config.set_library_path(library_path)
    else:
      Config.set_library_file(library_path)

  Config.set_compatibility_check(False)

  try:
    index = Index.create()
  except Exception as e:
    if quiet:
      return 0
    if library_path:
      suggestion = "Are you sure '%s' contains libclang?" % library_path
    else:
      suggestion = "Consider setting g:clang_library_path."

    if debug:
      exception_msg = str(e)
    else:
      exception_msg = ''

    print('''Loading libclang failed, completion won't be available. %s
    %s
    ''' % (suggestion, exception_msg))
    return 0

  global builtinHeaderPath
  builtinHeaderPath = None
  if not canFindBuiltinHeaders(index):
    builtinHeaderPath = getBuiltinHeaderPath(library_path)

    if not builtinHeaderPath:
      print("WARNING: libclang can not find the builtin includes.")
      print("         This will cause slow code completion.")
      print("         Please report the problem.")

  global translationUnits
  translationUnits = dict()
  global complete_flags
  complete_flags = int(clang_complete_flags)
  global compilation_database
  if clang_compilation_database != '':
    compilation_database = CompilationDatabase.fromDirectory(clang_compilation_database)
  else:
    compilation_database = None
  global libclangLock
  libclangLock = threading.Lock()
  return 1
示例#9
0
def main(args):
    clang_args = None
    args_split = [i for i, arg in enumerate(args) if arg == "--"]
    if args_split:
        args, clang_args = args[:args_split[0]], args[args_split[0] + 1:]

    default_config = os.path.dirname(args[0]) + "/gmock.conf"

    parser = OptionParser(usage="usage: %prog [options] files...")
    parser.add_option("-c",
                      "--config",
                      dest="config",
                      default=default_config,
                      help="config FILE (default='gmock.conf')",
                      metavar="FILE")
    parser.add_option("-d",
                      "--dir",
                      dest="path",
                      default=".",
                      help="dir for generated mocks (default='.')",
                      metavar="DIR")
    parser.add_option(
        "-e",
        "--expr",
        dest="expr",
        default="",
        help="limit to interfaces within expression (default='')",
        metavar="LIMIT")
    parser.add_option("-l",
                      "--libclang",
                      dest="libclang",
                      default=None,
                      help="path to libclang.so (default=None)",
                      metavar="LIBCLANG")
    (options, args) = parser.parse_args(args)

    if len(args) == 1:
        parser.error("at least one file has to be given")

    config = {}
    with open(options.config, 'r') as file:
        exec(file.read(), config)

    if options.libclang:
        Config.set_library_file(options.libclang)

    return mock_generator(
        files=args[1:],
        args=clang_args,
        expr=options.expr,
        path=options.path,
        mock_file_hpp=config['mock_file_hpp'],
        file_template_hpp=config['file_template_hpp'],
        mock_file_cpp=config['mock_file_cpp'],
        file_template_cpp=config['file_template_cpp']).generate()
示例#10
0
def clang_setup(force=False):
    """Try to find and configure libclang location on RTD."""
    if 'READTHEDOCS' in os.environ or force:
        try:
            result = subprocess.run(['llvm-config', '--libdir'],
                                    check=True, capture_output=True, encoding='utf-8')
            libdir = result.stdout.strip()

            # For some reason there is no plain libclang.so symlink on RTD.
            from clang.cindex import Config
            Config.set_library_file(os.path.join(libdir, 'libclang.so.1'))
        except Exception as e:
            print(e)
示例#11
0
文件: analyzer.py 项目: lp6m/SWORDS
    def __init__(self, filename, llvm_libdir=None, llvm_libfile=None):
        self.prototypes = []
        self.functions = {}

        self.filename = filename

        if llvm_libdir is not None:
            Config.set_library_path(llvm_libdir)

        if llvm_libfile is not None:
            Config.set_library_file(llvm_libfile)

        self._parse()
示例#12
0
def main(prog_path, libclang_path, api_header, pch_dst, *libclang_args):
    Config.set_library_file(libclang_path)
    index = Index.create(excludeDecls=True)
    # We should really want to use a compilation database here, except that it's only supported by makefiles...
    tu = index.parse(api_header,
                     args=libclang_args,
                     options=TranslationUnit.PARSE_INCOMPLETE
                     | TranslationUnit.PARSE_SKIP_FUNCTION_BODIES)

    errors = diagnose_errors(list_diagnostics(tu))
    if errors:
        raise errors
    else:
        tu.save(
            pch_dst
        )  # We'll need this in a minute, and there's no way to just get it in RAM
示例#13
0
def find_clang_posix() -> None:
    # Find the clang library. On some distros, the clang library is not called `libclang.so`, for
    # example on Ubuntu, it is `libclang.so.1`, making cindex unable to find it.
    proc: subprocess.CompletedProcess = subprocess.run(
        ['llvm-config', '--libdir'],
        stdin=subprocess.PIPE,
        stderr=subprocess.PIPE,
        stdout=subprocess.PIPE,
        encoding='utf-8')

    if proc.returncode != 0:
        raise RuntimeError('Could not find LLVM path')

    clang_libs: List[str] = glob.glob(
        os.path.join(proc.stdout.strip(), 'libclang.so*'))
    if len(clang_libs) == 0:
        raise RuntimeError(
            'Could not find libclang.so, make sure Clang is installed')
    Config.set_library_file(clang_libs[0])
示例#14
0
    def __init__(self, hw_file_name, json_file_name, llvm_libdir,
                 llvm_libfile):

        #llvmのファイルをセット
        if llvm_libfile != None:
            Config.set_library_file(llvm_libfile)
        if llvm_libdir != None:
            Config.set_library_path(llvm_libdir)

        #clangにソースコードをぶちこむ
        self.index = clang.cindex.Index.create()
        self.tree = self.index.parse(hw_file_name)

        self.hw_file_name = hw_file_name
        self.json_file_name = json_file_name

        #抽出するデータたち
        self.func_name = ""
        self.func_decl = ""
        self.return_type = ""
        self.parm_decls = []
        self.parm_types = []
        self.parm_suffixs = []
        self.parm_data_numbers = []
        self.parm_interfaces = []
        self.parm_bundles = []
        self.parm_directions = []
        self.parm_slave_bundles_noduplication = []
        self.bundle_port_dic = {}
        self.use_hp_ports = False

        self.func_find_flag = False
        self.func_find_flag_once = False

        #Json/C解析
        self.__analyzeJson()
        self.__extractParameter()

        #関数名の成形
        self.func_name_u = self.func_name.upper()
        self.func_name_l = self.func_name.lower()
        self.func_name_ul = (self.func_name[0]).upper() + (
            self.func_name[1:]).lower()
示例#15
0
def try_clang_cindex():
    from clang.cindex import Index, Config, TranslationUnit
    Config.set_library_file(f"/usr/lib/llvm-9/lib/libclang.so")

    filename = "/tmp/clang_cindex_tmp_src.cc"
    with open(filename, "w") as f:
        f.write(code)

    index = Index.create()
    t_start = time.time()
    tu = TranslationUnit.from_source(
        filename=filename,
        index=index,
        args=[
            f"-I/usr/include/eigen3",
        ],
    )
    dt = time.time() - t_start
    return dt
示例#16
0
    def init(self):

        clang_complete_flags = self.vim.eval('g:clang_complete_lib_flags')
        library_path = self.vim.eval('g:clang_library_path')
        clang_compilation_database = self.vim.eval(
            'g:clang_compilation_database')

        if library_path:
            if os.path.isdir(library_path):
                Config.set_library_path(library_path)
            else:
                Config.set_library_file(library_path)

        Config.set_compatibility_check(False)

        try:
            self.index = Index.create()
        except Exception as e:
            if library_path:
                suggestion = "Are you sure '%s' contains libclang?" % library_path
            else:
                suggestion = "Consider setting g:clang_library_path."

            logger.exception(
                "Loading libclang failed, completion won't be available. %s %s ",
                suggestion, exception_msg)
            return 0

        if not self.canFindBuiltinHeaders(self.index):
            self.builtinHeaderPath = self.getBuiltinHeaderPath(library_path)

            if not self.builtinHeaderPath:
                logger.warn("libclang find builtin header path failed: %s",
                            self.builtinHeaderPath)

        self.complete_flags = int(clang_complete_flags)
        if clang_compilation_database != '':
            self.compilation_database = CompilationDatabase.fromDirectory(
                clang_compilation_database)
        else:
            self.compilation_database = None
        return 1
示例#17
0
def main(prog_path, libclang_path, api_header, pch_dst, api_casts_dst, namespace_filter, function_filter, namespace_dst, *libclang_args):
	accept_from = set(namespace_filter.split(" "))
	valid_function_prefixes = set(function_filter.split(" "))
	
	Config.set_library_file(libclang_path)
	index = Index.create(excludeDecls=True)
	# We should really want to use a compilation database here, except that it's only supported by makefiles...
	tu = TranslationUnit.from_ast_file(pch_dst, index)

	filt = FFIFilter(lambda s: s[0] in accept_from,
		lambda x: any([x.displayname.startswith(prefix) for prefix in valid_function_prefixes]),
		solve_template_base_config(index, pch_dst))
	
	code_gen = CodeGen(prog_path,
						pre_hook = lambda: ("namespace %s {" % (namespace_dst,), 4),
						post_hook = lambda indent: "}")
	
	with open(api_casts_dst, 'w') as out_handle:
		from os.path import abspath
		out_handle.write(code_gen(api_header, filt.exposed_types, filt.emit_table_for_TU(tu.cursor)))
def main(filename):
    """Main function"""
    functions = []
    tree = []
    Config.set_library_file(
        "/Library/Developer/CommandLineTools/usr/lib/libclang.dylib")

    index = Index.create()
    ast = index.parse(None, [filename])
    if not ast:
        print("Unable to parse file")
        sys.exit(1)

    # Step 1: Find all the C/ObjC functions
    functions = [x for x in ast.cursor.get_children() if is_function(x)]

    # Step 1a: Add in ObjC class methods
    for item in ast.cursor.get_children():
        if is_implementation(item):
            functions += [x for x in item.get_children() if is_function(x)]

    # Step 2: Filter out all of the functions that are Lua->C calls
    functions = [x for x in functions if not is_lua_call(x)]

    # Step 3: Recursively walk the remaining functions
    tree = [build_tree(x, False) for x in functions]

    # Step 4: Filter the functions down to those which contain Lua calls
    tree = [x for x in tree if contains_lua_calls(x)]

    for thing in tree:
        stacktxt = "NO STACKGUARD"
        hasstackentry = "_lua_stackguard_entry" in thing['tokens']
        hasstackexit = "_lua_stackguard_exit" in thing['tokens']
        if hasstackentry and hasstackexit:
            continue
        if hasstackentry and not hasstackexit:
            stacktxt = "STACK ENTRY, BUT NO EXIT"
        if hasstackexit and not hasstackentry:
            stacktxt = "STACK EXIT, BUT NO ENTRY (THIS IS A CRASH)"
        print(u"%s :: %s :: %s" % (filename, thing['spelling'], stacktxt))
def main(filename):
    """Main function"""
    functions = []
    tree = []
    Config.set_library_file(
        "/Library/Developer/CommandLineTools/usr/lib/libclang.dylib")

    index = Index.create()
    ast = index.parse(None, [filename])
    if not ast:
        print("Unable to parse file")
        sys.exit(1)

    # Step 1: Find all the C/ObjC functions
    functions = [x for x in ast.cursor.get_children() if is_function(x)]

    # Step 1a: Add in ObjC class methods
    for item in ast.cursor.get_children():
        if is_implementation(item):
            functions += [x for x in item.get_children() if is_function(x)]

    # Step 2: Filter out all of the functions that are Lua->C calls
    functions = [x for x in functions if not is_lua_call(x)]

    # Step 3: Recursively walk the remaining functions
    tree = [build_tree(x, False) for x in functions]

    # Step 4: Filter the functions down to those which contain Lua calls
    tree = [x for x in tree if contains_lua_calls(x)]

    for thing in tree:
        stacktxt = "NO STACKGUARD"
        hasstackentry = "_lua_stackguard_entry" in thing['tokens']
        hasstackexit = "_lua_stackguard_exit" in thing['tokens']
        if hasstackentry and hasstackexit:
            continue
        if hasstackentry and not hasstackexit:
            stacktxt = "STACK ENTRY, BUT NO EXIT"
        if hasstackexit and not hasstackentry:
            stacktxt = "STACK EXIT, BUT NO ENTRY (THIS IS A CRASH)"
        print(u"%s :: %s :: %s" % (filename, thing['spelling'], stacktxt))
示例#20
0
def init_clang(path=None):

    global initialized, ix

    if not initialized:
        conda_prefix = Path(getenv('CONDA_PREFIX', ''))

        if path:
            pass
        elif platform.startswith('win'):
            path = conda_prefix / 'Library' / 'bin' / 'libclang.dll'
        elif platform.startswith('linux') or platform.startswith('freebsd'):
            path = conda_prefix / 'lib' / 'libclang.so'
        elif platform.startswith('darwin'):
            path = conda_prefix / 'lib' / 'libclang.dylib'

        Config.set_library_file(path)

        # Monkeypatch clang
        monkeypatch_cursor('is_virtual', 'clang_isVirtualBase', [Cursor],
                           c_uint)

        monkeypatch_cursor('is_inline', 'clang_Cursor_isFunctionInlined',
                           [Cursor], c_uint)

        monkeypatch_cursor('get_specialization',
                           'clang_getSpecializedCursorTemplate', [Cursor],
                           Cursor)

        monkeypatch_cursor('get_template_kind', 'clang_getTemplateCursorKind',
                           [Cursor], c_uint)

        monkeypatch_cursor('get_num_overloaded_decl',
                           'clang_getNumOverloadedDecls', [Cursor], c_uint)

        initialized = True
        ix = Index.create()
示例#21
0
def main():
    from clang.cindex import Index, Config
    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="Compute cursor IDs (very slow)",
                      action="store_true", 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()

    from pathlib import Path as path

    file = path('../src/simple.cpp')
    #file = path('/home/mpercossi/.conan/data/range-v3/0.11.0/_/_/package/5ab84d6acfe1f23c4fae0ab88f26e3a396351ac9/include/range/v3/view/single.hpp')

    all_args = ['--show-ids', str(file.absolute()), '-stdlib=libc++', '-std=c++20', '-L/usr/lib/llvm-11/lib', '-I/usr/lib/llvm-11/include', '-std=c++20'] + EXTRA_ARGS.split(' ')
    print(f"{' '.join(all_args)}")
    (opts, args) = parser.parse_args(['--show-ids', str(file.absolute()), '-stdlib=libc++', '-std=c++20', '-L/usr/lib/llvm-11/lib', '-I/usr/lib/llvm-11/include', '-std=c++20'] + EXTRA_ARGS.split(' '))

    if len(args) == 0:
        parser.error('invalid number arguments')

    Config.set_library_file('/usr/lib/llvm-11/lib/libclang-11.so')
    index = Index.create()
    tu = index.parse(None, args)
    if not tu:
        parser.error("unable to load input")

    #pprint(('diags', [get_diag_info(d) for d in  tu.diagnostics]))
    pprint(('nodes', get_defns(tu.cursor)))
示例#22
0
文件: check.py 项目: wyjw/space-tree
def main():
    from pprint import pprint

    from optparse import OptionParser, OptionGroup
    import os

    global opts

    parser = OptionParser("usage: %prog [options] {filename} [clang-args*]")
    parser.add_option("",
                      "--show-ids",
                      dest="showIDs",
                      help="Compute cursor IDs (very slow)",
                      action="store_true",
                      default=False)
    parser.add_option("",
                      "--max-depth",
                      dest="maxDepth",
                      help="Limit cursor expansion to depth N",
                      metavar="N",
                      type=int,
                      default=None)
    parser.add_option("",
                      "--old",
                      dest="old",
                      action="store_true",
                      default=False)
    parser.disable_interspersed_args()
    (opts, args) = parser.parse_args()

    tmpDir = "/tmp/"
    print(args)
    # set config library
    Config.set_library_file("/usr/lib/llvm-10/lib/libclang.so")
    if len(args) == 0:
        #parser.error('invalid number arguments')

        kInputsDir = os.getcwd() + '/../CutDownPerconaFT/'
        print("Directory is " + str(kInputsDir))
        index = Index.create()
        with open('files.txt', 'r') as f:
            for line in f:
                if (str(line)[0] == '#'):
                    print("Passed " + line)
                    continue
                if (str(line.rstrip())[-1] != 'h'):
                    print("Passed " + line)
                    continue
                addr = '../CutDownPerconaFT/' + str(line.rstrip())

                # this adds some letters at the end of the word so that clang thinks it is a C++ file
                nfile = tmpDir + line.rstrip().split("/")[-1] + "pp"
                cmd = "cp " + addr + " " + nfile
                print("Command is " + cmd + " location is " + nfile)
                os.system(cmd)
                #print("Parsing " + addr)
                #tu = index.parse(None, [str(addr)])
                tu = index.parse(None, [str(nfile)])
                if not tu:
                    parser.error("unable to load input")

                get_struct(tu.cursor)
                get_class(tu.cursor)

    else:
        index = Index.create()
        tu = index.parse(None, args)
        if not tu:
            parser.error("unable to load input")

        get_struct(tu.cursor)
        get_class(tu.cursor)

    pprint(struct_defs)
    pprint(class_defs)
    pprint(('diags', [get_diag_info(d) for d in tu.diagnostics]))

    if len(args) != 0:
        if opts.old == True:
            index = Index.create()
            tu = index.parse(None, args)
            if not tu:
                parser.error("unable to load input")
            finalDict = get_info(tu.cursor)
            pprint(finalDict)

    needed_convs = []
    #use_struct(struct_defs)
    gen_struct_from_class(class_defs)
示例#23
0
 def __init__(self, libclang_path, srcdir):
     if Config.library_file != libclang_path:
         Config.set_library_file(libclang_path)
     self.srcdir = srcdir
示例#24
0
elif platform.system() == "Darwin":  # IS_MAC
    slash = '/'
    libclang_path = '/Library/Developer/CommandLineTools/usr/lib/libclang.dylib'
    pipe = os.popen('mdfind -name "libclang.dylib"').readlines()
    if not pipe:
        raise Exception("Please install clang with libclang.dylib")
elif platform.system() == "Linux":  # IS_LINUX
    slash = '/'
    libclang_path = '/usr/lib/llvm-7.0/lib/libclang-7.0.so.1'
    if not os.path.exists(libclang_path):
        raise Exception("Please install clang with libclang.so")

if Config.loaded == True:
    pass
else:
    Config.set_library_file(libclang_path)

syspath = ccsyspath.system_include_paths('clang++')
incargs = [b'-I' + inc for inc in syspath]
args = '-x c++'.split() + incargs

parser = OptionParser()
parser.add_option("-s", "--source_dir", action="store", dest="source_dir", help="read input data from source directory")
parser.add_option("-t", "--target_file", action="store", dest="target_file", help="parse data to target file")
(options, _) = parser.parse_args()
INPUT_SOURCE_ORIGIN = []
INPUT_SOURCE_ORIGIN.append(options.source_dir)

_VAR_DECL = []  # record variable offsets
_DECL_REF_EXPR = []  # record variable reference offsets
_NODE_DICT = {}  # record node: domain
示例#25
0
            'impls': [g.implementation() for g in generators],
            'headers':
            [x for x in [g.header() for g in generators] if len(x) > 0],
            'object_names': [o.name for o in h.objects],
            'attrs': sorted(all_attrs),
            'custom_headers': header.custom_headers
        }


if __name__ == '__main__':
    parser = ArgumentParser()
    parser.add_argument('--clang-lib',
                        default='/usr/lib/llvm-6.0/lib/libclang.so.1')
    parser.add_argument('--out-dir', default='.')
    parser.add_argument('header')
    parser.add_argument('custom', nargs='*', default=[])
    args = parser.parse_args()

    Config.set_library_file(args.clang_lib)

    h = TAIHeader(args.header)
    for c in args.custom:
        h.add_custom(c)

    g = TAIMetadataGenerator(h)
    with open('{}/taimetadata.h'.format(args.out_dir), 'w') as f:
        f.write(g.header())

    with open('{}/taimetadata.c'.format(args.out_dir), 'w') as f:
        f.write(g.implementation())
示例#26
0
文件: tools.py 项目: skidzo/autowig
from ConfigParser import ConfigParser
from path import path

if not Config.loaded:
    _path_ = path(__file__)
    while len(_path_) > 0 and not str(_path_.name) == 'src':
        _path_ = _path_.parent
    _path_ = _path_.parent
    configparser = ConfigParser()
    configparser.read(_path_/'metainfo.ini')
    config = dict(configparser.items('libclang'))

    if 'path' in config:
            Config.set_library_path(config['path'])
    elif 'file' in config:
        Config.set_library_file(config['file'])
    else:
        raise IOError('cannot find libclang path or file')

class AST(object):
    """
    """

    def __init__(self, *translation_units):
        """
        """
        if any(not isinstance(translation_unit, TranslationUnit) for translation_unit in translation_units):
            raise TypeError('`translation_units` parameter')
        self._translation_units = translation_units

    def function(self, child):
示例#27
0
def main(argv=None):
    """
    Takes a set of C++ header files and generate a JSON output file describing
    the objects found in them. This output is intended to support more
    convenient access to a set of cppyy-supported bindings.

    Examples:

        INC=/usr/include
        QT5=$INC/x86_64-linux-gnu/qt5
        KF5=$INC/KF5
        INCDIRS="\\\\-I$KF5/KConfigCore;\\\\-I$QT5/QtXml;\\\\-I$QT5/QtCore"
        STDDIRS="\\\\-I$Qt5/mkspecs/linux-g++-64\\\\;-I$KF5;\\\\-I$QT5"
        FLAGS="\\\\-fvisibility=hidden;\\\-D__PIC__;\\\\-Wno-macro-redefined;\\\\-std=c++14"

        cppyy-generator --flags "$FLAGS;$INCDIRS;$STDDIRS" KF5/Config/Config.map $INC/KF5/KConfigCore/*
    """
    if argv is None:
        argv = sys.argv
    parser = argparse.ArgumentParser(epilog=inspect.getdoc(main),
                                     formatter_class=HelpFormatter)
    parser.add_argument("-v", "--verbose", action="store_true", default=False, help=_("Enable verbose output"))
    parser.add_argument("--flags", default="",
                        help=_("Semicolon-separated C++ compile flags to use, escape leading - or -- with \\"))
    parser.add_argument("--libclang", help=_("libclang library to use for parsing"))
    parser.add_argument("output", help=_("Output filename to write"))
    parser.add_argument("sources", nargs="+", help=_("C++ headers to process"))
    try:
        args = parser.parse_args(argv[1:])
        if args.verbose:
            logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)s %(levelname)s: %(message)s')
        else:
            logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')
        flags = []
        for f in args.flags.lstrip().split(";"):
            if f.startswith("\\-\\-"):
                flags.append("--" + f[4:])
            elif f.startswith("\\-"):
                flags.append("-" + f[2:])
            elif f:
                flags.append(f)
        #
        # Load the given libclang.
        #
        if args.libclang:
            Config.set_library_file(args.libclang)
        lib = Config().lib
        import ctypes
        from clang.cindex import Type
        items = [
            ("clang_Type_getNumTemplateArguments", [Type], ctypes.c_size_t),
        ]
        for item in items:
            func = getattr(lib, item[0])
            if len(item) >= 2:
                func.argtypes = item[1]

            if len(item) >= 3:
                func.restype = item[2]

            if len(item) == 4:
                func.errcheck = item[3]
        #
        # Generate!
        #
        g = CppyyGenerator(flags, verbose=args.verbose)
        mapping = g.create_mapping(args.sources)
        with open(args.output, "w") as f:
            json.dump(mapping, f, indent=1, sort_keys=True)
        return 0
    except Exception as e:
        tbk = traceback.format_exc()
        print(tbk)
        return 1
示例#28
0
                unsaved_contents == self.cached_contents):
            return translation_unit
        options = 0  # There are no reparse options available in libclang yet.
        translation_unit.reparse(self._make_files(unsaved_contents), options)
        self.cached_contents = unsaved_contents
        if self.completion_cache is not None:
            self.completion_cache.invalidate()
        return translation_unit

    def _register_custom_clang_functions(self):
        # Extend the Clang C bindings with the additional required functions.
        for item in Server.CUSTOM_CLANG_FUNCTIONS:
            func = getattr(self.custom_clang_lib, item[0])
            func.argtypes = item[1]
            func.restype = item[2]


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('src', metavar='<path>', type=str,
                        help='Full path of source file to analyze.')
    parser.add_argument('flags', metavar='<flags>', type=str, nargs='*',
                        help='Extra flags to pass to Clang.')
    parser.add_argument('--libclang-file', help='Path to libclang dynamic library')
    args = parser.parse_args()

    if args.libclang_file:
        Config.set_library_file(args.libclang_file)
    set_up_logging(args.src)
    Server(args.src, args.flags, sys.stdin, sys.stdout).run()
示例#29
0
            self.completion_cache.invalidate()
        return translation_unit

    def _register_custom_clang_functions(self):
        # Extend the Clang C bindings with the additional required functions.
        for item in Server.CUSTOM_CLANG_FUNCTIONS:
            func = getattr(self.custom_clang_lib, item[0])
            func.argtypes = item[1]
            func.restype = item[2]


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('src',
                        metavar='<path>',
                        type=str,
                        help='Full path of source file to analyze.')
    parser.add_argument('flags',
                        metavar='<flags>',
                        type=str,
                        nargs='*',
                        help='Extra flags to pass to Clang.')
    parser.add_argument('--libclang-file',
                        help='Path to libclang dynamic library')
    args = parser.parse_args()

    if args.libclang_file:
        Config.set_library_file(args.libclang_file)
    set_up_logging(args.src)
    Server(args.src, args.flags, sys.stdin, sys.stdout).run()
示例#30
0
文件: schema.py 项目: anscor/CodeGrow
    def resolve_code_syntax_cmp(self, info, **kwargs):
        # 要比较的提交id
        submission_id = kwargs.get("submission_id", None)
        if not submission_id:
            return None

        pre_submission, submission = Query.__get_submission(
            submission_id, info)
        # 提交不存在、两次提交中有编译错误不进行比较
        if (not pre_submission or pre_submission.result == "Compile Error"
                or submission.result == "Compile Error"):
            return None

        if not Config.loaded:
            Config.set_library_file(settings.LIBCLANG_FILE)

        old_lines = pre_submission.code.replace("\r\n", "\n").split("\n")
        new_lines = submission.code.replace("\r\n", "\n").split("\n")

        old_nodes_lines, new_nodes_lines = (
            Query.__code_to_node_line(pre_submission.code),
            Query.__code_to_node_line(submission.code),
        )

        eq_lines = Query.__lcs(old_lines, new_lines, old_nodes_lines,
                               new_nodes_lines)
        eq_lines = sorted(eq_lines, key=lambda line: line["old"])
        last_old, last_new = 0, 0
        i = 0
        cmp_lines = []
        for eq in eq_lines:
            now_old, now_new = eq["old"], eq["new"]
            while last_old < now_old - 1 and last_new < now_new - 1:
                cmp_lines.append(
                    CodeSyntaxLineCmp(
                        order=i,
                        old_line_number=last_old + 1,
                        old_line=old_lines[last_old],
                        new_line_number=last_new + 1,
                        new_line=new_lines[last_new],
                        is_same=False,
                    ))
                last_new += 1
                last_old += 1
                i += 1

            while last_old < now_old - 1:
                # 如果没有对应的语法节点链,则认为在语法成分上相等(主要为忽略{})
                is_same = len(old_nodes_lines[last_old]) == 0
                cmp_lines.append(
                    CodeSyntaxLineCmp(
                        order=i,
                        old_line_number=last_old + 1,
                        old_line=old_lines[last_old],
                        is_same=is_same,
                    ))
                last_old += 1
                i += 1

            while last_new < now_new - 1:
                is_same = len(new_nodes_lines[last_new]) == 0
                cmp_lines.append(
                    CodeSyntaxLineCmp(
                        order=i,
                        new_line_number=last_new + 1,
                        new_line=new_lines[last_new],
                        is_same=is_same,
                    ))
                last_new += 1
                i += 1

            cmp_lines.append(
                CodeSyntaxLineCmp(
                    order=i,
                    old_line_number=last_old + 1,
                    old_line=old_lines[last_old],
                    new_line_number=last_new + 1,
                    new_line=new_lines[last_new],
                    is_same=True,
                ))
            last_old += 1
            last_new += 1
            i += 1

        while last_old < len(old_lines):
            is_same = len(old_nodes_lines[last_old]) == 0
            cmp_lines.append(
                CodeSyntaxLineCmp(
                    order=i,
                    old_line_number=last_old + 1,
                    old_line=old_lines[last_old],
                    is_same=is_same,
                ))
            last_old += 1
            i += 1

        while last_new < len(new_lines):
            is_same = len(new_nodes_lines[last_new]) == 0
            cmp_lines.append(
                CodeSyntaxLineCmp(
                    order=i,
                    new_line_number=last_new + 1,
                    new_line=new_lines[last_new],
                    is_same=is_same,
                ))
            last_new += 1
            i += 1
        return cmp_lines
示例#31
0
#!/usr/bin/env python

import sys
import clang.cindex
import os
from clang.cindex import Config
from clang.cindex import Cursor
from clang.cindex import CursorKind
import re

Config.set_library_file("/usr/lib/llvm-6.0/lib/libclang-6.0.so.1")
index = clang.cindex.Index.create()

top_function_name = ""
top_function_node = None
line_filter = []
bypass_line = []
logfile = None
static_arrays = []


def get_diag_info(diag):
    return {
        'severity': diag.severity,
        'location': diag.location,
        'spelling': diag.spelling,
        'ranges': diag.ranges,
        'fixits': diag.fixits
    }

示例#32
0
            g = ObjectMetadataGenerator(obj)
            generators.append(g)

            all_attrs += [a.name for a in attrs]

        self.data = {
            'impls': [g.implementation() for g in generators],
            'headers':
            [x for x in [g.header() for g in generators] if len(x) > 0],
            'object_names': [o.name for o in h.objects],
            'attrs': sorted(all_attrs)
        }


if __name__ == '__main__':
    parser = OptionParser()
    parser.add_option('--clang-lib',
                      default='/usr/lib/llvm-6.0/lib/libclang.so.1')
    (options, args) = parser.parse_args()

    Config.set_library_file(options.clang_lib)

    h = TAIHeader(args[0])

    g = TAIMetadataGenerator(h)
    with open('taimetadata.h', 'w') as f:
        f.write(g.header())

    with open('taimetadata.c', 'w') as f:
        f.write(g.implementation())
示例#33
0
import sys
import clang.cindex
from clang.cindex import Config
from clang.cindex import Cursor
from clang.cindex import CursorKind
import os
import math

Config.set_library_file("/usr/local/Cellar/llvm/8.0.0_1/lib/libclang.dylib")


def get_lf(dic_path):
    def get_leaves_inside(cur, ld={}):
        if any(True for _ in cur.get_children()) == False:
            # print "ffff"
            if cur.spelling.strip():
                leave = cur.spelling
                if leave not in ld:
                    ld[leave] = 1
                # else:
                #     ld[leave] += 1
        else:
            # print "t"
            for c in cur.get_children():
                get_leaves_inside(c, ld)

    lod = {}
    for r, d, f in os.walk(dic_path):
        for file in f:
            if str(file) != '.DS_Store':
                dic_tem = {}
示例#34
0
文件: config.py 项目: aqrln/fcd
def init_clang():
    if not Config.loaded:
        Config.set_library_file(get_libclang_path())
示例#35
0
library = cdll.LoadLibrary("C:\\Program Files\\LLVM\\bin\\libclang.dll")

#shell_result = subprocess.run(["llvm-config", "--src-root"], capture_output=True)
#sys.path.insert(0, shell_result.stdout.decode("utf-8")[:-1] + "/bindings/python")
#sys.path.insert(0, shell_result.stdout.decode("utf-8")[:-1] + "/tools/clang/bindings/python")
sys.path.insert(0, "C:\\Program Files\\LLVM\\llvm-8.0.1.src\\bindings\\python")
sys.path.insert(
    0,
    "C:\\Program Files\\LLVM\\llvm-8.0.1.src\\tools\\clang\\bindings\\python")
#sys.path.insert(0, "/cygdrive/c/Program Files/LLVM/llvm-8.0.1.src/bindings/python")
#sys.path.insert(0, "")
import llvm
import clang.cindex
from clang.cindex import Config
#Config.set_library_path("C:\\Program Files\\LLVM\\bin")
Config.set_library_file("C:\\Program Files\\LLVM\\bin\\libclang.dll")


def SigHandler_SIGINT(signum, frame):
    print()
    sys.exit(0)


class Argparser(object):
    def __init__(self):
        parser = argparse.ArgumentParser()
        parser.add_argument("--file", type=str, help="string")
        parser.add_argument("--symbol", type=str, help="string")
        parser.add_argument("--bool",
                            action="store_true",
                            help="bool",
示例#36
0
A simple command line tool for dumping a Graphviz description (dot) that
describes include dependencies. Heavily inspired by cindex-includes.py
disitributed with the clang source code.
"""
import ctypes.util
import logging
import sys
import os

from clang.cindex import Index, Config


for libname in ['clang', 'clang-4.0', 'clang-3.9', 'clang-3.8', 'clang-3.7']:
    filename = ctypes.util.find_library(libname)
    if filename:
        Config.set_library_file(filename)
        break


logger = logging.getLogger('incdeps')


def emit_node(out, uid, label):
    out.write('  "%s" [label="%s"];\n' % (uid, label))


def emit_cluster(out, children, cluster_path='', parent_path=''):
    prefix = '  ' * (cluster_path.count(os.path.sep) - 1)
    
    nodes = list()
    clusters = dict()
示例#37
0
import sys, os
import ctypes
import clang.cindex
from clang.cindex import Index, Config, CursorKind, TypeKind, TranslationUnit
Config.set_library_path('/usr/lib/llvm-6.0/lib/')
Config.set_library_file('/usr/lib/llvm-6.0/lib/libclang.so.1')
REAL_NUMBER_TYPES = set({TypeKind.DOUBLE, TypeKind.FLOAT, TypeKind.FLOAT128})
INTEGER_TYPES = set({
    TypeKind.INT, TypeKind.INT128, TypeKind.LONG, TypeKind.LONGDOUBLE,
    TypeKind.LONGLONG, TypeKind.UCHAR, TypeKind.CHAR32
})
NUMERIC_TYPES = REAL_NUMBER_TYPES | INTEGER_TYPES

BUILTIN_C_TYPES = {
    TypeKind.BOOL: ctypes.c_bool,
    TypeKind.CHAR_S: ctypes.c_char,
    TypeKind.CHAR_U: ctypes.c_char,
    TypeKind.DOUBLE: ctypes.c_double,
    TypeKind.FLOAT: ctypes.c_float,
    TypeKind.INT: ctypes.c_int,
    TypeKind.LONG: ctypes.c_long,
    TypeKind.LONGDOUBLE: ctypes.c_longdouble,
    TypeKind.LONGLONG: ctypes.c_longlong,
    TypeKind.SCHAR: ctypes.c_char,
    TypeKind.SHORT: ctypes.c_short,
    TypeKind.UCHAR: ctypes.c_char,
    TypeKind.UINT: ctypes.c_uint,
    TypeKind.ULONG: ctypes.c_ulong,
    TypeKind.ULONGLONG: ctypes.c_ulonglong,
    TypeKind.USHORT: ctypes.c_ushort,
    TypeKind.WCHAR: ctypes.c_wchar
示例#38
0
文件: main.py 项目: Daiver/jff
#!/usr/bin/env python
""" Usage: call with <filename> <typename>
"""

import sys
import clang.cindex

def find_typerefs(node, typename):
    """ Find all references to the type named 'typename'
    """
    if node.kind.is_reference():
        ref_node = clang.cindex.Cursor(node)
        if ref_node.spelling == typename:
            print 'Found %s [line=%s, col=%s]' % (
                typename, node.location.line, node.location.column)
    # Recurse for children of this node
    for c in node.get_children():
        find_typerefs(c, typename)

from ctypes.util import find_library
from clang.cindex import Config
Config.set_library_file(find_library('clang'))

index = clang.cindex.Index.create()
tu = index.parse(sys.argv[1])
print 'Translation unit:', tu.spelling
find_typerefs(tu.cursor, sys.argv[2])