waspy 0.11.0

A Python interpreter written in Rust, designed for WebAssembly.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
//! Waspy: A Python to WebAssembly compiler written in Rust.
//!
//! Waspy translates Python functions into WebAssembly, allowing Python code
//! to run in browsers and other WebAssembly environments.

pub mod analysis;
pub mod compiler;
pub mod core;
pub mod ir;
pub mod optimize;
pub mod stdlib;
pub mod utils;

// WASM plugin integration
#[cfg(feature = "wasm-plugin")]
pub mod wasmrun;

#[cfg(feature = "wasm-plugin")]
pub use wasmrun::{WaspyBuilder, WaspyPlugin};

use crate::core::config::ProjectConfig;
pub use crate::core::options::{CompilerOptions, Verbosity};
use crate::ir::{EntryPointInfo, IRType};
use anyhow::{anyhow, Context, Result};
use std::fs;
use std::path::Path;

/// Compile Python source code into a WASM binary using default options.
///
/// # Arguments
///
/// * `source` - Python source code to compile
///
/// # Returns
///
/// WebAssembly binary as a byte vector
///
/// # Errors
///
/// Returns an error if parsing, IR conversion, or WebAssembly generation fails
pub fn compile_python_to_wasm(source: &str) -> Result<Vec<u8>> {
    compile_python_to_wasm_with_options(source, &CompilerOptions::default())
}

/// Compile Python source code into a WASM binary with specified options.
///
/// # Arguments
///
/// * `source` - Python source code to compile
/// * `options` - Compiler options
///
/// # Returns
///
/// WebAssembly binary as a byte vector
///
/// # Errors
///
/// Returns an error if parsing, IR conversion, or WebAssembly generation fails
pub fn compile_python_to_wasm_with_options(
    source: &str,
    options: &CompilerOptions,
) -> Result<Vec<u8>> {
    // Initialize logging with the specified verbosity
    utils::logging::init(options.verbosity);

    log_debug!("Starting compilation with options: {:?}", options);

    // Parse Python to AST
    log_verbose!("Parsing Python source code...");
    let ast = core::parser::parse_python(source).context("Failed to parse Python code")?;
    log_debug!("Successfully parsed Python AST");

    // Lower AST to IR
    log_verbose!("Converting AST to intermediate representation...");
    let mut ir_module = ir::lower_ast_to_ir(&ast).context("Failed to convert Python AST to IR")?;
    log_debug!(
        "Generated IR module with {} functions",
        ir_module.functions.len()
    );

    // Process decorators
    log_verbose!("Processing decorators...");
    let decorator_registry = ir::DecoratorRegistry::new();
    ir_module.functions = ir_module
        .functions
        .into_iter()
        .map(|func| {
            if !func.decorators.is_empty() {
                log_debug!("Applying decorators to function: {}", func.name);
                decorator_registry.apply_decorators(func)
            } else {
                func
            }
        })
        .collect();
    log_verbose!("{:#?}", ir_module);
    // Check for entry points
    log_verbose!("Detecting entry points...");
    if let Ok(Some(entry_point_info)) = ir::detect_entry_points(source, None) {
        log_debug!("Found entry point: {:?}", entry_point_info);
        // Add entry point support if detected
        ir::add_entry_point_to_module(&mut ir_module, &entry_point_info)?;
    }

    // Generate WASM binary
    log_verbose!("Generating WebAssembly binary...");
    let raw_wasm = compiler::compile_ir_module(&ir_module);
    log_debug!("Generated WASM binary: {} bytes", raw_wasm.len());

    // Optimize the WASM binary if requested
    if options.optimize {
        log_verbose!("Optimizing WebAssembly binary...");
        let optimized =
            optimize::optimize_wasm(&raw_wasm).context("Failed to optimize WebAssembly binary")?;
        log_debug!(
            "Optimized WASM binary: {} bytes (saved {} bytes)",
            optimized.len(),
            raw_wasm.len() as i64 - optimized.len() as i64
        );
        Ok(optimized)
    } else {
        log_debug!("Skipping optimization");
        Ok(raw_wasm)
    }
}

/// Compile multiple Python source files into a single WASM binary.
///
/// # Arguments
///
/// * `sources` - Array of (filename, source code) pairs
/// * `optimize` - Whether to optimize the output
///
/// # Returns
///
/// WebAssembly binary as a byte vector
///
/// # Errors
///
/// Returns an error if parsing, IR conversion, or WebAssembly generation fails
pub fn compile_multiple_python_files(sources: &[(&str, &str)], optimize: bool) -> Result<Vec<u8>> {
    let options = CompilerOptions {
        optimize,
        ..CompilerOptions::default()
    };

    compile_multiple_python_files_with_options(sources, &options)
}

/// Compile multiple Python source files with options.
///
/// # Arguments
///
/// * `sources` - Array of (filename, source code) pairs
/// * `options` - Compiler options
///
/// # Returns
///
/// WebAssembly binary as a byte vector
///
/// # Errors
///
/// Returns an error if parsing, IR conversion, or WebAssembly generation fails
pub fn compile_multiple_python_files_with_options(
    sources: &[(&str, &str)],
    options: &CompilerOptions,
) -> Result<Vec<u8>> {
    // Parse and convert each Python source to IR
    let mut combined_module = ir::IRModule::new();
    let mut function_names = std::collections::HashSet::new();
    let mut has_entry_point = false;
    let mut entry_point_info: Option<EntryPointInfo> = None;

    for (filename, source) in sources {
        // Skip incompatible files
        if utils::is_special_python_file(filename) {
            log_verbose!("Skipping special file: {filename}");
            continue;
        }

        // Check for entry points
        if !has_entry_point {
            if let Ok(Some(info)) = ir::detect_entry_points(source, Some(Path::new(filename))) {
                has_entry_point = true;
                entry_point_info = Some(info);
                log_debug!("Detected entry point in file: {filename}");
            }
        }

        log_debug!("Processing file: {filename}");

        // Parse Python to AST
        let ast = match core::parser::parse_python(source) {
            Ok(ast) => ast,
            Err(e) => {
                log_warn!("Failed to parse {filename}: {e}");
                continue;
            }
        };

        // Lower AST to IR
        let ir_module = match ir::lower_ast_to_ir(&ast) {
            Ok(module) => module,
            Err(e) => {
                log_warn!("Failed to convert {filename} to IR: {e}");
                continue;
            }
        };

        // Skip if no functions
        if ir_module.functions.is_empty() {
            log_verbose!("Skipping file with no functions: {filename}");
            continue;
        }

        log_debug!(
            "Found {} functions in {filename}",
            ir_module.functions.len()
        );

        // Check for duplicate function names and add functions
        for func in ir_module.functions {
            if !function_names.insert(func.name.clone()) {
                log_warn!(
                    "Duplicate function '{}' found in file: {}",
                    func.name,
                    filename
                );
                // Skip the duplicate but continue processing
            } else {
                log_debug!("Adding function: {}", func.name);
                // Add the function
                combined_module.functions.push(func);
            }
        }

        // Add module-level variables and imports (might use these later)
        combined_module.variables.extend(ir_module.variables);
        combined_module.imports.extend(ir_module.imports);
        combined_module.classes.extend(ir_module.classes);

        // Merge this file's string/bytes layout into the combined module.
        combined_module
            .memory_layout
            .merge_from(&ir_module.memory_layout);
    }

    if combined_module.functions.is_empty() {
        return Err(anyhow!(
            "No valid functions found in any of the provided files"
        ));
    }

    // Process decorators on the combined module
    let decorator_registry = ir::DecoratorRegistry::new();
    combined_module.functions = combined_module
        .functions
        .into_iter()
        .map(|func| {
            if !func.decorators.is_empty() {
                decorator_registry.apply_decorators(func)
            } else {
                func
            }
        })
        .collect();

    // Add entry point if one was detected
    if has_entry_point {
        if let Some(info) = entry_point_info {
            ir::add_entry_point_to_module(&mut combined_module, &info)?;
        }
    }

    // Generate WASM binary from the combined module
    let raw_wasm = compiler::compile_ir_module(&combined_module);

    // Optimize the WASM binary
    if options.optimize {
        optimize::optimize_wasm(&raw_wasm).context("Failed to optimize WebAssembly binary")
    } else {
        Ok(raw_wasm)
    }
}

/// Compile multiple Python source files into a single WASM binary with config awareness.
///
/// # Arguments
///
/// * `sources` - Array of (filename, source code) pairs
/// * `optimize` - Whether to optimize the output
/// * `config` - Project configuration
///
/// # Returns
///
/// WebAssembly binary as a byte vector
///
/// # Errors
///
/// Returns an error if parsing, IR conversion, or WebAssembly generation fails
pub fn compile_multiple_python_files_with_config(
    sources: &[(&str, &str)],
    optimize: bool,
    config: &ProjectConfig,
) -> Result<Vec<u8>> {
    // Parse and convert each Python source to IR
    let mut combined_module = ir::IRModule::new();
    let mut function_names = std::collections::HashSet::new();
    let mut has_entry_point = false;
    let mut entry_point_info: Option<EntryPointInfo> = None;

    // Set project metadata if available
    if !config.name.is_empty() {
        combined_module
            .metadata
            .insert("project_name".to_string(), config.name.clone());
        combined_module
            .metadata
            .insert("project_version".to_string(), config.version.clone());

        if let Some(description) = &config.description {
            combined_module
                .metadata
                .insert("project_description".to_string(), description.clone());
        }

        if let Some(author) = &config.author {
            combined_module
                .metadata
                .insert("project_author".to_string(), author.clone());
        }
    }

    for (filename, source) in sources {
        // Skip incompatible files
        if core::config::is_config_file(filename) {
            log_verbose!("Skipping configuration file: {filename}");
            continue;
        }

        // Skip incompatible files
        if utils::is_special_python_file(filename) {
            log_verbose!("Skipping special file: {filename}");
            continue;
        }

        // Check for entry points
        if !has_entry_point {
            if let Ok(Some(info)) = ir::detect_entry_points(source, Some(Path::new(filename))) {
                has_entry_point = true;
                entry_point_info = Some(info);
                log_debug!("Detected entry point in file: {filename}");
            }
        }

        log_debug!("Processing file: {filename}");

        // Parse Python to AST
        let ast = match core::parser::parse_python(source) {
            Ok(ast) => ast,
            Err(e) => {
                log_warn!("Failed to parse {filename}: {e}");
                continue;
            }
        };

        // Lower AST to IR
        let ir_module = match ir::lower_ast_to_ir(&ast) {
            Ok(module) => module,
            Err(e) => {
                log_warn!("Failed to convert {filename} to IR: {e}");
                continue;
            }
        };

        // Skip if no functions
        if ir_module.functions.is_empty() {
            log_verbose!("Skipping file with no functions: {filename}");
            continue;
        }

        log_debug!(
            "Found {} functions in {filename}",
            ir_module.functions.len()
        );

        // Check for duplicate function names and add functions
        for func in ir_module.functions {
            if !function_names.insert(func.name.clone()) {
                log_warn!(
                    "Duplicate function '{}' found in file: {}",
                    func.name,
                    filename
                );
                // Skip the duplicate but continue processing
            } else {
                log_debug!("Adding function: {}", func.name);
                // Add the function
                combined_module.functions.push(func);
            }
        }

        // Add module-level variables and imports
        combined_module.variables.extend(ir_module.variables);
        combined_module.imports.extend(ir_module.imports);
        combined_module.classes.extend(ir_module.classes);

        // Merge this file's string/bytes layout into the combined module.
        combined_module
            .memory_layout
            .merge_from(&ir_module.memory_layout);

        // Add module-level metadata
        for (key, value) in ir_module.metadata {
            combined_module.metadata.insert(key, value);
        }
    }

    if combined_module.functions.is_empty() {
        return Err(anyhow!(
            "No valid functions found in any of the provided files"
        ));
    }

    // Add entry point if one was detected
    if has_entry_point {
        if let Some(info) = entry_point_info {
            ir::add_entry_point_to_module(&mut combined_module, &info)?;
        }
    }

    // Generate WASM binary from the combined module
    let raw_wasm = compiler::compile_ir_module(&combined_module);

    // Optimize the WASM binary
    if optimize {
        optimize::optimize_wasm(&raw_wasm).context("Failed to optimize WebAssembly binary")
    } else {
        Ok(raw_wasm)
    }
}

/// Compile a Python project directory to WebAssembly.
///
/// # Arguments
///
/// * `project_dir` - Path to project directory
/// * `optimize` - Whether to optimize the output
///
/// # Returns
///
/// WebAssembly binary as a byte vector
///
/// # Errors
///
/// Returns an error if parsing, IR conversion, or WebAssembly generation fails
pub fn compile_python_project<P: AsRef<Path>>(project_dir: P, optimize: bool) -> Result<Vec<u8>> {
    let options = CompilerOptions {
        optimize,
        ..CompilerOptions::default()
    };

    compile_python_project_with_options(project_dir, &options)
}

/// Compile a Python project with options.
///
/// # Arguments
///
/// * `project_dir` - Path to project directory
/// * `options` - Compiler options
///
/// # Returns
///
/// WebAssembly binary as a byte vector
///
/// # Errors
///
/// Returns an error if parsing, IR conversion, or WebAssembly generation fails
pub fn compile_python_project_with_options<P: AsRef<Path>>(
    project_dir: P,
    options: &CompilerOptions,
) -> Result<Vec<u8>> {
    // Initialize logging with the specified verbosity
    utils::logging::init(options.verbosity);

    // Load and analyze the project
    let project_dir = project_dir.as_ref();

    log_info!("Analyzing project structure...");
    log_debug!("Project directory: {}", project_dir.display());

    // Load project configuration
    let config = core::config::load_project_config(project_dir)?;

    log_info!("Project Name: {}", config.name);
    log_info!("Project Version: {}", config.version);
    if let Some(description) = &config.description {
        log_verbose!("Description: {description}");
    }
    if let Some(author) = &config.author {
        log_verbose!("Author: {author}");
    }

    let files = utils::collect_compilable_python_files(project_dir)?;

    if files.is_empty() {
        return Err(anyhow!("No compilable Python files found in the project"));
    }

    // Look for entry points in the project
    let mut entry_point_file = None;
    let mut entry_point_info = None;

    log_verbose!("Searching for entry points...");
    // First, check for __main__.py
    let main_py_path = project_dir.join("__main__.py");
    if main_py_path.exists() && main_py_path.is_file() {
        log_debug!("Checking __main__.py for entry point");
        if let Ok(content) = fs::read_to_string(&main_py_path) {
            if let Ok(Some(info)) = ir::detect_entry_points(&content, Some(&main_py_path)) {
                entry_point_file = Some("__main__.py".to_string());
                entry_point_info = Some(info);
            }
        }
    }

    // If no __main__.py, check other files for entry points
    if entry_point_info.is_none() {
        for (path, content) in &files {
            log_debug!("Checking {} for entry point", path);
            if let Ok(Some(info)) = ir::detect_entry_points(content, Some(Path::new(path))) {
                entry_point_file = Some(path.clone());
                entry_point_info = Some(info);
                break;
            }
        }
    }

    if let Some(file) = &entry_point_file {
        log_info!("Found entry point in file: {file}");
    } else {
        log_debug!("No entry point detected");
    }

    log_info!("Found {} compilable Python files", files.len());
    log_debug!("Files: {:?}", files.keys().collect::<Vec<_>>());

    // Convert to the format expected by compile_multiple_python_files
    let sources: Vec<(&str, &str)> = files
        .iter()
        .map(|(path, content)| (path.as_str(), content.as_str()))
        .collect();

    // Compile all files together
    let result = compile_multiple_python_files_with_config(&sources, options.optimize, &config)?;

    // If we found an entry point, we might need to add special handling here
    if entry_point_info.is_some() {
        // We've already integrated this in compile_multiple_python_files_with_config
        // But could add any additional entry point processing here
    }

    Ok(result)
}

/// Get metadata about a Python source file without compiling to WASM.
/// Returns a list of function signatures for documentation or analysis.
///
/// # Arguments
///
/// * `source` - Python source code
///
/// # Returns
///
/// List of function signatures
///
/// # Errors
///
/// Returns an error if parsing or IR conversion fails
pub fn get_python_file_metadata(
    source: &str,
) -> Result<Vec<analysis::metadata::FunctionSignature>> {
    // Parse Python to AST
    let ast = core::parser::parse_python(source).context("Failed to parse Python code")?;

    // Lower AST to IR
    let ir_module = ir::lower_ast_to_ir(&ast).context("Failed to convert Python AST to IR")?;

    // Extract function signatures
    let mut signatures = Vec::new();
    for func in &ir_module.functions {
        let param_types: Vec<String> = func
            .params
            .iter()
            .map(|p| format!("{}: {}", p.name, type_to_string(&p.param_type)))
            .collect();

        signatures.push(analysis::metadata::FunctionSignature {
            name: func.name.clone(),
            parameters: param_types,
            return_type: type_to_string(&func.return_type),
        });
    }

    Ok(signatures)
}

/// Get metadata about an entire Python project.
/// Returns a list of function signatures for all files.
///
/// # Arguments
///
/// * `project_dir` - Path to project directory
///
/// # Returns
///
/// List of (file path, function signatures) pairs
///
/// # Errors
///
/// Returns an error if parsing or IR conversion fails
pub fn get_python_project_metadata<P: AsRef<Path>>(
    project_dir: P,
) -> Result<Vec<(String, Vec<analysis::metadata::FunctionSignature>)>> {
    let project_dir = project_dir.as_ref();
    let files = utils::collect_compilable_python_files(project_dir)?;

    let mut all_metadata = Vec::new();

    for (path, content) in files {
        match get_python_file_metadata(&content) {
            Ok(signatures) => {
                if !signatures.is_empty() {
                    all_metadata.push((path, signatures));
                }
            }
            Err(e) => {
                println!("Warning: Failed to extract metadata from {path}: {e}");
            }
        }
    }

    Ok(all_metadata)
}

/// Convert IR type to string
pub fn type_to_string(ir_type: &IRType) -> String {
    match ir_type {
        IRType::Int => "int".to_string(),
        IRType::Float => "float".to_string(),
        IRType::Bool => "bool".to_string(),
        IRType::String => "str".to_string(),
        IRType::List(elem_type) => format!("List[{}]", type_to_string(elem_type)),
        IRType::Dict(key_type, val_type) => format!(
            "Dict[{}, {}]",
            type_to_string(key_type),
            type_to_string(val_type)
        ),
        IRType::Tuple(types) => {
            let inner = types
                .iter()
                .map(type_to_string)
                .collect::<Vec<_>>()
                .join(", ");
            format!("Tuple[{inner}]")
        }
        IRType::Optional(inner) => format!("Optional[{}]", type_to_string(inner)),
        IRType::Union(types) => {
            let inner = types
                .iter()
                .map(type_to_string)
                .collect::<Vec<_>>()
                .join(" | ");
            format!("Union[{inner}]")
        }
        IRType::Class(name) => name.clone(),
        IRType::Module(name) => format!("Module[{name}]"),
        IRType::Bytes => "bytes".to_string(),
        IRType::Set(elem_type) => format!("Set[{}]", type_to_string(elem_type)),
        IRType::Range => "range".to_string(),
        IRType::None => "None".to_string(),
        IRType::Any => "Any".to_string(),
        IRType::Unknown => "unknown".to_string(),
        IRType::Callable { .. } => "Callable".to_string(),
        IRType::Generator(yield_type) => format!("Generator[{}]", type_to_string(yield_type)),
        IRType::Datetime => "datetime.datetime".to_string(),
        IRType::Date => "datetime.date".to_string(),
        IRType::Time => "datetime.time".to_string(),
        IRType::Timedelta => "datetime.timedelta".to_string(),
    }
}

pub use crate::analysis::metadata::FunctionSignature;
pub use crate::core::parser;

#[cfg(test)]
mod collection_tests {
    use super::*;

    use wasmi::{Engine, Linker, Module, Store};

    /// Compile (unoptimized) and instantiate the module, returning the wasmi
    /// instance + store so a test can call exported functions. Instantiation
    /// validates types and stack balance, so this also guards the codegen bugs
    /// that previously produced invalid modules.
    fn instantiate(source: &str) -> (wasmi::Instance, Store<()>) {
        let options = CompilerOptions {
            optimize: false,
            ..CompilerOptions::default()
        };
        let wasm = compile_python_to_wasm_with_options(source, &options).expect("compilation");
        let engine = Engine::default();
        let module = Module::new(&engine, &wasm[..]).expect("valid wasm module");
        let mut store = Store::new(&engine, ());
        let instance = Linker::<()>::new(&engine)
            .instantiate(&mut store, &module)
            .expect("instantiation")
            .start(&mut store)
            .expect("start");
        (instance, store)
    }

    fn call_i32(source: &str, func: &str) -> i32 {
        let (instance, mut store) = instantiate(source);
        instance
            .get_typed_func::<(), i32>(&store, func)
            .expect("exported i32 fn")
            .call(&mut store, ())
            .expect("call")
    }

    fn call_i32_arg(source: &str, func: &str, arg: i32) -> i32 {
        let (instance, mut store) = instantiate(source);
        instance
            .get_typed_func::<i32, i32>(&store, func)
            .expect("exported i32 fn")
            .call(&mut store, arg)
            .expect("call")
    }

    /// A rectangle class with float fields, used by the class+float tests. Each
    /// test function returns 1 when the float computation matches its expected
    /// value (the wasmi build in use can't return an f64 directly).
    const RECT_SRC: &str = "class Rectangle:\n    default_width = 10\n    default_height = 5\n    def __init__(self, width: float, height: float):\n        self.width = width\n        self.height = height\n    def area(self) -> float:\n        return self.width * self.height\n    def perimeter(self) -> float:\n        return 2 * (self.width + self.height)\n    def scale(self, factor: float) -> None:\n        self.width *= factor\n        self.height *= factor\n";

    #[test]
    fn class_float_fields_and_methods() {
        // Float instance fields are stored/loaded as f64, and a method returning
        // a float computes correctly (previously fields read as i32 and the f64
        // return mismatched).
        let area = format!(
            "{RECT_SRC}def f() -> int:\n    r = Rectangle(10.0, 5.0)\n    if r.area() == 50.0:\n        return 1\n    return 0\n"
        );
        assert_eq!(call_i32(&area, "f"), 1);
        // `2 * (a + b)` keeps the float result instead of truncating it to int.
        let perim = format!(
            "{RECT_SRC}def f() -> int:\n    r = Rectangle(10.0, 5.0)\n    if r.perimeter() == 30.0:\n        return 1\n    return 0\n"
        );
        assert_eq!(call_i32(&perim, "f"), 1);
    }

    #[test]
    fn class_int_args_coerced_to_float() {
        // Int literals passed to float constructor parameters widen to f64.
        let src = format!(
            "{RECT_SRC}def f() -> int:\n    r = Rectangle(3, 4)\n    if r.area() == 12.0:\n        return 1\n    return 0\n"
        );
        assert_eq!(call_i32(&src, "f"), 1);
    }

    #[test]
    fn class_augmented_field_assign() {
        // `self.width *= factor` performs an f64 load/mul/store (was a no-op).
        let src = format!(
            "{RECT_SRC}def f() -> int:\n    r = Rectangle(2.0, 3.0)\n    r.scale(2.0)\n    if r.area() == 24.0:\n        return 1\n    return 0\n"
        );
        assert_eq!(call_i32(&src, "f"), 1);
    }

    #[test]
    fn class_variable_access() {
        // `ClassName.classvar` reads the class-level variable's value (10 * 5).
        let src = format!(
            "{RECT_SRC}def f() -> int:\n    r = Rectangle(Rectangle.default_width, Rectangle.default_height)\n    if r.area() == 50.0:\n        return 1\n    return 0\n"
        );
        assert_eq!(call_i32(&src, "f"), 1);
    }

    #[test]
    fn float_list_roundtrips() {
        // Reads the float element back and compares (returns 1 on match). The
        // value is stored as f32; 2.5 is exact, so equality holds.
        let src = "def f() -> int:\n    xs = [1.5, 2.5, 3.5]\n    if xs[1] == 2.5:\n        return 1\n    return 0\n";
        assert_eq!(call_i32(src, "f"), 1);
    }

    #[test]
    fn float_tuple_roundtrips() {
        let src = "def f() -> int:\n    t = (1.25, 2.75)\n    if t[1] == 2.75:\n        return 1\n    return 0\n";
        assert_eq!(call_i32(src, "f"), 1);
    }

    #[test]
    fn int_list_indexing_returns_element() {
        // Previously returned a constant 0: the untyped local lost its type.
        let src = "def f() -> int:\n    xs = [10, 20, 30]\n    return xs[1]\n";
        assert_eq!(call_i32(src, "f"), 20);
    }

    #[test]
    fn string_read_back_from_list_has_length() {
        // A string element stores only its offset; reading it back rebuilds the
        // (offset, length) pair from the blob's length prefix. Previously this
        // dropped the length, so binding it to a local emitted invalid WASM
        // ("not enough arguments on the stack for local.set").
        let src =
            "def f() -> int:\n    xs = [\"alpha\", \"beta\", \"gamma\"]\n    w = xs[1]\n    return len(w)\n";
        assert_eq!(call_i32(src, "f"), 4);
    }

    #[test]
    fn string_read_back_from_tuple_has_length() {
        let src =
            "def f() -> int:\n    t = (\"one\", \"three\", \"x\")\n    w = t[1]\n    return len(w)\n";
        assert_eq!(call_i32(src, "f"), 5);
    }

    #[test]
    fn string_read_back_preserves_identity() {
        // The recovered offset is the interned one, so membership (offset
        // comparison) still finds the value pulled back out of the list.
        let src = "def f() -> int:\n    xs = [\"alpha\", \"beta\", \"gamma\"]\n    w = xs[1]\n    if w in xs:\n        return 1\n    return 0\n";
        assert_eq!(call_i32(src, "f"), 1);
    }

    #[test]
    fn string_membership_unaffected_by_read_back() {
        // Reading strings out of collections must not regress offset-based
        // membership/dedup, which the length-prefix layout leaves untouched.
        let present =
            "def f() -> int:\n    xs = [\"a\", \"b\", \"c\"]\n    if \"b\" in xs:\n        return 1\n    return 0\n";
        assert_eq!(call_i32(present, "f"), 1);
        let absent =
            "def f() -> int:\n    xs = [\"a\", \"b\", \"c\"]\n    if \"z\" in xs:\n        return 1\n    return 0\n";
        assert_eq!(call_i32(absent, "f"), 0);
        let set_dedup =
            "def f() -> int:\n    s = {\"x\", \"y\", \"x\", \"z\"}\n    return len(s)\n";
        assert_eq!(call_i32(set_dedup, "f"), 3);
    }

    #[test]
    fn string_concatenation_round_trips() {
        // Real runtime concatenation: `__alloc` a fresh blob and copy both
        // operands in (was a placeholder that aliased the left operand).
        let len = "def f() -> int:\n    a = \"foo\"\n    b = \"barbar\"\n    return len(a + b)\n";
        assert_eq!(call_i32(len, "f"), 9);
        // The concatenated string round-trips through a list slot too.
        let via_list = "def f() -> int:\n    a = \"foo\"\n    b = \"bar\"\n    xs = [a + b]\n    w = xs[0]\n    return len(w)\n";
        assert_eq!(call_i32(via_list, "f"), 6);
    }

    #[test]
    fn distinct_collections_do_not_alias() {
        // Both lists previously shared one address (base + local_count*100).
        let src =
            "def f() -> int:\n    a = [1, 2, 3]\n    b = [10, 20, 30]\n    return a[0] + b[0]\n";
        assert_eq!(call_i32(src, "f"), 11);
    }

    #[test]
    fn nested_collections_do_not_alias() {
        let src = "def f() -> int:\n    m = [[1, 2], [3, 4]]\n    return m[0][1] + m[1][0]\n";
        assert_eq!(call_i32(src, "f"), 5);
    }

    #[test]
    fn print_of_collection_element_is_valid() {
        // print() returns nothing; a stray drop would underflow and fail to
        // instantiate. Just ensure it builds and instantiates.
        instantiate("def f():\n    xs = [1, 2, 3]\n    print(xs[0])\n");
    }

    #[test]
    fn range_for_loop_iterates() {
        // for-over-range: previously the loop's iterator locals were added
        // after the function's locals were fixed (out-of-range), and the range
        // object's fields were stored with reversed operands, so the loop ran
        // zero times. Sum 0..5 (with step) to exercise both.
        let sum =
            "def f() -> int:\n    t = 0\n    for i in range(5):\n        t = t + i\n    return t\n";
        assert_eq!(call_i32(sum, "f"), 10);
        let step = "def f() -> int:\n    t = 0\n    for i in range(0, 10, 2):\n        t = t + i\n    return t\n";
        assert_eq!(call_i32(step, "f"), 20);
    }

    #[test]
    fn descending_range_for_loop_iterates() {
        // range(start, stop, -step): the loop's break test was ascending-only
        // (current >= stop), so a descending range exited immediately. The step
        // also relied on integer unary negation, which evaluated `-x` as `x`.
        let down = "def f() -> int:\n    t = 0\n    for i in range(10, 0, -1):\n        t = t + i\n    return t\n";
        assert_eq!(call_i32(down, "f"), 55);
        let neg = "def f() -> int:\n    t = 0\n    for i in range(20, 5, -3):\n        t = t + i\n    return t\n";
        assert_eq!(call_i32(neg, "f"), 70);
        let empty = "def f() -> int:\n    t = 0\n    for i in range(0, 5, -1):\n        t = t + i\n    return t\n";
        assert_eq!(call_i32(empty, "f"), 0);
    }

    #[test]
    fn integer_unary_negation() {
        // `-x` previously emitted `operand - 0`, leaving the value unchanged.
        let src = "def f() -> int:\n    x = 7\n    return -x\n";
        assert_eq!(call_i32(src, "f"), -7);
    }

    #[test]
    fn nested_range_loops_use_distinct_iterators() {
        let src = "def f() -> int:\n    s = 0\n    for i in range(3):\n        for j in range(4):\n            s = s + 1\n    return s\n";
        assert_eq!(call_i32(src, "f"), 12);
    }

    #[test]
    fn bytes_local_round_trips() {
        // A string/bytes value is an (offset, length) pair, but a local holds
        // one word; without a companion length local the offset was dropped, so
        // indexing read from offset 0 and len() returned 0.
        let idx = "def f() -> int:\n    b = b\"hello\"\n    return b[0]\n";
        assert_eq!(call_i32(idx, "f"), 104); // 'h'
        let idx1 = "def f() -> int:\n    b = b\"hello\"\n    return b[1]\n";
        assert_eq!(call_i32(idx1, "f"), 101); // 'e'
        let length = "def f() -> int:\n    b = b\"hello\"\n    return len(b)\n";
        assert_eq!(call_i32(length, "f"), 5);
    }

    #[test]
    fn string_local_len() {
        // len() of a string local previously kept the offset, not the length.
        let src = "def f() -> int:\n    s = \"hello\"\n    return len(s)\n";
        assert_eq!(call_i32(src, "f"), 5);
    }

    #[test]
    fn bytes_slicing_round_trips() {
        // `Expr::Slice` now lowers, and the slice codegen is branchless so it
        // validates. Slices share the source bytes' backing memory.
        let mid = "def f() -> int:\n    b = b\"hello\"\n    s = b[1:4]\n    return s[0]\n";
        assert_eq!(call_i32(mid, "f"), 101); // b"ell"[0] == 'e'
        let mid_len = "def f() -> int:\n    b = b\"hello\"\n    s = b[1:4]\n    return len(s)\n";
        assert_eq!(call_i32(mid_len, "f"), 3);
        let open_end = "def f() -> int:\n    b = b\"hello\"\n    return len(b[2:])\n";
        assert_eq!(call_i32(open_end, "f"), 3);
        let open_start = "def f() -> int:\n    b = b\"hello\"\n    return len(b[:3])\n";
        assert_eq!(call_i32(open_start, "f"), 3);
        let negative = "def f() -> int:\n    b = b\"hello\"\n    s = b[-2:]\n    return s[0]\n";
        assert_eq!(call_i32(negative, "f"), 108); // b"lo"[0] == 'l'
    }

    #[test]
    fn bytes_concatenation_round_trips() {
        let src =
            "def f() -> int:\n    a = b\"ab\"\n    c = b\"cd\"\n    d = a + c\n    return d[3]\n";
        assert_eq!(call_i32(src, "f"), 100); // 'd'
        let len = "def f() -> int:\n    a = b\"ab\"\n    c = b\"cd\"\n    return len(a + c)\n";
        assert_eq!(call_i32(len, "f"), 4);
    }

    #[test]
    fn try_except_finally_is_valid_and_runs() {
        // try/except/finally previously emitted an extra End that closed the
        // function frame early ("body shorter than given size").
        let src = "def f(x: int) -> int:\n    try:\n        return x + 1\n    except ValueError:\n        return -1\n    finally:\n        x = x + 100\n";
        assert_eq!(call_i32_arg(src, "f", 5), 6);
    }

    #[test]
    fn nested_try_except_is_valid() {
        let src = "def f(x: int) -> int:\n    try:\n        try:\n            return x + 5\n        except KeyError:\n            return -2\n    except ValueError:\n        return -1\n";
        assert_eq!(call_i32_arg(src, "f", 5), 10);
    }

    #[test]
    fn int_plus_float_coerces() {
        // a (int) + b (float) widens the int to f64; the result equals 3.5.
        let src = "def f() -> int:\n    a = 2\n    b = 1.5\n    if (a + b) == 3.5:\n        return 1\n    return 0\n";
        assert_eq!(call_i32(src, "f"), 1);
    }

    #[test]
    fn boolean_and_or_short_circuit() {
        // and/or now yield an i32 result from their if/else instead of an
        // empty block type.
        let and =
            "def f(a: int) -> int:\n    if (a > 0) and (a < 10):\n        return 1\n    return 0\n";
        assert_eq!(call_i32_arg(and, "f", 5), 1);
        assert_eq!(call_i32_arg(and, "f", 20), 0);
        let or =
            "def f(a: int) -> int:\n    if (a < 0) or (a > 100):\n        return 1\n    return 0\n";
        assert_eq!(call_i32_arg(or, "f", -1), 1);
        assert_eq!(call_i32_arg(or, "f", 50), 0);
    }

    #[test]
    fn unannotated_float_local_in_mixed_function() {
        // `result` is an unannotated float local (f64) living alongside the int
        // local `i`; both the type inference and index-order local layout must
        // be right for this to validate and compute 2**10.
        let src = "def f() -> int:\n    result = 1.0\n    i = 0\n    while i < 10:\n        result = result * 2.0\n        i = i + 1\n    if result == 1024.0:\n        return 1\n    return 0\n";
        assert_eq!(call_i32(src, "f"), 1);
    }

    #[test]
    fn module_level_float_constant_is_inlined() {
        // A module-level float constant used in arithmetic; emitting it at its
        // natural type (not the caller's expectation) keeps it an f64.
        let src = "PI = 2.5\ndef f() -> int:\n    if (PI * 4.0) == 10.0:\n        return 1\n    return 0\n";
        assert_eq!(call_i32(src, "f"), 1);
    }

    #[test]
    fn int_and_float_conversions() {
        // int() truncates a float; float() widens an int.
        let src = "def f() -> int:\n    return int(3.7) + int(float(2))\n";
        assert_eq!(call_i32(src, "f"), 5);
    }

    #[test]
    fn math_float_constant_local() {
        // `math.pi`/`math.tau` are f64 stdlib constants; their locals must be
        // f64 (previously an f64 store landed in an i32 slot, which failed
        // validation and aborted Binaryen during optimization).
        let src = "import math\ndef f() -> int:\n    pi = math.pi\n    tau = math.tau\n    if tau > pi:\n        return 1\n    return 0\n";
        assert_eq!(call_i32(src, "f"), 1);
    }

    #[test]
    fn unannotated_function_returning_float() {
        // An unannotated function that returns a float gets an f64 result type
        // inferred from its body, so a caller sees an f64 (previously the i32
        // result signature mismatched the f64 return value).
        let src = "import math\ndef get_pi():\n    pi = math.pi\n    return pi\ndef f() -> int:\n    if get_pi() > 3.0:\n        return 1\n    return 0\n";
        assert_eq!(call_i32(src, "f"), 1);
    }

    #[test]
    fn min_and_max_reduce() {
        // The reduction previously left the if/else stack unbalanced.
        let src = "def lo() -> int:\n    return min(5, 3, 8, 1, 9)\ndef hi() -> int:\n    return max(5, 3, 8, 1, 9)\n";
        assert_eq!(call_i32(src, "lo"), 1);
        assert_eq!(call_i32(src, "hi"), 9);
    }

    #[test]
    fn os_path_submodule_attribute_is_valid() {
        // os.path.<attr> previously fell through to a stray drop that
        // underflowed the stack; it now resolves the submodule attribute.
        instantiate("import os\ndef f():\n    print(\"sep:\", os.path.sep)\n");
    }

    #[test]
    fn string_equality_compares_contents() {
        // `==`/`!=` on str/bytes previously fell through to the integer path,
        // which compared only the top word (the right operand's length) and
        // stranded the left pair, so even equal strings compared unequal (#90).
        let eq =
            "def f() -> int:\n    a = \"hello\"\n    b = \"hello\"\n    if a == b:\n        return 1\n    return 0\n";
        assert_eq!(call_i32(eq, "f"), 1);
        let ne_same =
            "def f() -> int:\n    a = \"hello\"\n    b = \"hello\"\n    if a != b:\n        return 1\n    return 0\n";
        assert_eq!(call_i32(ne_same, "f"), 0);
        let neq =
            "def f() -> int:\n    a = \"hello\"\n    b = \"world\"\n    if a == b:\n        return 1\n    return 0\n";
        assert_eq!(call_i32(neq, "f"), 0);
        // Different lengths short-circuit before the byte loop.
        let diff_len =
            "def f() -> int:\n    a = \"hi\"\n    b = \"hello\"\n    if a == b:\n        return 1\n    return 0\n";
        assert_eq!(call_i32(diff_len, "f"), 0);
        // A runtime-built operand (concatenation) has a distinct offset, so a
        // content compare — not an offset compare — is required.
        let runtime =
            "def f() -> int:\n    a = \"foo\" + \"bar\"\n    b = \"foobar\"\n    if a == b:\n        return 1\n    return 0\n";
        assert_eq!(call_i32(runtime, "f"), 1);
        let bytes_eq =
            "def f() -> int:\n    a = b\"abc\"\n    b = b\"abc\"\n    if a == b:\n        return 1\n    return 0\n";
        assert_eq!(call_i32(bytes_eq, "f"), 1);
    }

    #[test]
    fn dict_string_value_read_back_has_length() {
        // Reading a str/bytes value out of a dict dropped its length (#91): the
        // matched value word is the blob offset, so rebuild (offset, length)
        // from the length prefix like list/tuple read-back does.
        let src =
            "def f() -> int:\n    d = {1: \"value\", 2: \"xy\"}\n    w = d[1]\n    return len(w)\n";
        assert_eq!(call_i32(src, "f"), 5);
        let other =
            "def f() -> int:\n    d = {1: \"value\", 2: \"xy\"}\n    w = d[2]\n    return len(w)\n";
        assert_eq!(call_i32(other, "f"), 2);
    }

    #[test]
    fn string_slice_into_collection_has_length() {
        // A slice's offset points into the source blob, not past a fresh length
        // prefix, so collection read-back (load(offset - 4)) read the source's
        // length. Slicing now allocates a prefixed blob (#92).
        let into_list =
            "def f() -> int:\n    s = \"hello world\"\n    part = s[0:5]\n    xs = [part]\n    w = xs[0]\n    return len(w)\n";
        assert_eq!(call_i32(into_list, "f"), 5);
        let bytes_into_tuple =
            "def f() -> int:\n    b = b\"hello world\"\n    part = b[6:11]\n    t = (part,)\n    w = t[0]\n    return len(w)\n";
        assert_eq!(call_i32(bytes_into_tuple, "f"), 5);
        // The relocated blob still holds the right bytes (bytes indexing
        // returns the byte value; string indexing would return a char offset).
        let content =
            "def f() -> int:\n    b = b\"hello world\"\n    part = b[6:11]\n    return part[0]\n";
        assert_eq!(call_i32(content, "f"), 119); // 'w'
    }
}