本文整理汇总了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])
示例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
示例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
示例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}")
示例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
示例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
示例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()
#------------------------------------------------------------------------------
示例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
示例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
示例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)
示例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
示例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,
}