How to use the pycparser.parse_file 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 oridb / mc / support / syscall-gen / c2myr.py View on Github external
if os.path.exists("/usr/include/sys"):
        syshdr = ["sys/" + h for h in os.listdir('/usr/include/sys')]
    if os.path.exists("/usr/include/linux"):
        syshdr = syshdr + ["linux/" + h for h in os.listdir("/usr/include/linux")]
    # it seems that sys headers can also be stashed here. Shit.
    if os.path.exists("/usr/include/x86_64-linux-gnu/sys"):
        syshdr = syshdr + ["linux/" + h for h in os.listdir("/usr/include/linux")]
    for hdr in syshdr:
        print 'trying {}'.format(hdr)
        if not hdr.endswith(".h"):
            continue
        try:
            include = prehdr + '\n#include <{}>'.format(hdr)
            with open('/tmp/myr-includes.h', 'w') as f:
                f.write(include)
            pycparser.parse_file('/tmp/myr-includes.h', use_cpp=True)
            includes.append('#include <{}>'.format(hdr))
        except Exception:
            print '...skip'

    print('importing' + ' '.join(includes))
    with open('/tmp/myr-includes.h', 'w') as f:
        f.write(prehdr + '\n' + '\n'.join(includes))
    with open('want.txt') as f:
        want = f.read().split()
    with open('have.txt') as f:
        have |= set(f.read().split())
        for sz in ['', 8, 16, 32, 64]:
            have.add('int{}'.format(sz))
            have.add('uint{}'.format(sz))
    ast = pycparser.parse_file('/tmp/myr-includes.h', use_cpp=True)
    collect(ast)
github jerryscript-project / jerryscript / targets / mbedos5 / tools / generate_pins.py View on Github external
def enumerate_pins(c_source_file, include_dirs, definitions):
    """
    Enumerate pins specified in PinNames.h, by looking for a PinName enum
    typedef somewhere in the file.
    """
    definitions += ['__attribute(x)__=', '__extension__(x)=', 'register=', '__IO=', 'uint32_t=unsigned int']

    gcc_args = ['-E', '-fmerge-all-constants']
    gcc_args += ['-I' + directory for directory in include_dirs]

    gcc_args += ['-D' + definition for definition in definitions]
    parsed_ast = parse_file(c_source_file,
                            use_cpp=True,
                            cpp_path='arm-none-eabi-gcc',
                            cpp_args=gcc_args,
                            parser=GnuCParser())

    # now, walk the AST
    visitor = TypeDeclVisitor(['PinName'])
    return visitor.visit(parsed_ast)
github networkupstools / nut / scripts / DMF / jsonify-mib.py View on Github external
p = s_mkparser ()
args = p.parse_args (sys.argv[1:])
drivers_dir = os.path.dirname (os.path.abspath (args.source))
include_dir = os.path.abspath (os.path.join (drivers_dir, "../include"))
info ("CALL parse_file():")

try:
    gcc_cppflags = os.environ["CPPFLAGS"].split()
except KeyError:
    gcc_cppflags = []

try:
    ### NOTE: If 'nut-cpp' fails here and returns exit code != 0 alone,
    ### there is no exception; so to abort pycparser we also print some
    ### invalid C pragma so the parser does die early.
    ast = parse_file (
        args.source,
        use_cpp=True,
        cpp_path=s_cpp_path (),
        cpp_args=["-I"+drivers_dir, "-I"+include_dir] + gcc_cppflags
        )
    if not isinstance(ast, c_ast.FileAST):
        raise RuntimeError("Got a not c_ast.FileAST instance after parsing")
    c = 0
    for idx, node in ast.children ():
        c = c+1
    if c == 0 :
        raise RuntimeError ("Got no data in resulting tree")
except Exception as e:
    warn ("FAILED to parse %s: %s" % (args.source, e))
    sys.exit(1)
github blexim / synth / src / frontends / pycparser / utils / internal / zz_parse.py View on Github external
import sys
sys.path.insert(0, '../..')

from pycparser import c_parser, c_ast, parse_file


if __name__ == "__main__":
    ast = parse_file('zc_pp.c', use_cpp=True, cpp_path="../cpp.exe")
github Nuand / bladeRF / host / libraries / libbladeRF_bindings / python / scripts / import_header.py View on Github external
def parse_header(filename):
    return parse_file(filename,
                      use_cpp=True,
                      cpp_args=[
                        r'-I{}'.format(os.path.dirname(filename)),
                        r'-I{}'.format(FAKE_LIBC_INCLUDE_DIR),
                        r'-D_DOXYGEN_ONLY_'])
github nsec / nsec-badge / nrf52 / utils / gen_image.py View on Github external
def decode_image(input_file_path, output_file_path, width, rotate=False):
    tree = pycparser.parse_file(input_file_path, use_cpp=True, cpp_path="arm-none-eabi-cpp")
    if len(tree.ext) != 1:
        raise Exception("C file has more than one element.")
    font = tree.ext[0]
    if "char" not in font.type.type.type.names:
        raise Exception("Array must be of type char.")
    buf = b""
    for con in font.init.exprs:
        buf += chr(int(con.value, 0))
    height = (len(buf) * 8) / width
    image = Image.frombytes("1", (width, height), buf)
    if rotate:
        image = image.transpose(Image.ROTATE_90)
    image.save(output_file_path)
github eliben / pycparser / examples / dump_ast.py View on Github external
import sys

# This is not required if you've installed pycparser into
# your site-packages/ with setup.py
sys.path.extend(['.', '..'])

from pycparser import c_parser, c_ast, parse_file

if __name__ == "__main__":
    argparser = argparse.ArgumentParser('Dump AST')
    argparser.add_argument('filename', help='name of file to parse')
    argparser.add_argument('--coord', help='show coordinates in the dump',
                           action='store_true')
    args = argparser.parse_args()

    ast = parse_file(args.filename, use_cpp=False)
    ast.show(showcoord=args.coord)
github LefterisJP / refuclib / build_script / ctemplate_parser.py View on Github external
r'-D__thread= ',
            r'-D__builtin_va_list=int',
            r'-D__asm__(x)= ',
            r'-D__inline= ',
            r'-D__extension__= ',
        ]

        if incl_dirs is not None:
            for incl in incl_dirs:
                cpp_args.append(r'-I{}'.format(incl))

        if extra_dirs is not None:
            for incl in extra_dirs:
                cpp_args.append(r'-I{}'.format(incl))

        self.ast = parse_file(filename, use_cpp=True,
                              cpp_args=cpp_args)