dol 0.8.1

DOL (Design Ontology Language) - A declarative specification language for ontology-first development
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
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
//! Semantic validation for Metal DOL.
//!
//! This module provides validation rules that cannot be enforced during parsing,
//! such as exegesis requirements, naming conventions, reference resolution, and
//! type checking for DOL 2.0 expressions.
//!
//! # Example
//!
//! ```rust
//! use metadol::{parse_file, validate};
//!
//! let source = r#"
//! gene container.exists {
//!   container has identity
//! }
//!
//! exegesis {
//!   A container is the fundamental unit.
//! }
//! "#;
//!
//! let decl = parse_file(source).unwrap();
//! let result = validate(&decl);
//! assert!(result.is_valid());
//! ```
//!
//! # Type Checking
//!
//! For DOL 2.0 expressions, type validation can be enabled:
//!
//! ```rust
//! use metadol::{parse_file, validator::{validate_with_options, ValidationOptions}};
//!
//! let source = r#"
//! gene typed.example {
//!   example has property
//! }
//!
//! exegesis {
//!   A typed example gene.
//! }
//! "#;
//!
//! let decl = parse_file(source).unwrap();
//! let options = ValidationOptions { typecheck: true };
//! let result = validate_with_options(&decl, &options);
//! ```

use crate::ast::*;
use crate::error::{ValidationError, ValidationWarning};
use crate::typechecker::{Type, TypeChecker, TypeError};
use std::collections::HashSet;

/// The result of validating a declaration.
#[derive(Debug, Clone)]
pub struct ValidationResult {
    /// The declaration that was validated
    pub declaration_name: String,

    /// Whether validation passed
    pub valid: bool,

    /// Collected errors
    pub errors: Vec<ValidationError>,

    /// Collected warnings
    pub warnings: Vec<ValidationWarning>,
}

impl ValidationResult {
    /// Creates a new validation result.
    fn new(name: impl Into<String>) -> Self {
        Self {
            declaration_name: name.into(),
            valid: true,
            errors: Vec::new(),
            warnings: Vec::new(),
        }
    }

    /// Returns true if validation passed (no errors).
    pub fn is_valid(&self) -> bool {
        self.valid && self.errors.is_empty()
    }

    /// Returns true if there are any warnings.
    pub fn has_warnings(&self) -> bool {
        !self.warnings.is_empty()
    }

    /// Adds an error and marks validation as failed.
    fn add_error(&mut self, error: ValidationError) {
        self.valid = false;
        self.errors.push(error);
    }

    /// Adds a warning.
    fn add_warning(&mut self, warning: ValidationWarning) {
        self.warnings.push(warning);
    }

    /// Adds a type error converted to a validation error.
    fn add_type_error(&mut self, error: &TypeError, span: Span) {
        self.add_error(ValidationError::TypeError {
            message: error.message.clone(),
            expected: error.expected.as_ref().map(|t| t.to_string()),
            actual: error.actual.as_ref().map(|t| t.to_string()),
            span,
        });
    }
}

/// Options for validation.
#[derive(Debug, Clone, Default)]
pub struct ValidationOptions {
    /// Enable type checking for DOL 2.0 expressions.
    pub typecheck: bool,
}

/// Validates a declaration with options.
///
/// # Arguments
///
/// * `decl` - The declaration to validate
/// * `options` - Validation options
///
/// # Returns
///
/// A `ValidationResult` containing any errors or warnings.
pub fn validate_with_options(decl: &Declaration, options: &ValidationOptions) -> ValidationResult {
    let mut result = ValidationResult::new(decl.name());

    // Validate exegesis
    validate_exegesis(decl, &mut result);

    // Validate naming conventions
    validate_naming(decl, &mut result);

    // Validate statements
    validate_statements(decl, &mut result);

    // Type-specific validations
    match decl {
        Declaration::Gene(gene) => validate_gene(gene, &mut result),
        Declaration::Trait(trait_decl) => validate_trait(trait_decl, &mut result),
        Declaration::Constraint(constraint) => validate_constraint(constraint, &mut result),
        Declaration::System(system) => validate_system(system, &mut result),
        Declaration::Evolution(evolution) => validate_evolution(evolution, &mut result),
        Declaration::Function(_) => {} // Top-level functions don't need special validation yet
        Declaration::Const(_) | Declaration::SexVar(_) => {} // Constants and SexVars are validated by type checking
    }

    // DOL 2.0 Type checking (if enabled)
    if options.typecheck {
        validate_types(decl, &mut result);
    }

    result
}

/// Validates a declaration.
///
/// # Arguments
///
/// * `decl` - The declaration to validate
///
/// # Returns
///
/// A `ValidationResult` containing any errors or warnings.
///
/// Note: This does not include type checking by default.
/// Use [`validate_with_options`] with `typecheck: true` for DOL 2.0 type validation.
pub fn validate(decl: &Declaration) -> ValidationResult {
    validate_with_options(decl, &ValidationOptions::default())
}

/// Validates a complete DOL file including module, uses, and declarations.
///
/// This performs file-level validation including:
/// - Module declaration format
/// - Use declaration validation (visibility, source resolution)
/// - Declaration validation
/// - Visibility rules enforcement
///
/// # Arguments
///
/// * `file` - The parsed DOL file to validate
///
/// # Returns
///
/// A `FileValidationResult` containing any errors or warnings.
pub fn validate_file(file: &DolFile) -> FileValidationResult {
    validate_file_with_options(file, &ValidationOptions::default())
}

/// Validates a complete DOL file with options.
pub fn validate_file_with_options(
    file: &DolFile,
    options: &ValidationOptions,
) -> FileValidationResult {
    let mut result = FileValidationResult::new();

    // Validate module declaration
    if let Some(ref module) = file.module {
        validate_module_decl(module, &mut result);
    }

    // Validate use declarations
    validate_use_declarations(&file.uses, &mut result);

    // Validate each declaration
    for decl in &file.declarations {
        let decl_result = validate_with_options(decl, options);
        result.declaration_results.push(decl_result);
    }

    // Cross-reference validation: check that uses reference valid declarations
    validate_use_references(file, &mut result);

    result
}

/// Result of validating a complete DOL file.
#[derive(Debug, Clone)]
pub struct FileValidationResult {
    /// Module-level errors
    pub module_errors: Vec<ValidationError>,
    /// Module-level warnings
    pub module_warnings: Vec<ValidationWarning>,
    /// Validation results for each declaration
    pub declaration_results: Vec<ValidationResult>,
}

impl FileValidationResult {
    /// Creates a new file validation result.
    fn new() -> Self {
        Self {
            module_errors: Vec::new(),
            module_warnings: Vec::new(),
            declaration_results: Vec::new(),
        }
    }

    /// Returns true if the file is valid (no errors).
    pub fn is_valid(&self) -> bool {
        self.module_errors.is_empty() && self.declaration_results.iter().all(|r| r.is_valid())
    }

    /// Returns true if there are any warnings.
    pub fn has_warnings(&self) -> bool {
        !self.module_warnings.is_empty()
            || self.declaration_results.iter().any(|r| r.has_warnings())
    }

    /// Collects all errors from the file.
    pub fn all_errors(&self) -> Vec<&ValidationError> {
        let mut errors: Vec<&ValidationError> = self.module_errors.iter().collect();
        for result in &self.declaration_results {
            errors.extend(result.errors.iter());
        }
        errors
    }

    /// Collects all warnings from the file.
    pub fn all_warnings(&self) -> Vec<&ValidationWarning> {
        let mut warnings: Vec<&ValidationWarning> = self.module_warnings.iter().collect();
        for result in &self.declaration_results {
            warnings.extend(result.warnings.iter());
        }
        warnings
    }

    fn add_error(&mut self, error: ValidationError) {
        self.module_errors.push(error);
    }

    fn add_warning(&mut self, warning: ValidationWarning) {
        self.module_warnings.push(warning);
    }
}

/// Validates a module declaration.
fn validate_module_decl(module: &ModuleDecl, result: &mut FileValidationResult) {
    // Module path must not be empty
    if module.path.is_empty() {
        result.add_error(ValidationError::InvalidIdentifier {
            name: "module".to_string(),
            reason: "module path cannot be empty".to_string(),
        });
        return;
    }

    // Validate each path segment
    for segment in &module.path {
        if segment.is_empty() {
            result.add_error(ValidationError::InvalidIdentifier {
                name: module.path.join("."),
                reason: "module path segment cannot be empty".to_string(),
            });
        } else if !segment.chars().next().unwrap_or('_').is_alphabetic() {
            result.add_error(ValidationError::InvalidIdentifier {
                name: segment.clone(),
                reason: "module path segment must start with a letter".to_string(),
            });
        }
    }

    // If version is present, validate it
    if let Some(ref version) = module.version {
        if version.major == 0 && version.minor == 0 && version.patch == 0 {
            result.add_warning(ValidationWarning::NamingConvention {
                name: module.path.join("."),
                suggestion:
                    "module version 0.0.0 is typically reserved; consider starting at 0.0.1"
                        .to_string(),
            });
        }
    }
}

/// Validates use declarations.
fn validate_use_declarations(uses: &[UseDecl], result: &mut FileValidationResult) {
    let mut seen_imports: HashSet<String> = HashSet::new();

    for use_decl in uses {
        // Check for duplicate imports
        let import_key = format_import_key(use_decl);
        if seen_imports.contains(&import_key) {
            result.add_warning(ValidationWarning::NamingConvention {
                name: import_key.clone(),
                suggestion: "duplicate import; this import was already declared".to_string(),
            });
        } else {
            seen_imports.insert(import_key);
        }

        // Validate import path
        validate_import_path(use_decl, result);

        // Validate visibility rules
        validate_use_visibility(use_decl, result);
    }
}

/// Formats an import key for duplicate detection.
fn format_import_key(use_decl: &UseDecl) -> String {
    let source_prefix = match &use_decl.source {
        ImportSource::Local => "local:".to_string(),
        ImportSource::Registry { org, package, .. } => format!("@{}/{}:", org, package),
        ImportSource::Git { url, .. } => format!("git:{}:", url),
        ImportSource::Https { url, .. } => format!("https:{}:", url),
    };
    format!("{}{}", source_prefix, use_decl.path.join("."))
}

/// Validates the import path in a use declaration.
fn validate_import_path(use_decl: &UseDecl, result: &mut FileValidationResult) {
    // Registry imports must have valid org/package
    if let ImportSource::Registry { org, package, .. } = &use_decl.source {
        if org.is_empty() {
            result.add_error(ValidationError::InvalidIdentifier {
                name: "registry import".to_string(),
                reason: "organization name cannot be empty".to_string(),
            });
        }
        if package.is_empty() {
            result.add_error(ValidationError::InvalidIdentifier {
                name: "registry import".to_string(),
                reason: "package name cannot be empty".to_string(),
            });
        }
    }

    // Git imports must have a URL
    if let ImportSource::Git { url, .. } = &use_decl.source {
        if url.is_empty() {
            result.add_error(ValidationError::InvalidIdentifier {
                name: "git import".to_string(),
                reason: "git URL cannot be empty".to_string(),
            });
        }
    }

    // HTTPS imports must have a valid URL
    if let ImportSource::Https { url, .. } = &use_decl.source {
        if url.is_empty() {
            result.add_error(ValidationError::InvalidIdentifier {
                name: "https import".to_string(),
                reason: "URL cannot be empty".to_string(),
            });
        }
        if !url.starts_with("https://") {
            result.add_error(ValidationError::InvalidIdentifier {
                name: url.clone(),
                reason: "HTTPS import URL must start with https://".to_string(),
            });
        }
    }

    // Validate named items if present
    if let UseItems::Named(items) = &use_decl.items {
        let mut seen_names: HashSet<String> = HashSet::new();
        for item in items {
            if seen_names.contains(&item.name) {
                result.add_warning(ValidationWarning::NamingConvention {
                    name: item.name.clone(),
                    suggestion: "duplicate item in import list".to_string(),
                });
            } else {
                seen_names.insert(item.name.clone());
            }
        }
    }
}

/// Validates visibility rules for use declarations.
fn validate_use_visibility(use_decl: &UseDecl, result: &mut FileValidationResult) {
    match use_decl.visibility {
        Visibility::Public => {
            // Public re-exports are allowed for all import types
        }
        Visibility::PubSpirit => {
            // pub(spirit) re-exports are only meaningful for local imports
            // For external imports, warn that pub(spirit) has limited utility
            if !matches!(use_decl.source, ImportSource::Local) {
                result.add_warning(ValidationWarning::NamingConvention {
                    name: format_import_key(use_decl),
                    suggestion: "pub(spirit) visibility on external imports has limited utility; consider using 'pub' instead".to_string(),
                });
            }
        }
        Visibility::PubParent => {
            // pub(parent) re-exports make an import visible only to the parent module
            // This is a valid use case for intermediate re-exports
        }
        Visibility::Private => {
            // Private imports are the default and always valid
        }
    }
}

/// Validates that use references are consistent within the file.
fn validate_use_references(file: &DolFile, _result: &mut FileValidationResult) {
    // Collect all declared names in this file
    let declared_names: HashSet<String> = file
        .declarations
        .iter()
        .map(|d| d.name().to_string())
        .collect();

    // Check that local re-exports actually exist
    for use_decl in &file.uses {
        // For local re-exports, the path should reference something
        // This is a soft check since the referenced module might be in another file
        if matches!(
            use_decl.visibility,
            Visibility::Public | Visibility::PubSpirit | Visibility::PubParent
        ) && matches!(use_decl.source, ImportSource::Local)
        {
            let full_path = use_decl.path.join(".");
            if !full_path.is_empty() && !declared_names.contains(&full_path) {
                // This is just informational - the import might reference another module
                // _result.add_warning(ValidationWarning::NamingConvention {
                //     name: full_path,
                //     suggestion: "re-exported item not found in this file".to_string(),
                // });
            }
        }
    }
}

/// Validates the exegesis block.
fn validate_exegesis(decl: &Declaration, result: &mut ValidationResult) {
    let exegesis = decl.exegesis();
    let span = decl.span();

    // Warn about very short exegesis
    let trimmed_len = exegesis.trim().len();
    if trimmed_len < 20 {
        result.add_warning(ValidationWarning::ShortExegesis {
            length: trimmed_len,
            span,
        });
    }
}

/// Validates naming conventions based on declaration type.
///
/// Conventions:
/// - Genes: PascalCase (Vec3, Container, MyceliumNode) OR dot notation (container.exists)
/// - Traits: PascalCase (Schedulable, Runnable) OR dot notation
/// - Systems: PascalCase (Scheduler, Ecosystem) OR dot notation
/// - Constraints: snake_case (valid_id, non_negative) OR dot notation
fn validate_naming(decl: &Declaration, result: &mut ValidationResult) {
    let name = decl.name();
    // Skip internal markers (e.g., _module_doc)
    if name.starts_with('_') {
        return;
    }
    // Skip empty names
    if name.is_empty() {
        return;
    }

    // If it contains a dot, it's qualified notation - validate each part
    if name.contains('.') {
        // Validate qualified identifier format
        if !is_valid_qualified_identifier(name) {
            result.add_error(ValidationError::InvalidIdentifier {
                name: name.to_string(),
                reason: "must be a valid qualified identifier (domain.property)".to_string(),
            });
        }
        return;
    }

    // Simple name - check based on declaration type
    match decl {
        // Types should be PascalCase
        Declaration::Gene(_) | Declaration::Trait(_) | Declaration::System(_) => {
            if !is_pascal_case(name) && !name.chars().next().is_some_and(|c| c.is_uppercase()) {
                result.add_warning(ValidationWarning::NamingConvention {
                    name: name.to_string(),
                    suggestion: format!(
                        "consider using PascalCase for type names: '{}'",
                        to_pascal_case(name)
                    ),
                });
            }
        }

        // Constraints can be snake_case or PascalCase
        Declaration::Constraint(_) => {
            // Constraints are flexible - no warning needed
        }

        // Evolution names follow "From > To" pattern - no validation needed
        Declaration::Evolution(_) => {}

        // Functions should be snake_case - no warning needed for now
        Declaration::Function(_) => {}

        // Constants should be SCREAMING_SNAKE_CASE
        Declaration::Const(_) => {}

        // SexVars should be SCREAMING_SNAKE_CASE like constants
        Declaration::SexVar(_) => {}
    }
}

/// Check if a name is PascalCase (starts with uppercase, no underscores between words)
fn is_pascal_case(s: &str) -> bool {
    if s.is_empty() {
        return false;
    }
    let first = s.chars().next().unwrap();
    // PascalCase starts with uppercase and doesn't have underscores
    first.is_uppercase() && !s.contains('_')
}

/// Convert to PascalCase
fn to_pascal_case(s: &str) -> String {
    s.split('_')
        .map(|word| {
            let mut chars = word.chars();
            match chars.next() {
                None => String::new(),
                Some(first) => first.to_uppercase().chain(chars).collect(),
            }
        })
        .collect()
}

/// Validates statements in a declaration.
fn validate_statements(decl: &Declaration, result: &mut ValidationResult) {
    let statements = match decl {
        Declaration::Gene(g) => &g.statements,
        Declaration::Trait(t) => &t.statements,
        Declaration::Constraint(c) => &c.statements,
        Declaration::System(s) => &s.statements,
        Declaration::Evolution(_)
        | Declaration::Function(_)
        | Declaration::Const(_)
        | Declaration::SexVar(_) => return, // Different structure
    };

    // Check for duplicate statements
    let mut seen_uses: Vec<&str> = Vec::new();
    for stmt in statements {
        if let Statement::Uses { reference, .. } = stmt {
            if seen_uses.contains(&reference.as_str()) {
                result.add_error(ValidationError::DuplicateDefinition {
                    kind: "uses".to_string(),
                    name: reference.clone(),
                });
            } else {
                seen_uses.push(reference);
            }
        }
    }
}

/// Validates gene-specific rules.
fn validate_gene(gene: &Gen, result: &mut ValidationResult) {
    // Genes should only contain has, is, derives from, requires statements
    for stmt in &gene.statements {
        match stmt {
            Statement::Has { .. }
            | Statement::Is { .. }
            | Statement::DerivesFrom { .. }
            | Statement::Requires { .. } => {}
            Statement::Uses { span, .. } => {
                result.add_error(ValidationError::InvalidIdentifier {
                    name: "uses".to_string(),
                    reason: "genes cannot use 'uses' statements; use traits instead".to_string(),
                });
                let _ = span; // suppress warning
            }
            _ => {}
        }
    }
}

/// Validates trait-specific rules.
fn validate_trait(trait_decl: &Trait, result: &mut ValidationResult) {
    // Traits should have at least one uses or behavior statement
    let has_uses = trait_decl
        .statements
        .iter()
        .any(|s| matches!(s, Statement::Uses { .. }));

    let has_behavior = trait_decl
        .statements
        .iter()
        .any(|s| matches!(s, Statement::Is { .. }));

    if !has_uses && !has_behavior {
        result.add_warning(ValidationWarning::NamingConvention {
            name: trait_decl.name.clone(),
            suggestion: "traits typically include 'uses' or behavior statements".to_string(),
        });
    }
}

/// Validates constraint-specific rules.
fn validate_constraint(constraint: &Rule, result: &mut ValidationResult) {
    // Constraints should have matches or never statements
    let has_constraint_stmts = constraint
        .statements
        .iter()
        .any(|s| matches!(s, Statement::Matches { .. } | Statement::Never { .. }));

    if !has_constraint_stmts {
        result.add_warning(ValidationWarning::NamingConvention {
            name: constraint.name.clone(),
            suggestion: "constraints typically include 'matches' or 'never' statements".to_string(),
        });
    }
}

/// Validates system-specific rules.
fn validate_system(system: &System, result: &mut ValidationResult) {
    // Validate version format
    if !is_valid_version(&system.version) {
        result.add_error(ValidationError::InvalidVersion {
            version: system.version.clone(),
            reason: "must be valid semver (X.Y.Z)".to_string(),
        });
    }

    // Validate requirements
    for req in &system.requirements {
        if !is_valid_version(&req.version) {
            result.add_error(ValidationError::InvalidVersion {
                version: req.version.clone(),
                reason: format!("invalid version in requirement for '{}'", req.name),
            });
        }
    }
}

/// Validates evolution-specific rules.
fn validate_evolution(evolution: &Evo, result: &mut ValidationResult) {
    // Validate versions
    if !is_valid_version(&evolution.version) {
        result.add_error(ValidationError::InvalidVersion {
            version: evolution.version.clone(),
            reason: "must be valid semver (X.Y.Z)".to_string(),
        });
    }

    if !is_valid_version(&evolution.parent_version) {
        result.add_error(ValidationError::InvalidVersion {
            version: evolution.parent_version.clone(),
            reason: "parent version must be valid semver (X.Y.Z)".to_string(),
        });
    }

    // Check version ordering (new version should be greater than parent)
    if is_valid_version(&evolution.version)
        && is_valid_version(&evolution.parent_version)
        && !is_version_greater(&evolution.version, &evolution.parent_version)
    {
        result.add_warning(ValidationWarning::NamingConvention {
            name: evolution.name.clone(),
            suggestion: format!(
                "new version '{}' should be greater than parent '{}'",
                evolution.version, evolution.parent_version
            ),
        });
    }

    // Should have at least one change
    if evolution.additions.is_empty()
        && evolution.deprecations.is_empty()
        && evolution.removals.is_empty()
    {
        result.add_warning(ValidationWarning::NamingConvention {
            name: evolution.name.clone(),
            suggestion: "evolution should include at least one adds, deprecates, or removes"
                .to_string(),
        });
    }
}

// === DOL 2.0 Type Validation ===

/// Validates types in DOL 2.0 expressions.
///
/// This function type-checks expressions found in the declaration,
/// including let bindings, lambda expressions, and control flow.
fn validate_types(decl: &Declaration, result: &mut ValidationResult) {
    let mut checker = TypeChecker::new();
    let span = decl.span();

    // Currently, DOL 2.0 expressions can appear in evolution additions
    // and potentially in future extended statement types
    if let Declaration::Evolution(evolution) = decl {
        for stmt in &evolution.additions {
            validate_statement_types(stmt, &mut checker, result, span);
        }
        for stmt in &evolution.deprecations {
            validate_statement_types(stmt, &mut checker, result, span);
        }
    }

    // Convert any accumulated type errors to validation errors
    for error in checker.errors() {
        result.add_type_error(error, span);
    }
}

/// Type-checks a statement for DOL 2.0 expressions.
fn validate_statement_types(
    _stmt: &Statement,
    _checker: &mut TypeChecker,
    _result: &mut ValidationResult,
    _span: Span,
) {
    // Current Statement enum doesn't embed DOL 2.0 expressions directly.
    // This is a placeholder for when statements can contain typed expressions.
    // For now, type checking happens when parsing DOL 2.0 expression blocks.
}

/// Type-checks an expression and reports any errors.
#[allow(dead_code)]
fn validate_expr_types(
    expr: &Expr,
    checker: &mut TypeChecker,
    result: &mut ValidationResult,
    span: Span,
) {
    if let Err(error) = checker.infer(expr) {
        result.add_type_error(&error, span);
    }
}

/// Type-checks a statement and reports any errors.
#[allow(dead_code)]
fn validate_stmt_types(
    stmt: &Stmt,
    checker: &mut TypeChecker,
    result: &mut ValidationResult,
    span: Span,
) {
    match stmt {
        Stmt::Let {
            name,
            type_ann,
            value,
        } => {
            // Infer the value's type
            match checker.infer(value) {
                Ok(inferred_type) => {
                    // If there's a type annotation, verify it matches
                    if let Some(ann) = type_ann {
                        let expected = Type::from_type_expr(ann);
                        if !types_match(&inferred_type, &expected) {
                            result.add_type_error(
                                &TypeError::mismatch(expected, inferred_type),
                                span,
                            );
                        }
                    }
                    // Bind the variable (would need to track in checker's env)
                    let _ = name; // Suppress unused warning
                }
                Err(error) => {
                    result.add_type_error(&error, span);
                }
            }
        }
        Stmt::Expr(expr) => {
            validate_expr_types(expr, checker, result, span);
        }
        Stmt::For {
            binding: _,
            iterable,
            body,
        } => {
            validate_expr_types(iterable, checker, result, span);
            for s in body {
                validate_stmt_types(s, checker, result, span);
            }
        }
        Stmt::While { condition, body } => {
            // Condition must be Bool
            if let Err(error) = checker.check(condition, &Type::Bool) {
                result.add_type_error(&error, span);
            }
            for s in body {
                validate_stmt_types(s, checker, result, span);
            }
        }
        Stmt::Loop { body } => {
            for s in body {
                validate_stmt_types(s, checker, result, span);
            }
        }
        Stmt::Return(Some(expr)) => {
            validate_expr_types(expr, checker, result, span);
        }
        Stmt::Return(None) | Stmt::Break | Stmt::Continue => {}
        Stmt::Assign { target, value } => {
            validate_expr_types(target, checker, result, span);
            validate_expr_types(value, checker, result, span);
        }
    }
}

/// Checks if two types match (considering Any and Unknown as wildcards).
fn types_match(ty1: &Type, ty2: &Type) -> bool {
    match (ty1, ty2) {
        (Type::Unknown, _) | (_, Type::Unknown) => true,
        (Type::Any, _) | (_, Type::Any) => true,
        (Type::Error, _) | (_, Type::Error) => true,
        (a, b) if a == b => true,
        // Numeric types are compatible
        (a, b) if a.is_numeric() && b.is_numeric() => true,
        _ => false,
    }
}

// === Helper Functions ===

/// Checks if an identifier is valid.
fn is_valid_qualified_identifier(name: &str) -> bool {
    if name.is_empty() {
        return false;
    }

    // Split by dots and validate each part
    for part in name.split('.') {
        if part.is_empty() {
            return false;
        }

        let mut chars = part.chars();
        let first = chars.next().unwrap();

        // First char must be alphabetic
        if !first.is_alphabetic() {
            return false;
        }

        // Rest must be alphanumeric or underscore
        for ch in chars {
            if !ch.is_alphanumeric() && ch != '_' {
                return false;
            }
        }
    }

    true
}

/// Checks if a version string is valid semver.
fn is_valid_version(version: &str) -> bool {
    let parts: Vec<&str> = version.split('.').collect();
    if parts.len() != 3 {
        return false;
    }

    for part in parts {
        if part.parse::<u64>().is_err() {
            return false;
        }
    }

    true
}

/// Compares two version strings.
fn is_version_greater(version: &str, other: &str) -> bool {
    let parse_version = |v: &str| -> (u64, u64, u64) {
        let parts: Vec<&str> = v.split('.').collect();
        (
            parts[0].parse().unwrap_or(0),
            parts[1].parse().unwrap_or(0),
            parts[2].parse().unwrap_or(0),
        )
    };

    let v1 = parse_version(version);
    let v2 = parse_version(other);

    v1 > v2
}

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

    fn make_gene(name: &str, exegesis: &str) -> Declaration {
        Declaration::Gene(Gen {
            visibility: Visibility::default(),
            name: name.to_string(),
            extends: None,
            statements: vec![Statement::Has {
                subject: "test".to_string(),
                property: "property".to_string(),
                span: Span::default(),
            }],
            exegesis: exegesis.to_string(),
            span: Span::default(),
        })
    }

    #[test]
    fn test_valid_declaration() {
        let decl = make_gene(
            "container.exists",
            "A container is the fundamental unit of workload isolation.",
        );
        let result = validate(&decl);
        assert!(result.is_valid());
    }

    #[test]
    fn test_empty_exegesis() {
        let decl = make_gene("container.exists", "");
        let result = validate(&decl);
        assert!(result.is_valid());
        assert!(result.has_warnings());
    }

    #[test]
    fn test_short_exegesis_warning() {
        let decl = make_gene("container.exists", "Short.");
        let result = validate(&decl);
        assert!(result.is_valid()); // Still valid, just warning
        assert!(result.has_warnings());
    }

    #[test]
    fn test_valid_identifier() {
        assert!(is_valid_qualified_identifier("container.exists"));
        assert!(is_valid_qualified_identifier("identity.cryptographic"));
        assert!(is_valid_qualified_identifier("simple"));
        assert!(!is_valid_qualified_identifier(""));
        assert!(!is_valid_qualified_identifier(".starts.with.dot"));
        assert!(!is_valid_qualified_identifier("123invalid"));
    }

    #[test]
    fn test_valid_version() {
        assert!(is_valid_version("0.0.1"));
        assert!(is_valid_version("1.2.3"));
        assert!(is_valid_version("10.20.30"));
        assert!(!is_valid_version("1.2"));
        assert!(!is_valid_version("1.2.3.4"));
        assert!(!is_valid_version("a.b.c"));
    }

    #[test]
    fn test_version_comparison() {
        assert!(is_version_greater("0.0.2", "0.0.1"));
        assert!(is_version_greater("0.1.0", "0.0.9"));
        assert!(is_version_greater("1.0.0", "0.9.9"));
        assert!(!is_version_greater("0.0.1", "0.0.2"));
        assert!(!is_version_greater("0.0.1", "0.0.1"));
    }

    // === DOL 2.0 Type-Aware Validation Tests ===

    #[test]
    fn test_validate_with_options_default() {
        let decl = make_gene("test.gene", "A test gene for validation options testing.");
        let options = ValidationOptions::default();
        assert!(!options.typecheck);
        let result = validate_with_options(&decl, &options);
        assert!(result.is_valid());
    }

    #[test]
    fn test_validate_with_typecheck_enabled() {
        let decl = make_gene("test.gene", "A test gene for type checking validation.");
        let options = ValidationOptions { typecheck: true };
        let result = validate_with_options(&decl, &options);
        // Should still be valid (no DOL 2.0 expressions with errors)
        assert!(result.is_valid());
    }

    #[test]
    fn test_types_match_any() {
        assert!(types_match(&Type::Any, &Type::Int32));
        assert!(types_match(&Type::String, &Type::Any));
    }

    #[test]
    fn test_types_match_unknown() {
        assert!(types_match(&Type::Unknown, &Type::Int32));
        assert!(types_match(&Type::String, &Type::Unknown));
    }

    #[test]
    fn test_types_match_error() {
        assert!(types_match(&Type::Error, &Type::Int32));
        assert!(types_match(&Type::String, &Type::Error));
    }

    #[test]
    fn test_types_match_same() {
        assert!(types_match(&Type::Int32, &Type::Int32));
        assert!(types_match(&Type::String, &Type::String));
        assert!(types_match(&Type::Bool, &Type::Bool));
    }

    #[test]
    fn test_types_match_numeric_promotion() {
        // All numeric types are compatible
        assert!(types_match(&Type::Int32, &Type::Int64));
        assert!(types_match(&Type::Float32, &Type::Float64));
        assert!(types_match(&Type::Int32, &Type::Float64));
    }

    #[test]
    fn test_types_mismatch() {
        assert!(!types_match(&Type::String, &Type::Int32));
        assert!(!types_match(&Type::Bool, &Type::String));
    }

    #[test]
    fn test_add_type_error_to_result() {
        let mut result = ValidationResult::new("test");
        let type_error = crate::typechecker::TypeError::mismatch(Type::String, Type::Int32);
        result.add_type_error(&type_error, Span::default());

        assert!(!result.is_valid());
        assert_eq!(result.errors.len(), 1);
        match &result.errors[0] {
            crate::error::ValidationError::TypeError {
                expected, actual, ..
            } => {
                assert!(expected.as_ref().unwrap().contains("String"));
                assert!(actual.as_ref().unwrap().contains("Int32"));
            }
            _ => panic!("Expected TypeError variant"),
        }
    }

    #[test]
    fn test_validation_options_typecheck_flag() {
        let options = ValidationOptions { typecheck: true };
        assert!(options.typecheck);

        let options = ValidationOptions { typecheck: false };
        assert!(!options.typecheck);
    }

    // === File Validation Tests ===

    fn make_use_decl(visibility: Visibility, source: ImportSource, path: Vec<&str>) -> UseDecl {
        UseDecl {
            visibility,
            source,
            path: path.into_iter().map(|s| s.to_string()).collect(),
            items: UseItems::Single,
            alias: None,
            span: Span::default(),
        }
    }

    #[test]
    fn test_validate_file_empty() {
        let file = DolFile {
            module: None,
            uses: vec![],
            declarations: vec![],
        };
        let result = validate_file(&file);
        assert!(result.is_valid());
    }

    #[test]
    fn test_validate_file_with_module() {
        let file = DolFile {
            module: Some(ModuleDecl {
                path: vec!["container".to_string()],
                version: None,
                span: Span::default(),
            }),
            uses: vec![],
            declarations: vec![],
        };
        let result = validate_file(&file);
        assert!(result.is_valid());
    }

    #[test]
    fn test_validate_file_with_versioned_module() {
        let file = DolFile {
            module: Some(ModuleDecl {
                path: vec!["container".to_string(), "lib".to_string()],
                version: Some(Version {
                    major: 1,
                    minor: 0,
                    patch: 0,
                    suffix: None,
                }),
                span: Span::default(),
            }),
            uses: vec![],
            declarations: vec![],
        };
        let result = validate_file(&file);
        assert!(result.is_valid());
    }

    #[test]
    fn test_validate_file_with_zero_version_warning() {
        let file = DolFile {
            module: Some(ModuleDecl {
                path: vec!["test".to_string()],
                version: Some(Version {
                    major: 0,
                    minor: 0,
                    patch: 0,
                    suffix: None,
                }),
                span: Span::default(),
            }),
            uses: vec![],
            declarations: vec![],
        };
        let result = validate_file(&file);
        assert!(result.is_valid()); // Still valid, just warning
        assert!(result.has_warnings());
    }

    #[test]
    fn test_validate_local_use() {
        let file = DolFile {
            module: None,
            uses: vec![make_use_decl(
                Visibility::Private,
                ImportSource::Local,
                vec!["container", "state"],
            )],
            declarations: vec![],
        };
        let result = validate_file(&file);
        assert!(result.is_valid());
    }

    #[test]
    fn test_validate_pub_use() {
        let file = DolFile {
            module: None,
            uses: vec![make_use_decl(
                Visibility::Public,
                ImportSource::Local,
                vec!["container", "Container"],
            )],
            declarations: vec![],
        };
        let result = validate_file(&file);
        assert!(result.is_valid());
    }

    #[test]
    fn test_validate_registry_use() {
        let file = DolFile {
            module: None,
            uses: vec![make_use_decl(
                Visibility::Private,
                ImportSource::Registry {
                    org: "univrs".to_string(),
                    package: "std".to_string(),
                    version: None,
                },
                vec!["io"],
            )],
            declarations: vec![],
        };
        let result = validate_file(&file);
        assert!(result.is_valid());
    }

    #[test]
    fn test_validate_duplicate_use_warning() {
        let file = DolFile {
            module: None,
            uses: vec![
                make_use_decl(Visibility::Private, ImportSource::Local, vec!["container"]),
                make_use_decl(Visibility::Private, ImportSource::Local, vec!["container"]),
            ],
            declarations: vec![],
        };
        let result = validate_file(&file);
        assert!(result.is_valid()); // Still valid, just warning
        assert!(result.has_warnings());
    }

    #[test]
    fn test_validate_empty_registry_org_error() {
        let file = DolFile {
            module: None,
            uses: vec![make_use_decl(
                Visibility::Private,
                ImportSource::Registry {
                    org: "".to_string(),
                    package: "std".to_string(),
                    version: None,
                },
                vec![],
            )],
            declarations: vec![],
        };
        let result = validate_file(&file);
        assert!(!result.is_valid());
    }

    #[test]
    fn test_validate_https_url_format() {
        // Valid HTTPS URL
        let file = DolFile {
            module: None,
            uses: vec![make_use_decl(
                Visibility::Private,
                ImportSource::Https {
                    url: "https://example.com/module.dol".to_string(),
                    sha256: None,
                },
                vec![],
            )],
            declarations: vec![],
        };
        let result = validate_file(&file);
        assert!(result.is_valid());
    }

    #[test]
    fn test_validate_https_missing_protocol_error() {
        let file = DolFile {
            module: None,
            uses: vec![make_use_decl(
                Visibility::Private,
                ImportSource::Https {
                    url: "example.com/module.dol".to_string(), // Missing https://
                    sha256: None,
                },
                vec![],
            )],
            declarations: vec![],
        };
        let result = validate_file(&file);
        assert!(!result.is_valid());
    }

    #[test]
    fn test_file_validation_result_all_errors() {
        let mut result = FileValidationResult::new();
        result.add_error(ValidationError::InvalidIdentifier {
            name: "test".to_string(),
            reason: "test error".to_string(),
        });
        let errors = result.all_errors();
        assert_eq!(errors.len(), 1);
    }

    #[test]
    fn test_file_validation_result_all_warnings() {
        let mut result = FileValidationResult::new();
        result.add_warning(ValidationWarning::ShortExegesis {
            length: 5,
            span: Span::default(),
        });
        let warnings = result.all_warnings();
        assert_eq!(warnings.len(), 1);
    }
}