dixscript 1.0.0

Config, code, and encryption in one file — a data interchange format with compile-time functions, AES-256/ChaCha20 built-in, and cross-platform FFI
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
//! Recursive import resolution with cycle detection and cloud download.


use std::collections::{HashMap, HashSet};
use std::path::Path;
// Only referenced from the native variant of read_local_file_sync below —
// gating it avoids an unused-import warning on wasm32 (clippy CI runs with
// -D warnings, turning that into a hard failure). Same reasoning as the
// CloudProviderFactory gate just below.
#[cfg(not(target_arch = "wasm32"))]
use std::fs;
use crate::Compiler::AST::*;
use crate::Compiler::Core::{
    ConfigSectionHandler,
    DebugMode,
    ErrorHandlingStrategy,
    GeneralAstEnhancer,
    GeneralParser,
    GeneralSemanticAnalyzer,
    OperationalSettings,
};
use crate::Compiler::Core::Tokenizer::{Tokenizer, split_config_tokens};
use crate::Compiler::Utilities::{FunctionSignature, ParameterInfo, QuickFunctionInfo, SymbolTable};
use crate::Compiler::Utilities::symbol_table::ImportedNamespace;
use crate::ErrorManager::{DebugConfig, ErrorManager, ImportsResolutionErrorType};
use super::{HashVerifier, CloudFileCache};
// Only referenced from the native + cloud-import variant of
// download_cloud_file_sync below — gating the import too avoids an
// unused-import warning (clippy CI runs with -D warnings) on wasm32 *and*
// on any native build with cloud-import disabled, since CloudProviderFactory
// itself is only re-exported from ImportsResolution/mod.rs under that same
// combined condition.
#[cfg(all(not(target_arch = "wasm32"), feature = "cloud-import"))]
use super::CloudProviderFactory;

pub struct ImportsResolver<'a> {
    symbol_table:         &'a mut SymbolTable,
    operational_settings: &'a OperationalSettings,
    error_manager:        ErrorManager,
    debug_config:         DebugConfig,
    cloud_cache:          CloudFileCache,
    visiting:             HashSet<String>,
    visited:              HashSet<String>,
    import_stack:         Vec<String>,
}

impl<'a> ImportsResolver<'a> {
    pub fn new(
        symbol_table:         &'a mut SymbolTable,
        operational_settings: &'a OperationalSettings,
    ) -> Self {
        Self::new_with_error_manager(
            symbol_table,
            operational_settings,
            ErrorManager::get_shared_instance(),
        )
    }

    pub fn new_with_error_manager(
        symbol_table:         &'a mut SymbolTable,
        operational_settings: &'a OperationalSettings,
        error_manager:        ErrorManager,
    ) -> Self {
        let debug_config = DebugConfig::from_debug_mode(error_manager.get_debug_mode());
        let cloud_cache  = CloudFileCache::new(error_manager.clone());

        ImportsResolver {
            symbol_table,
            operational_settings,
            error_manager,
            debug_config,
            cloud_cache,
            visiting:     HashSet::new(),
            visited:      HashSet::new(),
            import_stack: Vec::new(),
        }
    }

    // ── Primary entry point ───────────────────────────────────────────────────

    pub fn resolve_from_imports_section(
        &mut self,
        imports_section: &ImportsSection,
        base_dir:        &str,
    ) -> bool {
        if imports_section.imports.is_empty() {
            if self.debug_config.is_enabled {
                self.error_manager.log_debug("[ImportsResolver] No imports to resolve");
            }
            return true;
        }

        self.error_manager.log_info(&format!(
            "[ImportsResolver] Resolving {} top-level import(s) from '{}'",
            imports_section.imports.len(),
            base_dir,
        ));

        self.visiting.clear();
        self.visited.clear();
        self.import_stack.clear();

        let mut success = true;

        for import in &imports_section.imports {
            let resolved_path = if import.is_cloud_import {
                import.path.clone()
            } else {
                Self::resolve_path(base_dir, &import.path)
            };

            if self.debug_config.is_enabled {
                self.error_manager.log_debug(&format!(
                    "[ImportsResolver] Loading '{}' from '{}'",
                    import.alias, resolved_path,
                ));
            }

            let raw_ast = match self.read_and_parse_raw(import, &resolved_path) {
                Ok(a)  => a,
                Err(e) => {
                    self.error_manager.log_error(&format!(
                        "[ImportsResolver] Failed to load '{}': {}",
                        import.alias, e,
                    ));
                    if self.operational_settings.error_handling_strategy
                        == ErrorHandlingStrategy::Halt
                    {
                        return false;
                    }
                    success = false;
                    continue;
                }
            };

            if !self.resolve_import_recursive(&import.alias, &raw_ast, &resolved_path) {
                self.error_manager.log_error(&format!(
                    "[ImportsResolver] Failed to resolve '{}'",
                    import.alias,
                ));
                if self.operational_settings.error_handling_strategy
                    == ErrorHandlingStrategy::Halt
                {
                    return false;
                }
                success = false;
            }
        }

        let error_count = self.error_manager.get_imports_resolution_errors().len();
        if error_count > 0 {
            self.error_manager.log_warning(&format!(
                "[ImportsResolver] Resolution completed with {} error(s)",
                error_count,
            ));
            if self.operational_settings.error_handling_strategy == ErrorHandlingStrategy::Halt {
                return false;
            }
        } else if self.debug_config.is_enabled {
            self.error_manager
                .log_info("[ImportsResolver] All top-level imports resolved successfully");
        }

        success
    }

    // ── Legacy entry point ────────────────────────────────────────────────────

    pub fn resolve_imports(
        &mut self,
        parsed_imports: &HashMap<String, (String, DixScript)>,
    ) -> bool {
        if parsed_imports.is_empty() {
            if self.debug_config.is_enabled {
                self.error_manager.log_debug("[ImportsResolver] No pre-parsed imports to resolve");
            }
            return true;
        }

        self.error_manager.log_info(&format!(
            "[ImportsResolver] Resolving {} pre-parsed import(s)",
            parsed_imports.len()
        ));

        if self.debug_config.is_enabled {
            let stats = self.cloud_cache.get_statistics();
            self.error_manager.log_debug(&format!(
                "[ImportsResolver] Cache statistics: {}", stats
            ));
        }

        self.visiting.clear();
        self.visited.clear();
        self.import_stack.clear();

        let mut success = true;

        for (alias, (absolute_path, ast)) in parsed_imports {
            if self.debug_config.is_enabled {
                self.error_manager.log_debug(&format!(
                    "[ImportsResolver] Resolving import '{}' from '{}'",
                    alias, absolute_path
                ));
            }

            if !self.resolve_import_recursive(alias, ast, absolute_path) {
                self.error_manager.log_error(&format!(
                    "[ImportsResolver] Failed to resolve import '{}'",
                    alias
                ));
                if self.operational_settings.error_handling_strategy
                    == ErrorHandlingStrategy::Halt
                {
                    return false;
                }
                success = false;
            }
        }

        let error_count = self.error_manager.get_imports_resolution_errors().len();
        if error_count > 0 {
            self.error_manager.log_warning(&format!(
                "[ImportsResolver] Resolution completed with {} errors",
                error_count
            ));
            if self.operational_settings.error_handling_strategy == ErrorHandlingStrategy::Halt {
                return false;
            }
        } else {
            self.error_manager
                .log_info("[ImportsResolver] Successfully resolved imports");
        }

        success
    }

    // ── Recursive resolution ──────────────────────────────────────────────────

    fn resolve_import_recursive(
        &mut self,
        alias:         &str,
        raw_ast:       &DixScript,
        absolute_path: &str,
    ) -> bool {
        let normalized_path = if Self::is_cloud_url(absolute_path) {
            Self::strip_query_parameters(absolute_path)
        } else {
            match std::fs::canonicalize(absolute_path) {
                Ok(p)  => p.to_string_lossy().to_string(),
                Err(_) => absolute_path.to_string(),
            }
        };

        if self.visiting.contains(&normalized_path) {
            let cycle_path  = self.build_cycle_path(&normalized_path);
            let cycle_chain = self.build_cycle_chain_list(&normalized_path);

            self.error_manager.add_imports_resolution_error(
                ImportsResolutionErrorType::CircularDependency,
                format!("Circular dependency detected: {}", cycle_path),
                alias.to_string(),
                Some(absolute_path.to_string()),
                Some(normalized_path.clone()),
                Some(cycle_chain),
                0, 0, None,
            );
            return false;
        }

        if self.visited.contains(&normalized_path) {
            if self.debug_config.is_enabled {
                self.error_manager.log_debug(&format!(
                    "[ImportsResolver] Import '{}' already resolved, skipping",
                    alias
                ));
            }
            return true;
        }

        self.visiting.insert(normalized_path.clone());
        self.import_stack.push(normalized_path.clone());

        let result = self.resolve_import_inner(alias, raw_ast, &normalized_path);

        self.import_stack.pop();
        self.visiting.remove(&normalized_path);
        self.visited.insert(normalized_path);

        result
    }

    fn resolve_import_inner(
        &mut self,
        alias:           &str,
        raw_ast:         &DixScript,
        normalized_path: &str,
    ) -> bool {
        let mut local_imports = HashMap::new();

        // ── Step 1: Resolve all transitive dependencies FIRST ─────────────────
        if let Some(ref imports_section) = raw_ast.imports {
            let nested_base_dir = if Self::is_cloud_url(normalized_path) {
                Self::get_cloud_url_directory(normalized_path)
            } else {
                Path::new(normalized_path)
                    .parent()
                    .map(|p| p.to_string_lossy().to_string())
                    .unwrap_or_else(|| ".".to_string())
            };

            let nested_imports: Vec<ImportDeclaration> = imports_section.imports.clone();

            for nested_import in &nested_imports {
                let nested_path = if nested_import.is_cloud_import {
                    nested_import.path.clone()
                } else {
                    Self::resolve_path(&nested_base_dir, &nested_import.path)
                };

                if self.visited.contains(&nested_path) {
                    if let Some(existing_ns) =
                        self.symbol_table.try_get_namespace(&nested_import.alias)
                    {
                        local_imports.insert(
                            nested_import.alias.clone(),
                            existing_ns.clone(),
                        );
                        continue;
                    } else {
                        self.error_manager.add_imports_resolution_error(
                            ImportsResolutionErrorType::GeneralError,
                            format!(
                                "Internal: namespace '{}' marked visited but absent from symbol table",
                                nested_import.alias
                            ),
                            nested_import.alias.clone(),
                            Some(nested_import.path.clone()),
                            Some(nested_path.clone()),
                            None,
                            0, 0, None,
                        );
                        return false;
                    }
                }

                let normalized_nested = if Self::is_cloud_url(&nested_path) {
                    Self::strip_query_parameters(&nested_path)
                } else {
                    match std::fs::canonicalize(&nested_path) {
                        Ok(p)  => p.to_string_lossy().to_string(),
                        Err(_) => nested_path.clone(),
                    }
                };

                if self.visiting.contains(&normalized_nested) {
                    let cycle_path  = self.build_cycle_path(&normalized_nested);
                    let cycle_chain = self.build_cycle_chain_list(&normalized_nested);
                    self.error_manager.add_imports_resolution_error(
                        ImportsResolutionErrorType::CircularDependency,
                        format!("Circular dependency detected: {}", cycle_path),
                        nested_import.alias.clone(),
                        Some(nested_import.path.clone()),
                        Some(normalized_nested.clone()),
                        Some(cycle_chain),
                        0, 0, None,
                    );
                    return false;
                }

                let nested_raw =
                    match self.read_and_parse_raw(nested_import, &nested_path) {
                        Ok(a)  => a,
                        Err(_) => return false,
                    };

                if !self.resolve_import_recursive(
                    &nested_import.alias,
                    &nested_raw,
                    &nested_path,
                ) {
                    return false;
                }

                if let Some(ns) =
                    self.symbol_table.try_get_namespace(&nested_import.alias)
                {
                    local_imports.insert(nested_import.alias.clone(), ns.clone());
                }
            }
        }

        // ── Step 2: Seed namespaces for enhancement ───────────────────────────
        let seed_namespaces: HashMap<String, ImportedNamespace> =
            if let Some(ref imports_section) = raw_ast.imports {
                imports_section
                    .imports
                    .iter()
                    .filter_map(|imp| {
                        self.symbol_table
                            .namespaces
                            .get(&imp.alias)
                            .map(|ns| (imp.alias.clone(), ns.clone()))
                    })
                    .collect()
            } else {
                HashMap::new()
            };

        if self.debug_config.is_enabled {
            self.error_manager.log_debug(&format!(
                "[ImportsResolver] Seeding '{}' enhancement with {} namespace(s): [{}]",
                alias,
                seed_namespaces.len(),
                seed_namespaces.keys().cloned().collect::<Vec<_>>().join(", ")
            ));
        }

        let enhanced_ast =
            match self.analyze_and_enhance(raw_ast, normalized_path, alias, &seed_namespaces) {
                Ok(a)  => a,
                Err(_) => return false,
            };

        // ── Step 3: Extract symbols ───────────────────────────────────────────
        let functions =
            Self::extract_global_functions(enhanced_ast.quick_functions.as_ref(), alias);
        let enums = Self::extract_enums(enhanced_ast.enums.as_ref());

        if self.debug_config.is_enabled {
            if let Some(ref qf) = enhanced_ast.quick_functions {
                let skipped = qf.functions.len().saturating_sub(functions.len());
                self.error_manager.log_debug(&format!(
                    "[ImportsResolver] Extracted {}/{} functions from '{}' ({} scoped, not exported)",
                    functions.len(),
                    qf.functions.len(),
                    alias,
                    skipped
                ));
            }
        }

        self.symbol_table.register_namespace(
            alias.to_string(),
            normalized_path.to_string(),
            functions.clone(),
            enums.clone(),
            local_imports.clone(),
        );

        if self.debug_config.is_enabled {
            self.error_manager.log_debug(&format!(
                "[ImportsResolver] Registered namespace '{}' with {} functions, {} enums, {} local imports",
                alias,
                functions.len(),
                enums.len(),
                local_imports.len()
            ));
        }

        true
    }

    // ── Phase 1: Read and parse raw AST (Approach B) ──────────────────────────
    //
    // Tokenizes the full content first, splits @CONFIG tokens, processes config
    // via process_config_tokens (accurate positions, no source stripping), then
    // passes rest_tokens to GeneralParser. This is identical to the main loader
    // pipeline and gives imported files the same Approach B benefits.

    fn read_and_parse_raw(
        &mut self,
        import:        &ImportDeclaration,
        resolved_path: &str,
    ) -> Result<DixScript, String> {
        let content = self.read_import_content(import, resolved_path)?;

        if let Some(ref verify_hash) = import.verify_hash {
            HashVerifier::verify_hash(&content, verify_hash, &import.alias, resolved_path)
                .map_err(|e| {
                    self.error_manager.add_imports_resolution_error(
                        ImportsResolutionErrorType::HashVerificationFailed,
                        e.message.clone(),
                        import.alias.clone(),
                        Some(import.path.clone()),
                        Some(resolved_path.to_string()),
                        None, 0, 0, None,
                    );
                    format!("Hash verification failed: {}", e)
                })?;

            if self.debug_config.is_enabled {
                self.error_manager.log_debug(&format!(
                    "[ImportsResolver] Hash verification passed for '{}'",
                    import.alias
                ));
            }
        }

        if content.trim().is_empty() {
            self.error_manager.log_warning(&format!(
                "[ImportsResolver] Imported file '{}' is empty",
                resolved_path
            ));
            return Ok(DixScript::new());
        }

        // ── Approach B: tokenize full content ─────────────────────────────────
        let mut import_settings = self.operational_settings.clone();
        import_settings.source_file_path = Some(resolved_path.to_string());
        // Safe defaults for the tokenizer pass — real settings come from config.
        let tokenizer_settings = OperationalSettings {
            error_handling_strategy: import_settings.error_handling_strategy,
            debug_mode:              DebugMode::Off,
            source_file_path:        Some(resolved_path.to_string()),
            ..OperationalSettings::default()
        };

        let tokenizer = Tokenizer::new_with_error_manager(
            &content,
            &tokenizer_settings,
            self.error_manager.clone(),
        );
        let token_result = tokenizer.tokenize();

        if token_result.tokens.is_empty() {
            self.error_manager.add_imports_resolution_error(
                ImportsResolutionErrorType::ParseError,
                "Tokenization produced no tokens".to_string(),
                import.alias.clone(),
                Some(import.path.clone()),
                Some(resolved_path.to_string()),
                None, 0, 0, None,
            );
            return Err("Tokenization produced no tokens".to_string());
        }

        // ── Split @CONFIG from the rest ───────────────────────────────────────
        let split = split_config_tokens(token_result.tokens);

        let config_result = {
            let mut handler = ConfigSectionHandler::new_with_error_manager(
                None,
                self.error_manager.clone(),
            );
            handler.process_config_tokens(&split.config_tokens)
        };

        // Update import settings with real operational settings from config.
        import_settings = config_result.operational_settings.clone();
        import_settings.source_file_path = Some(resolved_path.to_string());
        // Keep skip_imports_resolution from caller to prevent nested resolver
        // spinning up with no knowledge of the outer visiting set.
        import_settings.skip_imports_resolution =
            self.operational_settings.skip_imports_resolution;

        if self.debug_config.is_enabled {
            self.error_manager.log_debug(&format!(
                "[ImportsResolver] Parsing imported file '{}'",
                import.alias
            ));
        }

        // ── Parse rest_tokens ─────────────────────────────────────────────────
        let general_parser = GeneralParser::new(
            split.rest_tokens,
            &config_result.config_section,
            &import_settings,
        )
        .map_err(|e| {
            self.error_manager.add_imports_resolution_error(
                ImportsResolutionErrorType::ParseError,
                format!("Failed to create parser: {}", e),
                import.alias.clone(),
                Some(import.path.clone()),
                Some(resolved_path.to_string()),
                None, 0, 0, None,
            );
            format!("Failed to create parser: {}", e)
        })?;

        let mut ast = general_parser.parse().map_err(|e| {
            let parse_errors = self.error_manager.get_parse_errors();
            if let Some(first) = parse_errors.first() {
                self.error_manager.add_imports_resolution_error(
                    ImportsResolutionErrorType::ParseError,
                    format!("Parse errors in imported file: {}", first.message),
                    import.alias.clone(),
                    Some(import.path.clone()),
                    Some(resolved_path.to_string()),
                    None,
                    first.line as i32,
                    first.column as i32,
                    None,
                );
            }
            format!("Parse errors in imported file: {}", e)
        })?;

        // Attach the already-parsed ConfigSection — GeneralParser doesn't
        // parse @CONFIG itself, it receives it as a pre-built argument.
        ast.config = Some(config_result.config_section);

        Ok(ast)
    }

    // ── Phase 2: Semantic analysis and AST enhancement ────────────────────────

    fn analyze_and_enhance(
        &mut self,
        raw_ast:         &DixScript,
        resolved_path:   &str,
        alias:           &str,
        seed_namespaces: &HashMap<String, ImportedNamespace>,
    ) -> Result<DixScript, String> {
        let mut import_settings = self.operational_settings.clone();
        import_settings.source_file_path        = Some(resolved_path.to_string());
        // CRITICAL: prevent a nested ImportsResolver from being created inside
        // GeneralSemanticAnalyzer, which has no knowledge of our visiting set.
        import_settings.skip_imports_resolution = true;

        if self.debug_config.is_enabled {
            self.error_manager.log_debug(&format!(
                "[ImportsResolver] Running semantic analysis on '{}' with {} seeded namespace(s)",
                alias,
                seed_namespaces.len()
            ));
        }

        let semantic_analyzer = GeneralSemanticAnalyzer::new_with_seed_namespaces(
            raw_ast,
            &import_settings,
            self.error_manager.clone(),
            seed_namespaces,
        );
        let semantic_result = semantic_analyzer.analyze();

        if !semantic_result.is_success {
            let summary = semantic_result
                .errors
                .first()
                .map(|e| format!("{}: {}", e.error_type, e.message))
                .unwrap_or_else(|| "Unknown semantic error".to_string());

            self.error_manager.add_imports_resolution_error(
                ImportsResolutionErrorType::ParseError,
                format!(
                    "Semantic analysis failed for '{}': {} (total: {} errors)",
                    alias,
                    summary,
                    semantic_result.errors.len()
                ),
                alias.to_string(),
                Some(resolved_path.to_string()),
                Some(resolved_path.to_string()),
                None, 0, 0, None,
            );
            return Err(format!("Semantic analysis failed for '{}'", alias));
        }

        if self.debug_config.is_enabled {
            self.error_manager.log_debug(&format!(
                "[ImportsResolver] Running AST enhancement on '{}'",
                alias
            ));
        }

        let ast_enhancer = GeneralAstEnhancer::new(&import_settings);
        let enhancement_result = ast_enhancer.enhance(raw_ast, Some(&semantic_result));

        if !enhancement_result.is_success {
            self.error_manager.add_imports_resolution_error(
                ImportsResolutionErrorType::ParseError,
                format!(
                    "AST enhancement failed for '{}': {} errors, {} warnings",
                    alias,
                    enhancement_result.errors.len(),
                    enhancement_result.warnings.len()
                ),
                alias.to_string(),
                Some(resolved_path.to_string()),
                Some(resolved_path.to_string()),
                None, 0, 0, None,
            );
            return Err(format!("AST enhancement failed for '{}'", alias));
        }

        let enhanced_ast = enhancement_result.enhanced_ast;

        if self.debug_config.is_enabled {
            self.error_manager.log_debug(&format!(
                "[ImportsResolver] Processed '{}' ({} functions)",
                alias,
                enhanced_ast
                    .quick_functions
                    .as_ref()
                    .map(|qf| qf.functions.len())
                    .unwrap_or(0)
            ));
        }

        Ok(enhanced_ast)
    }

    fn read_import_content(
        &mut self,
        import:        &ImportDeclaration,
        resolved_path: &str,
    ) -> Result<String, String> {
        if import.is_cloud_import {
            if self.debug_config.is_enabled {
                self.error_manager.log_debug(&format!(
                    "[ImportsResolver] Downloading cloud import: {}",
                    import.path
                ));
            }
            self.download_cloud_file_sync(&import.path, &import.alias)
        } else {
            if self.debug_config.is_enabled {
                self.error_manager.log_debug(&format!(
                    "[ImportsResolver] Reading local import: {}",
                    resolved_path
                ));
            }
            self.read_local_file_sync(resolved_path, import)
        }
    }

    /// Native variant: a real filesystem is available, so this is a
    /// straightforward read.
    #[cfg(not(target_arch = "wasm32"))]
    fn read_local_file_sync(
        &mut self,
        resolved_path: &str,
        import:        &ImportDeclaration,
    ) -> Result<String, String> {
        fs::read_to_string(resolved_path).map_err(|e| {
            self.error_manager.add_imports_resolution_error(
                ImportsResolutionErrorType::FileNotFound,
                format!("Failed to read file: {}", e),
                import.alias.clone(),
                Some(import.path.clone()),
                Some(resolved_path.to_string()),
                None, 0, 0, None,
            );
            format!("Failed to read file: {}", e)
        })
    }

    /// wasm32 variant: `std::fs` compiles here but every call always
    /// returns an error — there's no real filesystem on this target
    /// regardless of whether the host is a browser or Node.js, since
    /// `std::fs` doesn't special-case the host at compile time. Rather
    /// than surface whatever generic OS error `fs::read_to_string` would
    /// produce, this returns the same kind of clear, actionable message
    /// the cloud-import wasm32 path already gives: resolve the content on
    /// the JS side and hand it to `loadStr()` instead. Matches
    /// `download_cloud_file_sync`'s wasm32 variant in spirit and shape.
    #[cfg(target_arch = "wasm32")]
    fn read_local_file_sync(
        &mut self,
        resolved_path: &str,
        import:        &ImportDeclaration,
    ) -> Result<String, String> {
        let message = format!(
            "Local file imports are not supported when DixScript is compiled \
             to wasm32 — there is no real filesystem on this target. Read the \
             file yourself (e.g. JS fetch()/File API in a browser, or Node's \
             fs module) and either inline its content before calling loadStr(), \
             or pass it in directly instead of an @IMPORTS path. Path: {}",
            resolved_path
        );
        self.error_manager.add_imports_resolution_error(
            ImportsResolutionErrorType::FileNotFound,
            message.clone(),
            import.alias.clone(),
            Some(import.path.clone()),
            Some(resolved_path.to_string()),
            None, 0, 0, None,
        );
        Err(message)
    }

    #[cfg(all(not(target_arch = "wasm32"), feature = "cloud-import"))]
    fn download_cloud_file_sync(
        &mut self,
        cloud_url: &str,
        alias:     &str,
    ) -> Result<String, String> {
        let url_for_cache = Self::strip_query_parameters(cloud_url);

        if self.cloud_cache.is_cached(&url_for_cache) {
            if let Some(content) = self.cloud_cache.get_cached_content(&url_for_cache) {
                return Ok(content);
            }
            if self.debug_config.is_enabled {
                self.error_manager.log_debug(
                    "[ImportsResolver] Cache read failed, downloading fresh copy",
                );
            }
        }

        let provider =
            CloudProviderFactory::get_provider(cloud_url, &self.error_manager)
                .inspect_err(|e| {
                    self.error_manager.add_imports_resolution_error(
                        ImportsResolutionErrorType::CloudImportNotSupported,
                        e.clone(),
                        alias.to_string(),
                        Some(cloud_url.to_string()),
                        Some(cloud_url.to_string()),
                        None, 0, 0, None,
                    );
                })?;

        let content = tokio::runtime::Runtime::new()
            .map_err(|e| format!("Failed to create async runtime: {}", e))?
            .block_on(provider.download_file_async(cloud_url))
            .map_err(|e| {
                self.error_manager.add_imports_resolution_error(
                    ImportsResolutionErrorType::FileNotFound,
                    format!("Cloud download failed: {}", e),
                    alias.to_string(),
                    Some(cloud_url.to_string()),
                    Some(cloud_url.to_string()),
                    None, 0, 0, None,
                );
                format!("Cloud download failed: {}", e)
            })?;

        self.cloud_cache.cache_file(&url_for_cache, &content);
        Ok(content)
    }

    /// wasm32 variant: no tokio runtime can be constructed on this target
    /// (no real OS threads/scheduler for it to run on) and no HTTP
    /// provider exists either (see CloudProviderFactory's wasm32 variant)
    /// — so this returns the same kind of clear, actionable error
    /// `CloudProviderFactory::get_provider` would have, without ever
    /// touching tokio or reqwest at all. `cloud_cache`'s in-memory lookup
    /// is still consulted first for parity with the native path, even
    /// though nothing can ever populate it via a cloud download on this
    /// target — it costs nothing and keeps the two implementations
    /// structurally aligned.
    #[cfg(target_arch = "wasm32")]
    fn download_cloud_file_sync(
        &mut self,
        cloud_url: &str,
        alias:     &str,
    ) -> Result<String, String> {
        let url_for_cache = Self::strip_query_parameters(cloud_url);
        if self.cloud_cache.is_cached(&url_for_cache) {
            if let Some(content) = self.cloud_cache.get_cached_content(&url_for_cache) {
                return Ok(content);
            }
        }

        let message = format!(
            "Cloud (http/https) imports are not supported when DixScript is \
             compiled to wasm32 — fetch the content yourself (e.g. JS fetch() \
             in a browser, or Node's fs/http) and load it with loadStr() or \
             mergeSources() instead. URL: {}",
            cloud_url
        );
        self.error_manager.add_imports_resolution_error(
            ImportsResolutionErrorType::CloudImportNotSupported,
            message.clone(),
            alias.to_string(),
            Some(cloud_url.to_string()),
            Some(cloud_url.to_string()),
            None, 0, 0, None,
        );
        Err(message)
    }

    /// Native, but built without the `cloud-import` feature: the crate
    /// compiles fine (this whole function only exists in this cfg
    /// combination), but there's no `reqwest`/`tokio` in the dependency
    /// graph to actually download anything with. `cloud_cache` is still a
    /// plain data structure regardless of this feature (it's not gated by
    /// `cloud-import` at all), so a previously-cached entry — from a build
    /// that did have the feature on — still resolves here without error.
    #[cfg(all(not(target_arch = "wasm32"), not(feature = "cloud-import")))]
    fn download_cloud_file_sync(
        &mut self,
        cloud_url: &str,
        alias:     &str,
    ) -> Result<String, String> {
        let url_for_cache = Self::strip_query_parameters(cloud_url);
        if self.cloud_cache.is_cached(&url_for_cache) {
            if let Some(content) = self.cloud_cache.get_cached_content(&url_for_cache) {
                return Ok(content);
            }
        }

        let message = format!(
            "This file has a cloud (http/https) @IMPORTS reference, but this \
             build of dixscript was compiled without the 'cloud-import' \
             feature. Rebuild with `--features cloud-import` (or default \
             features) to resolve it. URL: {}",
            cloud_url
        );
        self.error_manager.add_imports_resolution_error(
            ImportsResolutionErrorType::CloudImportNotSupported,
            message.clone(),
            alias.to_string(),
            Some(cloud_url.to_string()),
            Some(cloud_url.to_string()),
            None, 0, 0, None,
        );
        Err(message)
    }

    // ── Symbol extraction ─────────────────────────────────────────────────────

    fn extract_global_functions(
        section:          Option<&QuickFuncsSection>,
        _namespace_name:  &str,
    ) -> HashMap<String, QuickFunctionInfo> {
        let mut functions = HashMap::new();

        let section = match section {
            Some(s) => s,
            None    => return functions,
        };

        for func in &section.functions {
            let is_global = match &func.scope_list {
                None => true,
                Some(scopes)
                    if scopes.len() == 1
                        && scopes[0].eq_ignore_ascii_case("global") => true,
                _ => false,
            };

            if !is_global { continue; }

            let parameters: Vec<ParameterInfo> = func
                .parameters
                .iter()
                .map(|p| ParameterInfo {
                    name:              p.name.clone(),
                    param_type:        p.data_type,
                    has_default_value: p.default_value.is_some(),
                    default_value:     p.default_value.clone(),
                })
                .collect();

            let signature = FunctionSignature {
                name:        func.name.clone(),
                return_type: func.return_type,
                parameters,
                scopes:      func.scope_list
                    .clone()
                    .unwrap_or_else(|| vec!["global".to_string()]),
                line:        func.position.line   as i32,
                column:      func.position.column as i32,
            };

            functions.insert(
                func.name.clone(),
                QuickFunctionInfo { signature, ast: func.clone() },
            );
        }

        functions
    }

    fn extract_enums(
        section: Option<&EnumsSection>,
    ) -> HashMap<String, HashMap<String, i32>> {
        let mut enums = HashMap::new();

        let section = match section {
            Some(s) => s,
            None    => return enums,
        };

        for enum_decl in &section.enums {
            let mut field_map   = HashMap::new();
            let mut auto_value  = 0i32;

            for field in &enum_decl.fields {
                if let Some(value) = field.value {
                    field_map.insert(field.name.clone(), value);
                    auto_value = value + 1;
                } else {
                    field_map.insert(field.name.clone(), auto_value);
                    auto_value += 1;
                }
            }

            enums.insert(enum_decl.name.clone(), field_map);
        }

        enums
    }

    // ── Utility helpers ───────────────────────────────────────────────────────

    #[inline]
    fn is_cloud_url(path: &str) -> bool {
        path.starts_with("http://") || path.starts_with("https://")
    }

    #[inline]
    fn strip_query_parameters(url: &str) -> String {
        match url.find('?') {
            Some(idx) => url[..idx].to_string(),
            None      => url.to_string(),
        }
    }

    fn get_cloud_url_directory(cloud_url: &str) -> String {
        let without_query = Self::strip_query_parameters(cloud_url);
        match without_query.rfind('/') {
            Some(idx) => without_query[..=idx].to_string(),
            None      => without_query,
        }
    }

    fn resolve_path(base_directory: &str, relative_path: &str) -> String {
        Path::new(base_directory)
            .join(relative_path)
            .to_string_lossy()
            .to_string()
    }

    fn extract_readable_path(path: &str) -> String {
        if Self::is_cloud_url(path) {
            path.split("://")
                .nth(1)
                .and_then(|s| s.split('/').next())
                .unwrap_or(path)
                .to_string()
        } else {
            Path::new(path)
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or(path)
                .to_string()
        }
    }

    fn build_cycle_path(&self, cycle_target: &str) -> String {
        let mut chain: Vec<String> = self
            .import_stack
            .iter()
            .map(|p| Self::extract_readable_path(p))
            .collect();
        chain.push(Self::extract_readable_path(cycle_target));
        chain.join(" -> ")
    }

    fn build_cycle_chain_list(&self, cycle_target: &str) -> Vec<String> {
        let mut chain: Vec<String> = self
            .import_stack
            .iter()
            .map(|p| Self::extract_readable_path(p))
            .collect();
        chain.push(Self::extract_readable_path(cycle_target));
        chain
    }

    pub fn get_statistics(&self) -> ImportResolutionStats {
        let total_functions: usize = self
            .symbol_table
            .namespaces
            .values()
            .map(|ns| ns.functions.len())
            .sum();

        let total_enums: usize = self
            .symbol_table
            .namespaces
            .values()
            .map(|ns| ns.enums.len())
            .sum();

        let total_local_imports: usize = self
            .symbol_table
            .namespaces
            .values()
            .map(|ns| ns.local_imports.len())
            .sum();

        ImportResolutionStats {
            total_namespaces:         self.symbol_table.namespaces.len(),
            total_functions_imported: total_functions,
            total_enums_imported:     total_enums,
            total_nested_imports:     total_local_imports,
            files_visited:            self.visited.len(),
        }
    }
}

#[derive(Debug, Clone)]
pub struct ImportResolutionStats {
    pub total_namespaces:         usize,
    pub total_functions_imported: usize,
    pub total_enums_imported:     usize,
    pub total_nested_imports:     usize,
    pub files_visited:            usize,
}

impl std::fmt::Display for ImportResolutionStats {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Namespaces: {}, Functions: {}, Enums: {}, Nested: {}, Files: {}",
            self.total_namespaces,
            self.total_functions_imported,
            self.total_enums_imported,
            self.total_nested_imports,
            self.files_visited
        )
    }
        }