Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
# Good luck!
from pycparser import CParser
from pycparser.c_ast import NodeVisitor, Constant
import re
import sys
DIRECTIVE_RE = re.compile("^#(.+)$", re.MULTILINE)
class DictWrapper(object):
def __init__(self, dict):
self.dict = dict
def __getattr__(self, key):
return self.dict[key]
class OptionParser(NodeVisitor):
def __init__(self):
self.commands = []
def visit_ExprList(self, node):
bits = [n[1] for n in node.children()]
if isinstance(bits[0], Constant) and bits[0].type == "string":
self.add_option(node, bits)
self.generic_visit(node)
def parse_file(self, filename):
parser = CParser()
buf = file(filename).read()
buf = DIRECTIVE_RE.sub("", buf)#r"/* directive \1 elided */", buf)
t = parser.parse(buf, filename)
self.visit(t)
'int64': 'int64_t',
}
print(f'typedef {ctype_names[info["getCType"]]} {mangle_name(name)};')
elif name == 'Builtin.NativeObject':
print(f'typedef void *{mangle_name(name)};')
else:
print(f'typedef char {mangle_name(name)}[{info["size"]}];')
elif info['kind'] == 'Function':
print(f"typedef void *func_{str(hash(name))[1:]};") # TODO: proper names
else:
print(f'typedef char {mangle_name(name)}[{info["size"]}];')
if ctype:
type_decl = TypeDecl(mangle_name(name), None, ctype)
ctypes[name] = type_decl
type_decl_forward = Struct(mangle_name(name) + "_s", [])
if isinstance(type_decl, PtrDecl):
ptr_types.add(name)
type_decl_forward = PtrDecl(None, type_decl_forward)
print(generator.visit(Typedef(mangle_name(name), None, ['typedef'], type_decl_forward)) + ";")
for name in ptr_types:
req_graph.pop(name, None)
for name in top_sort(req_graph):
if name in ctypes:
print(f"\n// {name}")
print(generator.visit(Typedef(mangle_name(name), None, ['typedef'], ctypes[name])) + ";")
def test_scalar_children(self):
b1 = c_ast.BinaryOp(
op='+',
left=c_ast.Constant(type='int', value='6'),
right=c_ast.ID(name='joe'))
cv = self.ConstantVisitor()
cv.visit(b1)
self.assertEqual(cv.values, ['6'])
b2 = c_ast.BinaryOp(
op='*',
left=c_ast.Constant(type='int', value='111'),
right=b1)
b3 = c_ast.BinaryOp(
op='^',
left=b2,
right=b1)
def _run_c_to_c(self, src):
ast = parse_to_ast(src)
generator = c_generator.CGenerator()
return generator.visit(ast)
def fnames_found():
return [
fname for fname in fnames_to_track
if os.path.isfile(fname)
]
if __name__ == '__main__':
# Confirm no files exist before we start.
if fnames_found():
raise SystemExit('FAIL: Files present before test.')
# Minimal invocation that generates the files.
from pycparser import c_parser
parser = c_parser.CParser()
# Were the files generated?
fnames_generated = fnames_found()
# Try to remove them, if so.
for fname in fnames_generated:
try:
os.unlink(fname)
except OSError:
pass
# Did we fail at deleting any file?
fnames_left = fnames_found()
# Fail if any file was generated.
if fnames_generated:
def test_scalar_children(self):
b1 = c_ast.BinaryOp(
op='+',
left=c_ast.Constant(type='int', value='6'),
right=c_ast.ID(name='joe'))
cv = self.ConstantVisitor()
cv.visit(b1)
self.assertEqual(cv.values, ['6'])
b2 = c_ast.BinaryOp(
op='*',
left=c_ast.Constant(type='int', value='111'),
right=b1)
b3 = c_ast.BinaryOp(
op='^',
left=b2,
right=b1)
cv = self.ConstantVisitor()
cv.visit(b3)
self.assertEqual(cv.values, ['111', '6', '6'])
b1 = c_ast.BinaryOp(
op='+',
left=c_ast.Constant(type='int', value='6'),
right=c_ast.ID(name='joe'))
cv = self.ConstantVisitor()
cv.visit(b1)
self.assertEqual(cv.values, ['6'])
b2 = c_ast.BinaryOp(
op='*',
left=c_ast.Constant(type='int', value='111'),
right=b1)
b3 = c_ast.BinaryOp(
op='^',
left=b2,
right=b1)
cv = self.ConstantVisitor()
cv.visit(b3)
self.assertEqual(cv.values, ['111', '6', '6'])
import os
import platform
import sys
import unittest
# Run from the root dir
sys.path.insert(0, '.')
from pycparser import c_parser, c_generator, c_ast, parse_file
_c_parser = c_parser.CParser(
lex_optimize=False,
yacc_debug=True,
yacc_optimize=False,
yacctab='yacctab')
def compare_asts(ast1, ast2):
if type(ast1) != type(ast2):
return False
if isinstance(ast1, tuple) and isinstance(ast2, tuple):
if ast1[0] != ast2[0]:
return False
ast1 = ast1[1]
ast2 = ast2[1]
return compare_asts(ast1, ast2)
for attr in ast1.attr_names: