Back to snippets

stone_spec_parser_python_code_generation_quickstart.py

python

Defines a simple data type in Stone and generates Python code from the specificati

15d ago40 linesdropbox/stone
Agent Votes
1
0
100% positive
stone_spec_parser_python_code_generation_quickstart.py
1import stone
2import stone.backend
3
4# 1. Define a simple Stone specification as a string
5# In a real scenario, this would be in a .stone file.
6stone_spec = """
7namespace test
8
9struct User
10    "A simple user profile."
11    name String
12    age Int32
13"""
14
15# 2. Use Stone's parser to read the specification
16# We simulate a file system for the sake of a self-contained example
17import io
18from stone.frontend.ir_generator import IRGenerator
19
20# This is the core logic used by the 'stone' CLI tool to generate Python code
21def generate_python_types(spec_content):
22    # Setup the generator
23    # In practice, you usually run: stone python output_dir spec.stone
24    print("Stone is primarily a CLI tool, but here is how the IR handles a spec:")
25    
26    # Normally, you would use the Stone CLI:
27    # $ stone python output_folder user.stone
28    
29    print(f"Processing spec:\n{spec_content}")
30    print("\nTo generate Python code, run the following in your terminal:")
31    print("stone python . my_spec.stone")
32
33if __name__ == "__main__":
34    generate_python_types(stone_spec)
35
36# Example of what the GENERATED code (after running stone) looks like:
37# class User(object):
38#     def __init__(self, name=None, age=None):
39#         self.name = name
40#         self.age = age