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


Python c_parser.CParser方法代码示例

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


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

示例1: explain_c_declaration

# 需要导入模块: from pycparser import c_parser [as 别名]
# 或者: from pycparser.c_parser import CParser [as 别名]
def explain_c_declaration(c_decl):
    """ Parses the declaration in c_decl and returns a text
        explanation as a string.

        The last external node of the string is used, to allow
        earlier typedefs for used types.
    """
    parser = c_parser.CParser()

    try:
        node = parser.parse(c_decl, filename='<stdin>')
    except c_parser.ParseError:
        e = sys.exc_info()[1]
        return "Parse error:" + str(e)

    if (not isinstance(node, c_ast.FileAST) or
        not isinstance(node.ext[-1], c_ast.Decl)
        ):
        return "Not a valid declaration"

    return _explain_decl_node(node.ext[-1]) 
开发者ID:johncsnyder,项目名称:SwiftKitten,代码行数:23,代码来源:cdecl.py

示例2: parse_source

# 需要导入模块: from pycparser import c_parser [as 别名]
# 或者: from pycparser.c_parser import CParser [as 别名]
def parse_source(self, output_file, option):
        path = self.root+output_file
        if os.path.exists(path) and option is 'existing':
            source = pd.read_pickle(path)
        else:
            from pycparser import c_parser
            parser = c_parser.CParser()
            source = pd.read_pickle(self.root+'programs.pkl')

            source.columns = ['id', 'code', 'label']
            source['code'] = source['code'].apply(parser.parse)

            source.to_pickle(path)
        self.sources = source
        return source

    # split data for training, developing and testing 
开发者ID:zhangj111,项目名称:astnn,代码行数:19,代码来源:pipeline.py

示例3: parse_access

# 需要导入模块: from pycparser import c_parser [as 别名]
# 或者: from pycparser.c_parser import CParser [as 别名]
def parse_access(c_access):
    """Parse C access

    @c_access: C access string
    """

    main = '''
    int main() {
    %s;
    }
    ''' % c_access

    parser = c_parser.CParser()
    node = parser.parse(main, filename='<stdin>')
    access = node.ext[-1].body.block_items[0]
    return access 
开发者ID:cea-sec,项目名称:miasm,代码行数:18,代码来源:objc.py

示例4: parse_c

# 需要导入模块: from pycparser import c_parser [as 别名]
# 或者: from pycparser.c_parser import CParser [as 别名]
def parse_c(source: str) -> ca.FileAST:
    try:
        return CParser().parse(source, "<source>")
    except ParseError as e:
        msg = str(e)
        position, msg = msg.split(": ", 1)
        parts = position.split(":")
        if len(parts) >= 2:
            # Adjust the line number by 1 to correct for the added typedefs
            lineno = int(parts[1]) - 1
            posstr = f" at line {lineno}"
            if len(parts) >= 3:
                posstr += f", column {parts[2]}"
            try:
                line = source.split("\n")[lineno].rstrip()
                posstr += "\n\n" + line
            except IndexError:
                posstr += "(out of bounds?)"
        else:
            posstr = ""
        raise DecompFailure(f"Syntax error when parsing C context.\n{msg}{posstr}") 
开发者ID:matt-kempster,项目名称:mips_to_c,代码行数:23,代码来源:c_types.py

示例5: compile

# 需要导入模块: from pycparser import c_parser [as 别名]
# 或者: from pycparser.c_parser import CParser [as 别名]
def compile(code):
	parser = CParser()

	stypes = 'u8 i8 u16 i16 u32 i32 u64 i64 f32 f64 f128'
	code = 'void runner() { ' + code + ' ; }'
	for type in stypes.split(' '):
		code = 'typedef void %s; %s' % (type, code)

	ast = parser.parse(code)
	found = None
	for _, child in ast.children():
		if isinstance(child, FuncDef):
			found = child
			break

	assert found is not None
	assert len(found.body.children()) == 1

	ast = found.body.children()[0][1]
	sexp = AstTranslator().process(ast)

	def run(ctu):
		return bare(SexpRunner(ctu).run(sexp))
	return run 
开发者ID:reswitched,项目名称:CageTheUnicorn,代码行数:26,代码来源:ceval.py

示例6: parseStructSource

# 需要导入模块: from pycparser import c_parser [as 别名]
# 或者: from pycparser.c_parser import CParser [as 别名]
def parseStructSource(self, src):
        src = preProcessSource( src )
        parser = c_parser.CParser()
        ast = parser.parse(src)
        #ast.show()

        for child in ast.children():
            xname, decl =  self._getVsElement( child )
            yield decl 
开发者ID:joxeankoret,项目名称:nightmare,代码行数:11,代码来源:cparse.py

示例7: _zz_test_translate

# 需要导入模块: from pycparser import c_parser [as 别名]
# 或者: from pycparser.c_parser import CParser [as 别名]
def _zz_test_translate():
    # internal use
    src = r'''

    void f(char * restrict joe){}

int main(void)
{
    unsigned int long k = 4;
    int p = - - k;
    return 0;
}
'''
    parser = c_parser.CParser()
    ast = parser.parse(src)
    ast.show()
    generator = c_generator.CGenerator()

    print(generator.visit(ast))

    # tracing the generator for debugging
    #~ import trace
    #~ tr = trace.Trace(countcallers=1)
    #~ tr.runfunc(generator.visit, ast)
    #~ tr.results().write_results()


#------------------------------------------------------------------------------ 
开发者ID:johncsnyder,项目名称:SwiftKitten,代码行数:30,代码来源:c-to-c.py

示例8: parse_source

# 需要导入模块: from pycparser import c_parser [as 别名]
# 或者: from pycparser.c_parser import CParser [as 别名]
def parse_source(self, output_file, option):
        path = self.root+self.language+'/'+output_file
        if os.path.exists(path) and option == 'existing':
            source = pd.read_pickle(path)
        else:
            if self.language is 'c':
                from pycparser import c_parser
                parser = c_parser.CParser()
                source = pd.read_pickle(self.root+self.language+'/programs.pkl')
                source.columns = ['id', 'code', 'label']
                source['code'] = source['code'].apply(parser.parse)
                source.to_pickle(path)
            else:
                import javalang
                def parse_program(func):
                    tokens = javalang.tokenizer.tokenize(func)
                    parser = javalang.parser.Parser(tokens)
                    tree = parser.parse_member_declaration()
                    return tree
                source = pd.read_csv(self.root+self.language+'/bcb_funcs_all.tsv', sep='\t', header=None, encoding='utf-8')
                source.columns = ['id', 'code']
                source['code'] = source['code'].apply(parse_program)
                source.to_pickle(path)
        self.sources = source
        return source

    # create clone pairs 
开发者ID:zhangj111,项目名称:astnn,代码行数:29,代码来源:pipeline.py

示例9: __init__

# 需要导入模块: from pycparser import c_parser [as 别名]
# 或者: from pycparser.c_parser import CParser [as 别名]
def __init__(self, *args, **kwargs):
        super(CParser, self).__init__(*args, **kwargs)

        self.postincdec = 0
        
        self.inswitch = False

        self.fncdef = False 
开发者ID:iradicek,项目名称:clara,代码行数:10,代码来源:c_parser.py

示例10: parse

# 需要导入模块: from pycparser import c_parser [as 别名]
# 或者: from pycparser.c_parser import CParser [as 别名]
def parse(self, code):
        '''
        Parses C code
        '''

        # Meta data
        if re.findall(r'^\s*//\s+#incorrect\s*', code, flags=re.M):
            self.prog.addmeta('incorrect', True)
        mfeed = re.findall(r'^\s*//\s+#feedback\s+(.*)', code, flags=re.M)
        if mfeed:
            self.prog.addmeta('feedback', mfeed[0])

        # Remove includes
        code = re.sub(r'\s*#include.*', ' ', code)

        # Run CPP
        args = ['cpp', '-x', 'c', '-']
        pipe = Popen(args, stdout=PIPE, stderr=PIPE, stdin=PIPE,
                     universal_newlines=True)
        code, err = pipe.communicate(code)

        # Get AST
        parser = c_parser.CParser()
        try:
            self.ast = parser.parse(code)
        except plyparser.ParseError as e:
            raise ParseError(str(e))
    
        self.visit(self.ast) 
开发者ID:iradicek,项目名称:clara,代码行数:31,代码来源:c_parser.py

示例11: parse

# 需要导入模块: from pycparser import c_parser [as 别名]
# 或者: from pycparser.c_parser import CParser [as 别名]
def parse(code, extra_cpp_args=[], whitelist=None):
    preprocessed = preprocess(code, extra_cpp_args=extra_cpp_args)
    parser = c_parser.CParser()
    ast = parser.parse(preprocessed)
    decls = []
    for decl in ast.ext:
        if hasattr(decl, 'name') and decl.name not in IGNORE_DECLARATIONS:
            if not whitelist or decl.coord.file in whitelist:
                decls.append(decl)
    ast.ext = decls
    return ast 
开发者ID:tarruda,项目名称:python-autopxd,代码行数:13,代码来源:__init__.py

示例12: __init__

# 需要导入模块: from pycparser import c_parser [as 别名]
# 或者: from pycparser.c_parser import CParser [as 别名]
def __init__(self, knowntypes=None, knowntypedefs=None):
        if knowntypes is None:
            knowntypes = {}
        if knowntypedefs is None:
            knowntypedefs = {}

        self._types = dict(knowntypes)
        self._typedefs = dict(knowntypedefs)
        self.cpt = 0
        self.loc_to_decl_info = {}
        self.parser = c_parser.CParser()
        self._cpt_decl = 0


        self.ast_to_typeid_rules = {
            c_ast.Struct: self.ast_to_typeid_struct,
            c_ast.Union: self.ast_to_typeid_union,
            c_ast.IdentifierType: self.ast_to_typeid_identifiertype,
            c_ast.TypeDecl: self.ast_to_typeid_typedecl,
            c_ast.Decl: self.ast_to_typeid_decl,
            c_ast.Typename: self.ast_to_typeid_typename,
            c_ast.FuncDecl: self.ast_to_typeid_funcdecl,
            c_ast.Enum: self.ast_to_typeid_enum,
            c_ast.PtrDecl: self.ast_to_typeid_ptrdecl,
            c_ast.EllipsisParam: self.ast_to_typeid_ellipsisparam,
            c_ast.ArrayDecl: self.ast_to_typeid_arraydecl,
        }

        self.ast_parse_rules = {
            c_ast.Struct: self.ast_parse_struct,
            c_ast.Union: self.ast_parse_union,
            c_ast.Typedef: self.ast_parse_typedef,
            c_ast.TypeDecl: self.ast_parse_typedecl,
            c_ast.IdentifierType: self.ast_parse_identifiertype,
            c_ast.Decl: self.ast_parse_decl,
            c_ast.PtrDecl: self.ast_parse_ptrdecl,
            c_ast.Enum: self.ast_parse_enum,
            c_ast.ArrayDecl: self.ast_parse_arraydecl,
            c_ast.FuncDecl: self.ast_parse_funcdecl,
            c_ast.FuncDef: self.ast_parse_funcdef,
            c_ast.Pragma: self.ast_parse_pragma,
        } 
开发者ID:cea-sec,项目名称:miasm,代码行数:44,代码来源:ctypesmngr.py


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