1+ import ast
2+ from pathlib import Path
3+ from symtable import Class
4+ from typing import cast
5+
6+ import astor # Install with `pip install astor`
7+ import click
8+ import os
9+ import sys
10+
11+ from lionwebpython .language import Language , Concept , Interface
12+ from lionwebpython .language .classifier import Classifier
13+ from lionwebpython .language .primitive_type import PrimitiveType
14+ from lionwebpython .lionweb_version import LionWebVersion
15+ from lionwebpython .serialization .serialization_provider import SerializationProvider
16+
17+ # Define the function AST
18+ func_def = ast .FunctionDef (
19+ name = "hello_world" ,
20+ args = ast .arguments (
21+ posonlyargs = [], args = [], kwonlyargs = [], kw_defaults = [], defaults = []
22+ ),
23+ body = [
24+ ast .Expr (value = ast .Call (
25+ func = ast .Name (id = "print" , ctx = ast .Load ()),
26+ args = [ast .Constant (value = "Hello, world!" )], keywords = []
27+ ))
28+ ],
29+ decorator_list = [],
30+ )
31+
32+ # # Convert AST to code
33+ # module = ast.Module(body=[func_def], type_ignores=[])
34+ # generated_code = astor.to_source(module)
35+ #
36+ # print(generated_code)
37+ #
38+
39+ @click .command ()
40+ @click .argument ("lionweb-language" , type = click .Path (exists = True , dir_okay = False , readable = True ))
41+ @click .argument ("output" , type = click .Path (exists = False , file_okay = False , writable = True ))
42+ def main (lionweb_language , output ):
43+ """Simple CLI that processes a file and writes results to a directory."""
44+ serialization = SerializationProvider .get_standard_json_serialization (LionWebVersion .V2023_1 )
45+ click .echo (f"📄 Processing file: { lionweb_language } " )
46+ with open (lionweb_language , "r" , encoding = "utf-8" ) as f :
47+ content = f .read ()
48+ language = cast (Language , serialization .deserialize_string_to_nodes (content )[0 ])
49+
50+ module = ast .Module (body = [], type_ignores = [])
51+ for element in language .get_elements ():
52+ if isinstance (element , Concept ):
53+ classdef = ast .ClassDef (element .get_name (), bases = [], # No parent classes
54+ keywords = [],
55+ body = [ast .Pass ()],
56+ decorator_list = [])
57+ module .body .append (classdef )
58+ elif isinstance (element , Interface ):
59+ pass
60+ elif isinstance (element , PrimitiveType ):
61+ pass
62+ else :
63+ raise ValueError (f"Unsupported { element } " )
64+ click .echo (f"📂 Saving results to: { output } " )
65+ generated_code = astor .to_source (module )
66+ output_path = Path (output )
67+ output_path .mkdir (parents = True , exist_ok = True )
68+ with Path (f"{ output } /ast.py" ).open ("w" , encoding = "utf-8" ) as f :
69+ f .write (generated_code )
70+
71+ if __name__ == "__main__" :
72+ main ()
0 commit comments