How to use the pycparser.c_generator.CGenerator function in pycparser

To help you get started, we’ve selected a few pycparser examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github eliben / pycparser / tests / test_c_generator.py View on Github external
def _run_c_to_c(self, src):
        ast = parse_to_ast(src)
        generator = c_generator.CGenerator()
        return generator.visit(ast)
github revng / llvmcpy / llvmcpy / llvm.py View on Github external
value += 1

                self.enums[self._name] = mapping

                # Clear the scope
                self._name = None

    with open(all_c_preprocessed) as f:
        ast, _, _ = cffi.cparser.Parser()._parse(f.read())

    visitor = EnumVisitor()
    visitor.visit(ast)

    with open(all_c_preprocessed, "w") as f:
        generator = pycparser.c_generator.CGenerator()
        f.write(generator.visit(ast).replace("__dotdotdot__", "foo"))

    return visitor.enums
github eliben / pycparser / examples / c-to-c.py View on Github external
def translate_to_c(filename):
    """ Simply use the c_generator module to emit a parsed AST.
    """
    ast = parse_file(filename, use_cpp=True)
    generator = c_generator.CGenerator()
    print(generator.visit(ast))
github libtcod / python-tcod / build_libtcod.py View on Github external
def get_cdef():
    generator = c_generator.CGenerator()
    return generator.visit(get_ast())
github pathmann / pyTSon / tools / generator / pytson / wrappers.py View on Github external
from pycparser import c_generator, c_ast

cgen = c_generator.CGenerator()

FILESTORAGE = {}


def closeFiles():
    global FILESTORAGE
    FILESTORAGE = {}


class FunctionWrapper(object):
    """

    """
    def __init__(self, ts3decl=None, pytsondecl=None):
        """
github littlevgl / lv_binding_micropython / gen / gen_mpy.py View on Github external
return result

#
# Initialization, data structures, helper functions
#

# We consider union as a struct, for simplicity
def is_struct(type):
    return isinstance(type, c_ast.Struct) or isinstance(type, c_ast.Union)

obj_metadata = {}
func_metadata = {}
callback_metadata = {}

parser = c_parser.CParser()
gen = c_generator.CGenerator()
ast = parser.parse(s, filename='')
func_defs = [x.decl for x in ast.ext if isinstance(x, c_ast.FuncDef)]
func_decls = [x for x in ast.ext if isinstance(x, c_ast.Decl) and isinstance(x.type, c_ast.FuncDecl)]
funcs = func_defs + func_decls
# eprint('... %s' % ',\n'.join(sorted('%s' % func.name for func in funcs)))
obj_ctors = [func for func in funcs if is_obj_ctor(func)]
for obj_ctor in obj_ctors:
    funcs.remove(obj_ctor)
obj_names = [re.match(create_obj_pattern, ctor.name).group(1) for ctor in obj_ctors]
typedefs = [x.type for x in ast.ext if isinstance(x, c_ast.Typedef)] # and not (hasattr(x.type, 'declname') and lv_base_obj_pattern.match(x.type.declname))]
# print('... %s' % str(typedefs))
struct_typedefs = [typedef for typedef in typedefs if is_struct(typedef.type)]
structs = collections.OrderedDict((typedef.declname, typedef.type) for typedef in struct_typedefs if typedef.declname and typedef.type.decls) # and not lv_base_obj_pattern.match(typedef.declname)) 
structs_without_typedef = collections.OrderedDict((decl.type.name, decl.type) for decl in ast.ext if hasattr(decl, 'type') and is_struct(decl.type))
structs.update(structs_without_typedef) # This is for struct without typedef
explicit_structs = collections.OrderedDict((typedef.type.name, typedef.declname) for typedef in struct_typedefs if typedef.type.name) # and not lv_base_obj_pattern.match(typedef.type.name))
github simonlindholm / decomp-permuter / src / ast_util.py View on Github external
# Ignore permuter pragmas, but leave actual pragmas in (like intrinsics)
            if stripped.startswith("#pragma _permuter"):
                continue
        if in_late_defines:
            continue
        if not same_line:
            line += "\n"
        elif out and not out[-1].endswith("\n"):
            line = " " + line.lstrip()
        out.append(line)
    assert same_line == 0
    return "".join(out).rstrip() + "\n"


class PatchedCGenerator(c_generator.CGenerator):
    """Like a CGenerator, except it keeps else if's prettier despite
    the terrible things we've done to them in normalize_ast."""

    def visit_If(self, n: ca.If) -> str:
        n2 = n
        if (
            n.iffalse
            and isinstance(n.iffalse, ca.Compound)
            and n.iffalse.block_items
            and len(n.iffalse.block_items) == 1
            and isinstance(n.iffalse.block_items[0], ca.If)
        ):
            n2 = ca.If(cond=n.cond, iftrue=n.iftrue, iffalse=n.iffalse.block_items[0])
        return super().visit_If(n2)  # type: ignore
github blexim / synth / src / frontend / frontend.py View on Github external
def split_func(fd, ofile):
  prog = FlatProgram()

  flatten(fd.body, prog)
  cgen = c_generator.CGenerator()
  (id_map, rev_id_map) = number_ids(fd)

  ofile.write('#include "synth.h"\n')
  ofile.write("/*\n")

  for id in sorted(rev_id_map.keys()):
    ofile.write(" * %s -> %d\n" % (rev_id_map[id], id))

  ofile.write("*/\n\n");

  nids = len(id_map)

  prefix = copy.deepcopy(prog.blocks[0])
  loop = copy.deepcopy(prog.blocks[1])

  decls = []