async_runtime_example/
async_runtime_example.rs1use python_ast::{parse_enhanced, CodeGenContext, PythonOptions, SymbolTableScopes, CodeGen, AsyncRuntime};
2
3fn main() {
4 let python_code = r#"
5import asyncio
6
7async def fetch_data():
8 await asyncio.sleep(1)
9 return "data"
10
11async def main():
12 result = await fetch_data()
13 print(result)
14
15if __name__ == "__main__":
16 asyncio.run(main())
17"#;
18
19 println!("=== Example 1: Tokio (default) ===");
21 let options = PythonOptions::default(); generate_and_display(python_code, options);
23
24 println!("\n=== Example 2: async-std ===");
26 let options = PythonOptions::with_async_std();
27 generate_and_display(python_code, options);
28
29 println!("\n=== Example 3: smol ===");
31 let options = PythonOptions::with_smol();
32 generate_and_display(python_code, options);
33
34 println!("\n=== Example 4: Custom runtime ===");
36 let options = PythonOptions::with_custom_runtime("my_runtime::main", "my_runtime");
37 generate_and_display(python_code, options);
38
39 println!("\n=== Example 5: Programmatic configuration ===");
41 let mut options = PythonOptions::default();
42 options.set_async_runtime(AsyncRuntime::AsyncStd);
43 generate_and_display(python_code, options);
44}
45
46fn generate_and_display(python_code: &str, options: PythonOptions) {
47 match parse_enhanced(python_code, "example.py") {
48 Ok(ast) => {
49 let ctx = CodeGenContext::Module("example".to_string());
50 let symbols = SymbolTableScopes::new();
51
52 match ast.to_rust(ctx, options, symbols) {
53 Ok(tokens) => {
54 let code_str = tokens.to_string();
55
56 println!("Generated Rust code:");
58
59 let parts: Vec<&str> = code_str.split(" ; ").collect();
61 for part in &parts {
62 if part.starts_with("use ") {
63 println!(" {}", part.trim());
64 }
65 }
66
67 if let Some(main_start) = code_str.find("# [") {
69 if let Some(main_end) = code_str[main_start..].find("async fn main") {
70 if let Some(brace) = code_str[main_start + main_end..].find(" {") {
71 let main_signature = &code_str[main_start..main_start + main_end + brace + 2];
72 println!(" {}", main_signature.trim());
73 println!(" // ... main function body ...");
74 println!(" }}");
75 }
76 }
77 }
78 }
79 Err(e) => {
80 println!("❌ Code generation failed: {}", e);
81 }
82 }
83 },
84 Err(e) => {
85 println!("❌ AST parsing failed: {}", e);
86 }
87 }
88}