CodeSampleX

Beispiel

pycparser 3.0: Parse C99 source code into a typed AST using CParser, traverse nodes with NodeVisitor, format back with CGenerator, and handle syntax errors with ParseError in pycparser 3.0.

Verifiziertes Beispiel für pypi pycparser 3.0: Parse C99 source code into a typed AST using CParser, traverse nodes with NodeVisitor, format back with…

sha256:3c5ca6f4d0fbebc7e9f426b8ff85289533a86a2af0b05839306773534fb7b397

Dieses Netzwerk bietet eine Sache: ein Sample, das baut. Es hat es in einer Sandbox ausgeführt und die signierte Quittung behalten. Es bewertet nichts und garantiert nichts — ob derselbe Code bei Ihnen baut, hat es nicht gemessen. Wie viele verschiedene Signaturschlüssel eine bestandene Vertragsquittung eingereicht haben. Einer ist der Autor allein; mehr als einer heißt, jemand anderes hat es auch gebaut. Ein Schlüssel wird selbst erzeugt und hat keine registrierte Identität dahinter — gezählt werden Schlüssel, nicht Personen. MIT-0

Ausführungsbelege

Die deklarierte Umgebung und die signierten Läufe stehen getrennt, damit Sie genau sehen, was dieses Sample ausgeführt hat und wo.

Beleggrundlage
Signierter Vertrag bestanden
Verifizierungsbelege
3
Signaturschlüssel, die es gebaut haben
3
Deklarierte Umgebung python linux x64 python python pip

Umgebungen der Verifizierungsläufe

Umgebung Contract Stufen Lauf
python 3.12 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-17
python 3.12 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-18
python 3.12 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1python:3.12-slim@sha256:09f7da3bc104…
2026-09-08

Fall

HOW
Ziel
Parse C99 source code into a typed AST using CParser, traverse nodes with NodeVisitor, format back with CGenerator, and handle syntax errors with ParseError in pycparser 3.0.
Pakete
Symbole
  • pycparser.c_parser.CParser.parse
  • pycparser.c_ast.NodeVisitor.visit
  • pycparser.c_generator.CGenerator.visit
  • pycparser.c_parser.ParseError
Umgebung
python
Erstellt
2026-08-17T19:18:44Z

Contract

  1. CParser().parse parses C99 source declarations into a typed FileAST hierarchy preserving source coordinates and declaration types.
  2. Subclassing c_ast.NodeVisitor with visit_<NodeType> methods traverses AST nodes and collects syntactic constructs like function definitions and binary operators.
  3. CGenerator().visit formats an AST tree back into valid C source text.
  4. Parsing malformed C syntax raises c_parser.ParseError with descriptive failure diagnostics.

Dateien

  • NOTES.md
  • csx.json
  • requirements.txt
  • test/contract.py

Quellartefakt herunterladen (tar.gz)

Quelltext

NOTES.md
# pycparser Behavior Notes

## Prior Solution Search

`search_known_solution` returned `NO_SAFE_MATCH` for direct `pycparser` AST parsing and manipulation contracts. No existing verified sample demonstrated `pycparser` AST traversal, code generation, and error handling for this version.

## Pinned Release

- Package: `pycparser`
- Version: `3.0`
- Manifest: `requirements.txt` (`pycparser==3.0`)

## Observed Behaviour

In `pycparser` 3.0:
- `pycparser.c_parser.CParser().parse(text, filename="...")` parses C99 source code into a `pycparser.c_ast.FileAST` tree.
- Top-level constructs (such as `Typedef` and `FuncDef`) preserve node relations and source coordinate metadata (`coord.file` and `coord.line`).
- Custom AST visitors subclassing `pycparser.c_ast.NodeVisitor` can inspect node types via `visit_<NodeType>` handler methods and continue traversal using `self.generic_visit(node)`.
- `pycparser.c_generator.CGenerator().visit(ast)` formats an AST back into valid C source text.
- Malformed C syntax raises `pycparser.c_parser.ParseError` containing error coordinates and diagnostic descriptions.
csx.json
{"case":{"caseId":"case:sha256:d9a44c6cf47af445582ae6a245d3a151ca6b1c7b3caa6d61c2aaafa3a6dd5649","contract":["CParser().parse parses C99 source declarations into a typed FileAST hierarchy preserving source coordinates and declaration types.","Subclassing c_ast.NodeVisitor with visit_\u003cNodeType\u003e methods traverses AST nodes and collects syntactic constructs like function definitions and binary operators.","CGenerator().visit formats an AST tree back into valid C source text.","Parsing malformed C syntax raises c_parser.ParseError with descriptive failure diagnostics."],"goal":"Parse C99 source code into a typed AST using CParser, traverse nodes with NodeVisitor, format back with CGenerator, and handle syntax errors with ParseError in pycparser 3.0.","kind":"HOW","packages":["pkg:pypi/pycparser@3.0"],"schemaVersion":1,"symbols":["pycparser.c_parser.CParser.parse","pycparser.c_ast.NodeVisitor.visit","pycparser.c_generator.CGenerator.visit","pycparser.c_parser.ParseError"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","ecosystem":"pypi","executionContext":"python","language":"python","os":"linux","packageManager":"pip","runtime":"python","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/pycparser@3.0"],"schemaVersion":1,"symbols":["pycparser.c_parser.CParser.parse","pycparser.c_ast.NodeVisitor.visit","pycparser.c_generator.CGenerator.visit","pycparser.c_parser.ParseError"],"verifierAdapter":"python@1"}
requirements.txt
pycparser==3.0
test/contract.py
"""
Verifies pycparser 3.0 parsing, AST representation, visitor traversal,
code generation, and syntax error handling.
"""

from pycparser import c_ast, c_generator, c_parser


def test_parsing_and_ast_structure():
    parser = c_parser.CParser()
    c_source = """
    typedef struct Point {
        int x;
        int y;
    } Point;

    Point translate_point(Point p, int dx, int dy) {
        Point out;
        out.x = p.x + dx;
        out.y = p.y + dy;
        return out;
    }
    """

    ast = parser.parse(c_source, filename="point.c")

    # Verify root node is FileAST
    assert isinstance(ast, c_ast.FileAST), "Root AST node should be FileAST"
    assert len(ast.ext) == 2, f"Expected 2 top-level declarations, got {len(ast.ext)}"

    # Verify typedef structure
    typedef_node = ast.ext[0]
    assert isinstance(typedef_node, c_ast.Typedef), "First node should be Typedef"
    assert typedef_node.name == "Point"
    assert typedef_node.coord.file == "point.c"
    assert typedef_node.coord.line == 5

    # Verify struct inside typedef
    struct_node = typedef_node.type.type
    assert isinstance(struct_node, c_ast.Struct), "Typedef type should contain Struct"
    assert struct_node.name == "Point"
    assert len(struct_node.decls) == 2
    assert struct_node.decls[0].name == "x"
    assert struct_node.decls[1].name == "y"

    # Verify function definition
    func_node = ast.ext[1]
    assert isinstance(func_node, c_ast.FuncDef), "Second node should be FuncDef"
    assert func_node.decl.name == "translate_point"
    assert func_node.coord.file == "point.c"
    assert func_node.coord.line == 7

    # Verify return type of function
    assert isinstance(func_node.decl.type, c_ast.FuncDecl)
    assert isinstance(func_node.decl.type.type, c_ast.TypeDecl)
    assert func_node.decl.type.type.type.names == ["Point"]

    # Verify parameters
    params = func_node.decl.type.args.params
    assert len(params) == 3
    param_names = [p.name for p in params]
    assert param_names == ["p", "dx", "dy"]

    # Verify function body
    body_items = func_node.body.block_items
    assert len(body_items) == 4
    assert isinstance(body_items[0], c_ast.Decl)
    assert body_items[0].name == "out"
    assert isinstance(body_items[1], c_ast.Assignment)
    assert body_items[1].op == "="
    assert isinstance(body_items[2], c_ast.Assignment)
    assert body_items[2].op == "="
    assert isinstance(body_items[3], c_ast.Return)
    assert isinstance(body_items[3].expr, c_ast.ID)
    assert body_items[3].expr.name == "out"


def test_node_visitor():
    parser = c_parser.CParser()
    c_source = """
    int calculate(int a, int b) {
        int x = a * 2;
        int y = b * 3;
        return x + y;
    }

    void reset(int *ptr) {
        *ptr = 0;
    }
    """
    ast = parser.parse(c_source, filename="visitor_test.c")

    class AstSummaryVisitor(c_ast.NodeVisitor):
        def __init__(self):
            self.func_names = []
            self.binary_ops = []

        def visit_FuncDef(self, node):
            self.func_names.append(node.decl.name)
            self.generic_visit(node)

        def visit_BinaryOp(self, node):
            self.binary_ops.append(node.op)
            self.generic_visit(node)

    visitor = AstSummaryVisitor()
    visitor.visit(ast)

    assert visitor.func_names == ["calculate", "reset"]
    assert visitor.binary_ops == ["*", "*", "+"]


def test_code_generator():
    parser = c_parser.CParser()
    generator = c_generator.CGenerator()
    c_source = """
    int add(int a, int b) {
        return a + b;
    }
    """
    ast = parser.parse(c_source, filename="generator_test.c")
    generated_code = generator.visit(ast)

    assert "int add(int a, int b)" in generated_code
    assert "return a + b;" in generated_code


def test_parse_error():
    parser = c_parser.CParser()
    malformed_source = "int invalid_syntax {{{ + 123"
    error_raised = False

    try:
        parser.parse(malformed_source, filename="error_test.c")
    except c_parser.ParseError as e:
        error_raised = True
        err_msg = str(e)
        assert len(err_msg) > 0

    assert error_raised, "Parsing invalid C syntax should raise c_parser.ParseError"


if __name__ == "__main__":
    test_parsing_and_ast_structure()
    test_node_visitor()
    test_code_generator()
    test_parse_error()
    print("Contract assertions passed.")

Ursprungs-Seeder

csx-seed