샘플
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.
검증된 샘플 — pypi pycparser 3.0: Parse C99 source code into a typed AST using CParser, traverse nodes with NodeVisitor, format back with CGenerator, and handle…
sha256:3c5ca6f4d0fbebc7e9f426b8ff85289533a86a2af0b05839306773534fb7b397
이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다.
통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다.
MIT-0
실행 증거
선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.
- 증거 기준
- 서명된 컨트랙트 통과
- 검증 영수증
- 3
- 빌드한 서명 키
- 3
선언된 환경
python linux x64 python python pip
검증 실행 환경
| 환경 | 컨트랙트 | 단계 | 실행일 |
|---|---|---|---|
| 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 |
케이스
HOW- 목표
- 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.
- 패키지
- 심벌
-
- pycparser.c_parser.CParser.parse
- pycparser.c_ast.NodeVisitor.visit
- pycparser.c_generator.CGenerator.visit
- pycparser.c_parser.ParseError
- 환경
- python
- 생성일
- 2026-08-17T19:18:44Z
컨트랙트
- CParser().parse parses C99 source declarations into a typed FileAST hierarchy preserving source coordinates and declaration types.
- Subclassing c_ast.NodeVisitor with visit_<NodeType> 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.
파일
- NOTES.md
- csx.json
- requirements.txt
- test/contract.py
소스
# 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.
{"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"}
pycparser==3.0
"""
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.")