pycparser

3.0 · active · verified Fri Mar 27

pycparser is a complete, standards-compliant C99 parser written in pure Python, producing an Abstract Syntax Tree (AST) that can be traversed, modified, and re-emitted as C code. Current version is 3.0, released January 2026, which replaced the bundled PLY (Lex/Yacc) backend with a hand-written lexer and recursive-descent parser—eliminating all external dependencies and improving parse speed by ~30%. Release cadence is irregular; major versions are rare (2.x spanned 2012–2025).

Warnings

Install

Imports

Quickstart

Parse a tiny C snippet directly with CParser (no preprocessor needed for self-contained code), then walk the AST with a visitor.

from pycparser import c_parser, c_ast, c_generator

# Direct in-memory parse — only works for preprocessor-free, self-contained C
parser = c_parser.CParser()

src = r"""
int add(int a, int b) {
    return a + b;
}
"""

ast = parser.parse(src, filename='<none>')
ast.show(attrnames=True, nodenames=True)

# Regenerate C source from AST
gen = c_generator.CGenerator()
print(gen.visit(ast))

# Visitor pattern: collect all function names
class FuncDefVisitor(c_ast.NodeVisitor):
    def visit_FuncDef(self, node):
        print('Function:', node.decl.name)

v = FuncDefVisitor()
v.visit(ast)

view raw JSON →