This Python project streamlines the process of generating C code from structured JSON input.
- No-Code/Low-Code Approach: Design C functions without writing C code directly.
- JSON-Driven: Describe the code structure in a clear, standardized format.
- AST-Based Parsing: Builds an internal representation for code generation.
- Flexible: Easily extendable to support more complex C language features.
-
Input: The script takes a JSON string as input. The JSON should describe the structure of the C function, including:
type
: Specifies the type of the JSON object, e.g., "function_declaration".name
: The name of the function.return_type
: The data type returned by the function.arguments
: An array of objects describing the function's parameters (each withname
andtype
).block
: An array of objects representing the statements within the function body (e.g., variable declarations, assignments, return statements).
-
Parsing: The
parser.py
module processes the JSON input and constructs an Abstract Syntax Tree (AST). This AST represents the structure of the function in a way that the code generator can understand. -
Code Generation: The
code_generator.py
module traverses the AST and generates the corresponding C code. This process handles variable declarations, assignments, expressions, and other C language constructs.
- ast.py # Defines the classes for the Abstract Syntax Tree (AST) nodes.
- parser.py # Contains the code to parse the JSON input and construct the AST.
- code_generator.py # Generates C code from the AST.
- main.py # Main script to demonstrate the usage of the tool.
- Python: (version 3.6 or later)
- PLY: Install using
pip install ply
The following is a sample JSON input that describes a simple function in C:
{
"type": "function_declaration",
"name": "calculate_sum",
"return_type": "int",
"arguments": [
{
"name": "a",
"type": "int"
},
{
"name": "b",
"type": "int"
}
],
"block": [
{
"type": "variable_declaration",
"declarations": [
{
"name": "sum",
"type": "int",
"value": {
"type": "binary_operation",
"operator": "+",
"left": {
"type": "variable_reference",
"name": "a"
},
"right": {
"type": "variable_reference",
"name": "b"
}
}
}
]
},
{
"type": "return_statement",
"value": {
"type": "variable_reference",
"name": "sum"
}
}
]
}
Running main.py with this input will generate the following C code:
void nested_example() {
int x = 0;
if (x == 0) {
if (x > -1) {
printf("Nested if statement");
}
}
}
Contributions are welcome! Feel free to submit issues and enhancement requests. Pull requests are also welcome.
This project is licensed under the MIT License. See the LICENSE file for more details.