oxilean-cli 0.1.2

OxiLean command-line interface
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
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
//! Auto-generated module
//!
//! 🤖 Generated with [SplitRS](https://github.com/cool-japan/splitrs)

use super::functions::*;
use oxilean_kernel::{Declaration, ReducibilityHint};
use std::collections::{HashMap, HashSet, VecDeque};
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};

#[allow(dead_code)]
#[derive(Debug, Clone)]
pub enum BuildEvent {
    Started { file: String },
    Succeeded { file: String, duration_ms: u64 },
    Failed { file: String, error: String },
    Skipped { file: String, reason: String },
    Warning { file: String, message: String },
}
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub struct BuildCacheEntry {
    pub source_hash: u64,
    pub output_path: std::path::PathBuf,
    pub built_at: std::time::SystemTime,
}
#[allow(dead_code)]
pub struct BuildFilter {
    include_patterns: Vec<String>,
    exclude_patterns: Vec<String>,
}
#[allow(dead_code)]
impl BuildFilter {
    pub fn new() -> Self {
        Self {
            include_patterns: Vec::new(),
            exclude_patterns: Vec::new(),
        }
    }
    pub fn include(mut self, pattern: &str) -> Self {
        self.include_patterns.push(pattern.to_string());
        self
    }
    pub fn exclude(mut self, pattern: &str) -> Self {
        self.exclude_patterns.push(pattern.to_string());
        self
    }
    pub fn matches(&self, path: &str) -> bool {
        let excluded = self
            .exclude_patterns
            .iter()
            .any(|p| path.contains(p.as_str()));
        if excluded {
            return false;
        }
        if self.include_patterns.is_empty() {
            return true;
        }
        self.include_patterns
            .iter()
            .any(|p| path.contains(p.as_str()))
    }
}
/// The build executor drives the compilation pipeline.
#[derive(Debug)]
pub struct BuildExecutor {
    /// Build configuration.
    config: BuildConfig,
    /// Build dependency graph.
    graph: BuildGraph,
    /// Accumulated results.
    results: Vec<BuildStepResult>,
    /// When the build started.
    start_time: Instant,
}
impl BuildExecutor {
    /// Create a new executor for the given configuration and graph.
    pub fn new(config: BuildConfig, graph: BuildGraph) -> Self {
        Self {
            config,
            graph,
            results: Vec::new(),
            start_time: Instant::now(),
        }
    }
    /// Run the full build, returning a report.
    pub fn execute_build(&mut self) -> BuildReport {
        self.start_time = Instant::now();
        self.results.clear();
        let order = match self.graph.topological_order() {
            Ok(o) => o,
            Err(msg) => {
                self.results.push(BuildStepResult {
                    module: "<graph>".to_string(),
                    status: BuildStatus::Failure,
                    duration: Duration::ZERO,
                    diagnostics: vec![msg],
                });
                return self.make_report();
            }
        };
        for module in &order {
            let result = self.execute_step(module);
            self.results.push(result);
        }
        self.make_report()
    }
    /// Compile a single module through the OxiLean pipeline.
    pub fn execute_step(&self, module_name: &str) -> BuildStepResult {
        let step_start = Instant::now();
        let node = match self.graph.get_node(module_name) {
            Some(n) => n,
            None => {
                return BuildStepResult {
                    module: module_name.to_string(),
                    status: BuildStatus::Failure,
                    duration: step_start.elapsed(),
                    diagnostics: vec![format!("module '{}' not found in graph", module_name)],
                };
            }
        };
        if !node.is_stale && !self.config.force_rebuild {
            return BuildStepResult {
                module: module_name.to_string(),
                status: BuildStatus::Skipped,
                duration: step_start.elapsed(),
                diagnostics: Vec::new(),
            };
        }
        if !self.config.force_rebuild {
            if let Some(cached) = self.check_cache(module_name, node.hash) {
                return cached;
            }
        }
        let source = match std::fs::read_to_string(&node.source_path) {
            Ok(s) => s,
            Err(e) => {
                return BuildStepResult {
                    module: module_name.to_string(),
                    status: BuildStatus::Failure,
                    duration: step_start.elapsed(),
                    diagnostics: vec![format!("cannot read {}: {}", node.source_path.display(), e)],
                };
            }
        };
        let mut diagnostics = Vec::new();
        let mut lexer = oxilean_parse::Lexer::new(&source);
        let tokens = lexer.tokenize();
        if tokens.is_empty() {
            diagnostics.push("warning: source file produced no tokens".to_string());
        }
        let mut parser = oxilean_parse::Parser::new(tokens);
        let mut decls = Vec::new();
        loop {
            match parser.parse_decl() {
                Ok(d) => decls.push(d),
                Err(e) => {
                    let msg = e.to_string();
                    if msg.contains("end of file") {
                        break;
                    }
                    return BuildStepResult {
                        module: module_name.to_string(),
                        status: BuildStatus::Failure,
                        duration: step_start.elapsed(),
                        diagnostics: vec![format!("parse error: {}", msg)],
                    };
                }
            }
        }
        let mut env = oxilean_kernel::Environment::new();
        for surface_decl in &decls {
            match oxilean_elab::elaborate_decl(&env, &surface_decl.value) {
                Ok(pending) => {
                    use oxilean_elab::PendingDecl;
                    use oxilean_kernel::{Declaration, ReducibilityHint};
                    let kernel_decl = match pending {
                        PendingDecl::Definition { name, ty, val, .. } => Declaration::Definition {
                            name,
                            univ_params: vec![],
                            ty,
                            val,
                            hint: ReducibilityHint::Regular(0),
                        },
                        PendingDecl::Theorem {
                            name, ty, proof, ..
                        } => Declaration::Theorem {
                            name,
                            univ_params: vec![],
                            ty,
                            val: proof,
                        },
                        PendingDecl::Axiom { name, ty, .. } => Declaration::Axiom {
                            name,
                            univ_params: vec![],
                            ty,
                        },
                        PendingDecl::Inductive { name, ty, .. } => Declaration::Axiom {
                            name,
                            univ_params: vec![],
                            ty,
                        },
                        PendingDecl::Opaque { name, ty, val } => Declaration::Opaque {
                            name,
                            univ_params: vec![],
                            ty,
                            val,
                        },
                    };
                    if let Err(e) = oxilean_kernel::check_declaration(&mut env, kernel_decl) {
                        return BuildStepResult {
                            module: module_name.to_string(),
                            status: BuildStatus::Failure,
                            duration: step_start.elapsed(),
                            diagnostics: vec![format!("type error: {}", e)],
                        };
                    }
                }
                Err(e) => {
                    return BuildStepResult {
                        module: module_name.to_string(),
                        status: BuildStatus::Failure,
                        duration: step_start.elapsed(),
                        diagnostics: vec![format!("elaboration error: {:?}", e)],
                    };
                }
            }
        }
        if self.config.verbose {
            diagnostics.push(format!(
                "checked {} declaration(s) in {}",
                decls.len(),
                module_name,
            ));
        }
        let result = BuildStepResult {
            module: module_name.to_string(),
            status: BuildStatus::Success,
            duration: step_start.elapsed(),
            diagnostics,
        };
        self.write_cache(module_name, node.hash);
        result
    }
    /// Try to load a cached result for the given module + hash.
    fn check_cache(&self, module_name: &str, hash: u64) -> Option<BuildStepResult> {
        let cache_path = self.config.cache_dir.join(format!("{}.cache", module_name));
        if let Ok(data) = std::fs::read_to_string(&cache_path) {
            if let Ok(cached_hash) = data.trim().parse::<u64>() {
                if cached_hash == hash {
                    return Some(BuildStepResult {
                        module: module_name.to_string(),
                        status: BuildStatus::Cached,
                        duration: Duration::ZERO,
                        diagnostics: Vec::new(),
                    });
                }
            }
        }
        None
    }
    /// Write a cache entry for the given module.
    fn write_cache(&self, module_name: &str, hash: u64) {
        let cache_path = self.config.cache_dir.join(format!("{}.cache", module_name));
        if let Some(parent) = cache_path.parent() {
            let _ = std::fs::create_dir_all(parent);
        }
        let _ = std::fs::write(&cache_path, hash.to_string());
    }
    /// Build a report from accumulated results.
    fn make_report(&self) -> BuildReport {
        let mut succeeded = 0usize;
        let mut failed = 0usize;
        let mut cached = 0usize;
        for r in &self.results {
            match r.status {
                BuildStatus::Success => succeeded += 1,
                BuildStatus::Failure => failed += 1,
                BuildStatus::Cached => cached += 1,
                BuildStatus::Skipped => {}
            }
        }
        BuildReport {
            total_modules: self.graph.node_count(),
            succeeded,
            failed,
            cached,
            elapsed: self.start_time.elapsed(),
            steps: self.results.clone(),
        }
    }
}
/// Optimisation level.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum OptLevel {
    /// No optimisations, full debug info.
    Debug,
    /// Full optimisations.
    Release,
    /// Optimise for binary size.
    Size,
}
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub struct DependencyVersion {
    pub name: String,
    pub version: String,
    pub hash: String,
}
/// Kind of build target (for BuildTargetConfig).
#[allow(dead_code)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum BuildTargetKind {
    Library,
    Binary,
    Test,
    Benchmark,
}
#[allow(dead_code)]
#[derive(Debug, Default)]
pub struct BuildMetrics {
    pub compiled: usize,
    pub skipped: usize,
    pub failed: usize,
    pub total_duration_ms: u64,
}
#[allow(dead_code)]
impl BuildMetrics {
    pub fn record_compiled(&mut self, duration_ms: u64) {
        self.compiled += 1;
        self.total_duration_ms += duration_ms;
    }
    pub fn record_skipped(&mut self) {
        self.skipped += 1;
    }
    pub fn record_failed(&mut self) {
        self.failed += 1;
    }
    pub fn success_rate(&self) -> f64 {
        let total = self.compiled + self.failed;
        if total == 0 {
            return 1.0;
        }
        self.compiled as f64 / total as f64
    }
    pub fn avg_duration_ms(&self) -> f64 {
        if self.compiled == 0 {
            return 0.0;
        }
        self.total_duration_ms as f64 / self.compiled as f64
    }
    pub fn to_summary(&self) -> String {
        format!(
            "Compiled: {} Skipped: {} Failed: {} Success: {:.1}%",
            self.compiled,
            self.skipped,
            self.failed,
            self.success_rate() * 100.0
        )
    }
}
/// A record of a past build.
#[allow(dead_code)]
#[derive(Clone, Debug)]
pub struct BuildHistoryEntry {
    pub timestamp_secs: u64,
    pub success: bool,
    pub duration_ms: u64,
    pub stage_reached: String,
    pub error_count: usize,
    pub warning_count: usize,
}
/// Result of compiling a single module.
#[derive(Clone, Debug)]
pub struct BuildStepResult {
    /// Module name.
    pub module: String,
    /// Final status.
    pub status: BuildStatus,
    /// Wall-clock time for this step.
    pub duration: Duration,
    /// Diagnostic messages (errors, warnings).
    pub diagnostics: Vec<String>,
}
impl BuildStepResult {
    /// Return true if the step succeeded (including cached).
    pub fn is_ok(&self) -> bool {
        matches!(
            self.status,
            BuildStatus::Success | BuildStatus::Cached | BuildStatus::Skipped
        )
    }
}
/// Manages compiled artifacts on disk.
#[derive(Clone, Debug)]
pub struct ArtifactStore {
    /// Root directory where artifacts are stored.
    root_dir: PathBuf,
}
impl ArtifactStore {
    /// Create a new artifact store at the given directory.
    pub fn new(root_dir: impl Into<PathBuf>) -> Self {
        Self {
            root_dir: root_dir.into(),
        }
    }
    /// Compute the path on disk for a given module name.
    pub fn artifact_path(&self, module_name: &str) -> PathBuf {
        let sanitized = module_name.replace('.', "/");
        self.root_dir.join(format!("{}.olean", sanitized))
    }
    /// Store compiled data for a module.
    pub fn store_artifact(&self, module_name: &str, data: &[u8]) -> Result<(), String> {
        let path = self.artifact_path(module_name);
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)
                .map_err(|e| format!("cannot create artifact dir: {}", e))?;
        }
        std::fs::write(&path, data)
            .map_err(|e| format!("cannot write artifact '{}': {}", path.display(), e))
    }
    /// Load compiled data for a module.
    pub fn load_artifact(&self, module_name: &str) -> Result<Vec<u8>, String> {
        let path = self.artifact_path(module_name);
        std::fs::read(&path)
            .map_err(|e| format!("cannot read artifact '{}': {}", path.display(), e))
    }
    /// Invalidate (remove) the artifact for a module.
    pub fn invalidate_artifact(&self, module_name: &str) -> Result<(), String> {
        let path = self.artifact_path(module_name);
        if path.exists() {
            std::fs::remove_file(&path)
                .map_err(|e| format!("cannot remove artifact '{}': {}", path.display(), e))?;
        }
        Ok(())
    }
    /// Remove all artifacts.
    pub fn clean_artifacts(&self) -> Result<usize, String> {
        if !self.root_dir.exists() {
            return Ok(0);
        }
        let mut count = 0usize;
        let entries = std::fs::read_dir(&self.root_dir)
            .map_err(|e| format!("cannot read artifact dir: {}", e))?;
        for entry in entries.flatten() {
            let path = entry.path();
            if path.extension().and_then(|e| e.to_str()) == Some("olean")
                && std::fs::remove_file(&path).is_ok()
            {
                count += 1;
            }
        }
        Ok(count)
    }
    /// Return the total size of all artifacts in bytes.
    pub fn total_size(&self) -> u64 {
        if !self.root_dir.exists() {
            return 0;
        }
        let mut total = 0u64;
        if let Ok(entries) = std::fs::read_dir(&self.root_dir) {
            for entry in entries.flatten() {
                if let Ok(meta) = entry.metadata() {
                    total += meta.len();
                }
            }
        }
        total
    }
}
/// A stage in the build pipeline.
#[allow(dead_code)]
#[derive(Clone, Debug)]
pub struct BuildStage {
    pub name: String,
    pub description: String,
    pub required: bool,
    pub parallel: bool,
}
impl BuildStage {
    /// Create a required sequential stage.
    #[allow(dead_code)]
    pub fn required(name: impl Into<String>, description: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            description: description.into(),
            required: true,
            parallel: false,
        }
    }
    /// Create an optional parallel stage.
    #[allow(dead_code)]
    pub fn optional_parallel(name: impl Into<String>, description: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            description: description.into(),
            required: false,
            parallel: true,
        }
    }
}
/// A named build target with explicit source/output config.
#[allow(dead_code)]
#[derive(Clone, Debug)]
pub struct BuildTargetConfig {
    pub name: String,
    pub sources: Vec<String>,
    pub dependencies: Vec<String>,
    pub output: String,
    pub build_type: BuildTargetKind,
}
impl BuildTargetConfig {
    /// Create a library target.
    #[allow(dead_code)]
    pub fn library(
        name: impl Into<String>,
        sources: Vec<String>,
        output: impl Into<String>,
    ) -> Self {
        Self {
            name: name.into(),
            sources,
            dependencies: vec![],
            output: output.into(),
            build_type: BuildTargetKind::Library,
        }
    }
    /// Create a binary target.
    #[allow(dead_code)]
    pub fn binary(
        name: impl Into<String>,
        sources: Vec<String>,
        output: impl Into<String>,
    ) -> Self {
        Self {
            name: name.into(),
            sources,
            dependencies: vec![],
            output: output.into(),
            build_type: BuildTargetKind::Binary,
        }
    }
    /// Add a dependency.
    #[allow(dead_code)]
    pub fn with_dependency(mut self, dep: impl Into<String>) -> Self {
        self.dependencies.push(dep.into());
        self
    }
}
/// A validation error.
#[allow(dead_code)]
#[derive(Clone, Debug)]
pub struct BuildValidationError {
    pub field: String,
    pub message: String,
}
#[allow(dead_code)]
pub struct ArtifactRegistry {
    artifacts: Vec<BuildArtifact>,
}
#[allow(dead_code)]
impl ArtifactRegistry {
    pub fn new() -> Self {
        Self {
            artifacts: Vec::new(),
        }
    }
    pub fn add(&mut self, artifact: BuildArtifact) {
        self.artifacts.push(artifact);
    }
    pub fn by_kind(&self, kind: &ArtifactKind) -> Vec<&BuildArtifact> {
        self.artifacts.iter().filter(|a| &a.kind == kind).collect()
    }
    pub fn total_size(&self) -> u64 {
        self.artifacts.iter().map(|a| a.size_bytes).sum()
    }
    pub fn count(&self) -> usize {
        self.artifacts.len()
    }
    pub fn find_by_source(&self, source: &str) -> Option<&BuildArtifact> {
        self.artifacts.iter().find(|a| a.source == source)
    }
}
/// History of past builds.
#[allow(dead_code)]
pub struct BuildHistory {
    pub(crate) entries: Vec<BuildHistoryEntry>,
    max_entries: usize,
}
impl BuildHistory {
    /// Create a new history store.
    #[allow(dead_code)]
    pub fn new(max_entries: usize) -> Self {
        Self {
            entries: vec![],
            max_entries,
        }
    }
    /// Record a build.
    #[allow(dead_code)]
    pub fn record(&mut self, entry: BuildHistoryEntry) {
        if self.entries.len() >= self.max_entries {
            self.entries.remove(0);
        }
        self.entries.push(entry);
    }
    /// Return the last N entries.
    #[allow(dead_code)]
    pub fn last_n(&self, n: usize) -> Vec<&BuildHistoryEntry> {
        self.entries.iter().rev().take(n).collect()
    }
    /// Return the success rate.
    #[allow(dead_code)]
    pub fn success_rate(&self) -> f64 {
        if self.entries.is_empty() {
            return 0.0;
        }
        let success = self.entries.iter().filter(|e| e.success).count();
        100.0 * success as f64 / self.entries.len() as f64
    }
}
#[allow(dead_code)]
pub struct BuildEventRecorder {
    events: Vec<(std::time::Instant, BuildEvent)>,
    max_events: usize,
}
#[allow(dead_code)]
impl BuildEventRecorder {
    pub fn new(max_events: usize) -> Self {
        Self {
            events: Vec::new(),
            max_events,
        }
    }
    pub fn record(&mut self, event: BuildEvent) {
        if self.events.len() >= self.max_events {
            self.events.remove(0);
        }
        self.events.push((std::time::Instant::now(), event));
    }
    pub fn failures(&self) -> Vec<&BuildEvent> {
        self.events
            .iter()
            .filter(|(_, e)| matches!(e, BuildEvent::Failed { .. }))
            .map(|(_, e)| e)
            .collect()
    }
    pub fn successes(&self) -> Vec<&BuildEvent> {
        self.events
            .iter()
            .filter(|(_, e)| matches!(e, BuildEvent::Succeeded { .. }))
            .map(|(_, e)| e)
            .collect()
    }
    pub fn event_count(&self) -> usize {
        self.events.len()
    }
}
/// Configuration for a build session.
#[derive(Clone, Debug)]
pub struct BuildConfig {
    /// Root directory of the project.
    pub project_root: PathBuf,
    /// Directory for build outputs.
    pub output_dir: PathBuf,
    /// Maximum number of parallel compilation units.
    pub parallelism: usize,
    /// Enable verbose logging.
    pub verbose: bool,
    /// Force a full rebuild regardless of cache state.
    pub force_rebuild: bool,
    /// Directory for build caches.
    pub cache_dir: PathBuf,
    /// The kind of build to perform.
    pub target: BuildTarget,
    /// Optimisation level.
    pub opt_level: OptLevel,
}
impl BuildConfig {
    /// Create a build configuration rooted at the given project directory.
    pub fn for_project(root: impl Into<PathBuf>) -> Self {
        let root = root.into();
        let output_dir = root.join("build");
        let cache_dir = output_dir.join("cache");
        Self {
            project_root: root,
            output_dir,
            cache_dir,
            ..Default::default()
        }
    }
    /// Return the effective optimisation level taking the target into account.
    pub fn effective_opt_level(&self) -> OptLevel {
        match self.target {
            BuildTarget::Release | BuildTarget::Bench => OptLevel::Release,
            _ => self.opt_level,
        }
    }
    /// Check whether the configuration requests parallel builds.
    pub fn is_parallel(&self) -> bool {
        self.parallelism > 1
    }
    /// Validate the configuration, returning an error message if invalid.
    pub fn validate(&self) -> Result<(), String> {
        if self.parallelism == 0 {
            return Err("parallelism must be at least 1".to_string());
        }
        Ok(())
    }
}
#[allow(dead_code)]
pub struct BuildLockfile {
    pub dependencies: Vec<DependencyVersion>,
    pub generated_at: String,
}
#[allow(dead_code)]
impl BuildLockfile {
    pub fn new() -> Self {
        Self {
            dependencies: Vec::new(),
            generated_at: "2026-02-28".to_string(),
        }
    }
    pub fn add_dep(&mut self, name: &str, version: &str, hash: &str) {
        self.dependencies.push(DependencyVersion {
            name: name.to_string(),
            version: version.to_string(),
            hash: hash.to_string(),
        });
    }
    pub fn find(&self, name: &str) -> Option<&DependencyVersion> {
        self.dependencies.iter().find(|d| d.name == name)
    }
    pub fn to_toml(&self) -> String {
        let mut out = format!("# Generated at {}\n\n", self.generated_at);
        for dep in &self.dependencies {
            out.push_str(&format!(
                "[[dependency]]\nname = \"{}\"\nversion = \"{}\"\nhash = \"{}\"\n\n",
                dep.name, dep.version, dep.hash
            ));
        }
        out
    }
}
/// Summary report for a build run.
#[derive(Clone, Debug)]
pub struct BuildReport {
    /// Total number of modules in the build graph.
    pub total_modules: usize,
    /// Number of modules that compiled successfully.
    pub succeeded: usize,
    /// Number of modules that failed to compile.
    pub failed: usize,
    /// Number of modules served from cache.
    pub cached: usize,
    /// Total wall-clock time.
    pub elapsed: Duration,
    /// Per-module results.
    pub steps: Vec<BuildStepResult>,
}
impl BuildReport {
    /// Return true if there were no failures.
    pub fn is_success(&self) -> bool {
        self.failed == 0
    }
    /// Return the list of failed modules.
    pub fn failed_modules(&self) -> Vec<&str> {
        self.steps
            .iter()
            .filter(|s| s.status == BuildStatus::Failure)
            .map(|s| s.module.as_str())
            .collect()
    }
    /// Collect all diagnostic messages.
    pub fn all_diagnostics(&self) -> Vec<&str> {
        self.steps
            .iter()
            .flat_map(|s| s.diagnostics.iter().map(|d| d.as_str()))
            .collect()
    }
}
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub struct BuildLogEntry {
    pub level: LogLevel,
    pub message: String,
    pub source: Option<String>,
    pub timestamp: std::time::Instant,
}
#[allow(dead_code)]
pub struct BuildLog {
    entries: Vec<BuildLogEntry>,
    max_entries: usize,
}
#[allow(dead_code)]
impl BuildLog {
    pub fn new(max_entries: usize) -> Self {
        Self {
            entries: Vec::new(),
            max_entries,
        }
    }
    pub fn log(&mut self, level: LogLevel, message: &str, source: Option<&str>) {
        if self.entries.len() >= self.max_entries {
            self.entries.remove(0);
        }
        self.entries.push(BuildLogEntry {
            level,
            message: message.to_string(),
            source: source.map(|s| s.to_string()),
            timestamp: std::time::Instant::now(),
        });
    }
    pub fn info(&mut self, msg: &str) {
        self.log(LogLevel::Info, msg, None);
    }
    pub fn warn(&mut self, msg: &str) {
        self.log(LogLevel::Warning, msg, None);
    }
    pub fn error(&mut self, msg: &str) {
        self.log(LogLevel::Error, msg, None);
    }
    pub fn errors(&self) -> Vec<&BuildLogEntry> {
        self.entries
            .iter()
            .filter(|e| e.level == LogLevel::Error)
            .collect()
    }
    pub fn warnings(&self) -> Vec<&BuildLogEntry> {
        self.entries
            .iter()
            .filter(|e| e.level == LogLevel::Warning)
            .collect()
    }
    pub fn last_n(&self, n: usize) -> &[BuildLogEntry] {
        let start = self.entries.len().saturating_sub(n);
        &self.entries[start..]
    }
}
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub struct BuildArtifact {
    pub source: String,
    pub output: std::path::PathBuf,
    pub kind: ArtifactKind,
    pub size_bytes: u64,
}
/// A single node in the build dependency graph.
#[derive(Clone, Debug)]
pub struct BuildNode {
    /// Fully qualified module name (e.g. `Mathlib.Algebra.Group`).
    pub module_name: String,
    /// Path to the source file.
    pub source_path: PathBuf,
    /// Module names this node directly depends on.
    pub dependencies: Vec<String>,
    /// Path where the compiled output will be written.
    pub output_path: PathBuf,
    /// Whether this node needs to be rebuilt.
    pub is_stale: bool,
    /// Content hash of the source file.
    pub hash: u64,
}
impl BuildNode {
    /// Create a new build node.
    pub fn new(module_name: String, source_path: PathBuf, output_path: PathBuf) -> Self {
        Self {
            module_name,
            source_path,
            dependencies: Vec::new(),
            output_path,
            is_stale: true,
            hash: 0,
        }
    }
    /// Add a dependency on another module.
    pub fn add_dependency(&mut self, dep: String) {
        if !self.dependencies.contains(&dep) {
            self.dependencies.push(dep);
        }
    }
    /// Return the number of direct dependencies.
    pub fn dependency_count(&self) -> usize {
        self.dependencies.len()
    }
}
#[allow(dead_code)]
pub struct BuildCache {
    entries: std::collections::HashMap<String, BuildCacheEntry>,
}
#[allow(dead_code)]
impl BuildCache {
    pub fn new() -> Self {
        Self {
            entries: std::collections::HashMap::new(),
        }
    }
    pub fn insert(&mut self, source: &str, entry: BuildCacheEntry) {
        self.entries.insert(source.to_string(), entry);
    }
    pub fn get(&self, source: &str) -> Option<&BuildCacheEntry> {
        self.entries.get(source)
    }
    pub fn is_stale(&self, source: &str, current_hash: u64) -> bool {
        match self.get(source) {
            None => true,
            Some(e) => e.source_hash != current_hash,
        }
    }
    pub fn invalidate(&mut self, source: &str) {
        self.entries.remove(source);
    }
    pub fn clear(&mut self) {
        self.entries.clear();
    }
    pub fn size(&self) -> usize {
        self.entries.len()
    }
}
/// A multi-stage build pipeline.
#[allow(dead_code)]
pub struct BuildPipeline {
    stages: Vec<BuildStage>,
}
impl BuildPipeline {
    /// Create a default OxiLean build pipeline.
    #[allow(dead_code)]
    pub fn default_oxilean() -> Self {
        Self {
            stages: vec![
                BuildStage::required("parse", "Parse all source files"),
                BuildStage::required("elaborate", "Elaborate declarations"),
                BuildStage::required("typecheck", "Type-check elaborated terms"),
                BuildStage::optional_parallel("codegen", "Generate code"),
                BuildStage::optional_parallel("optimize", "Optimize output"),
                BuildStage::required("link", "Link artifacts"),
            ],
        }
    }
    /// Return stage names.
    #[allow(dead_code)]
    pub fn stage_names(&self) -> Vec<&str> {
        self.stages.iter().map(|s| s.name.as_str()).collect()
    }
    /// Return required stages.
    #[allow(dead_code)]
    pub fn required_stages(&self) -> Vec<&BuildStage> {
        self.stages.iter().filter(|s| s.required).collect()
    }
}
/// Severity of a build diagnostic.
#[allow(dead_code)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum BuildDiagnosticSeverity {
    Error,
    Warning,
    Note,
}
#[allow(dead_code)]
pub struct ParallelBuildPlan {
    pub waves: Vec<Vec<String>>,
}
#[allow(dead_code)]
impl ParallelBuildPlan {
    pub fn from_deps(deps: &std::collections::HashMap<String, Vec<String>>) -> Self {
        let mut in_degree: std::collections::HashMap<&str, usize> =
            std::collections::HashMap::new();
        for (node, _) in deps {
            in_degree.entry(node.as_str()).or_insert(0);
        }
        for deps_list in deps.values() {
            for dep in deps_list {
                *in_degree.entry(dep.as_str()).or_insert(0) += 1;
            }
        }
        let mut waves = Vec::new();
        while !in_degree.is_empty() {
            let wave: Vec<String> = in_degree
                .iter()
                .filter(|(_, &d)| d == 0)
                .map(|(n, _)| n.to_string())
                .collect();
            if wave.is_empty() {
                break;
            }
            for node in &wave {
                in_degree.remove(node.as_str());
                if let Some(dependents) = deps.get(node.as_str()) {
                    for dep in dependents {
                        if let Some(d) = in_degree.get_mut(dep.as_str()) {
                            *d = d.saturating_sub(1);
                        }
                    }
                }
            }
            waves.push(wave);
        }
        Self { waves }
    }
    pub fn wave_count(&self) -> usize {
        self.waves.len()
    }
    pub fn total_nodes(&self) -> usize {
        self.waves.iter().map(|w| w.len()).sum()
    }
}
/// Build target kind.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum BuildTarget {
    /// Type-check only (no code generation).
    Check,
    /// Full build with debug info.
    Build,
    /// Optimised release build.
    Release,
    /// Build and run tests.
    Test,
    /// Build and run benchmarks.
    Bench,
    /// Generate documentation.
    Doc,
}
/// Status of a single build step.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BuildStatus {
    /// Compilation succeeded.
    Success,
    /// Compilation failed.
    Failure,
    /// Result was served from cache.
    Cached,
    /// Step was skipped (e.g. not stale).
    Skipped,
}
/// Directed acyclic graph of build nodes.
#[derive(Clone, Debug)]
pub struct BuildGraph {
    /// All nodes keyed by module name.
    nodes: HashMap<String, BuildNode>,
    /// Adjacency list: module -> modules that depend on it.
    reverse_deps: HashMap<String, Vec<String>>,
}
impl BuildGraph {
    /// Create an empty build graph.
    pub fn new() -> Self {
        Self {
            nodes: HashMap::new(),
            reverse_deps: HashMap::new(),
        }
    }
    /// Add a node to the graph.
    pub fn add_node(&mut self, node: BuildNode) {
        let name = node.module_name.clone();
        for dep in &node.dependencies {
            self.reverse_deps
                .entry(dep.clone())
                .or_default()
                .push(name.clone());
        }
        self.nodes.insert(name, node);
    }
    /// Retrieve a node by module name.
    pub fn get_node(&self, name: &str) -> Option<&BuildNode> {
        self.nodes.get(name)
    }
    /// Retrieve a mutable reference to a node.
    pub fn get_node_mut(&mut self, name: &str) -> Option<&mut BuildNode> {
        self.nodes.get_mut(name)
    }
    /// Return all node names.
    pub fn module_names(&self) -> Vec<String> {
        self.nodes.keys().cloned().collect()
    }
    /// Return the number of nodes.
    pub fn node_count(&self) -> usize {
        self.nodes.len()
    }
    /// Return true if the graph contains a node with the given name.
    pub fn contains(&self, name: &str) -> bool {
        self.nodes.contains_key(name)
    }
    /// Compute staleness for each node by comparing content hashes and
    /// checking whether any dependency is stale.
    pub fn compute_staleness(&mut self, cache: &HashMap<String, u64>) {
        let names: Vec<String> = self.nodes.keys().cloned().collect();
        for name in &names {
            if let Some(node) = self.nodes.get_mut(name) {
                match cache.get(name) {
                    Some(&cached_hash) if cached_hash == node.hash => {
                        node.is_stale = false;
                    }
                    _ => {
                        node.is_stale = true;
                    }
                }
            }
        }
        let mut changed = true;
        while changed {
            changed = false;
            for name in &names {
                let stale = {
                    let node = &self.nodes[name];
                    if node.is_stale {
                        continue;
                    }
                    node.dependencies
                        .iter()
                        .any(|d| self.nodes.get(d).is_some_and(|n| n.is_stale))
                };
                if stale {
                    self.nodes
                        .get_mut(name)
                        .expect("name exists in nodes: iterating over self.nodes keys")
                        .is_stale = true;
                    changed = true;
                }
            }
        }
    }
    /// Return a topological ordering of the modules that is safe for
    /// parallel compilation (all dependencies of a module appear before it).
    pub fn topological_order(&self) -> Result<Vec<String>, String> {
        let mut in_degree: HashMap<String, usize> = HashMap::new();
        for (name, node) in &self.nodes {
            in_degree.entry(name.clone()).or_insert(0);
            for dep in &node.dependencies {
                if self.nodes.contains_key(dep) {
                    *in_degree.entry(name.clone()).or_insert(0) += 1;
                }
            }
        }
        let mut queue: VecDeque<String> = in_degree
            .iter()
            .filter(|(_, &d)| d == 0)
            .map(|(n, _)| n.clone())
            .collect();
        let mut order = Vec::with_capacity(self.nodes.len());
        while let Some(name) = queue.pop_front() {
            order.push(name.clone());
            if let Some(dependents) = self.reverse_deps.get(&name) {
                for dep in dependents {
                    if let Some(d) = in_degree.get_mut(dep) {
                        *d = d.saturating_sub(1);
                        if *d == 0 {
                            queue.push_back(dep.clone());
                        }
                    }
                }
            }
        }
        if order.len() != self.nodes.len() {
            return Err("cyclic dependency detected in build graph".to_string());
        }
        Ok(order)
    }
    /// Return the set of modules that need to be rebuilt when the given
    /// module changes (transitive dependents).
    pub fn affected_nodes(&self, changed: &str) -> HashSet<String> {
        let mut affected = HashSet::new();
        let mut queue = VecDeque::new();
        queue.push_back(changed.to_string());
        while let Some(name) = queue.pop_front() {
            if affected.contains(&name) {
                continue;
            }
            affected.insert(name.clone());
            if let Some(dependents) = self.reverse_deps.get(&name) {
                for dep in dependents {
                    if !affected.contains(dep) {
                        queue.push_back(dep.clone());
                    }
                }
            }
        }
        affected
    }
}
#[allow(dead_code)]
#[derive(Debug, Clone, PartialEq)]
pub enum ArtifactKind {
    ObjectFile,
    Binary,
    WasmModule,
    DocumentationFile,
    TestBinary,
}
#[allow(dead_code)]
pub struct BuildSummaryReport {
    pub files_compiled: usize,
    pub files_skipped: usize,
    pub files_failed: usize,
    pub total_duration_ms: u64,
    pub errors: Vec<String>,
    pub warnings: Vec<String>,
}
#[allow(dead_code)]
impl BuildSummaryReport {
    pub fn new() -> Self {
        Self {
            files_compiled: 0,
            files_skipped: 0,
            files_failed: 0,
            total_duration_ms: 0,
            errors: Vec::new(),
            warnings: Vec::new(),
        }
    }
    pub fn is_success(&self) -> bool {
        self.files_failed == 0
    }
    pub fn to_string(&self) -> String {
        format!(
            "Build: {} compiled, {} skipped, {} failed in {}ms. {} error(s), {} warning(s).",
            self.files_compiled,
            self.files_skipped,
            self.files_failed,
            self.total_duration_ms,
            self.errors.len(),
            self.warnings.len()
        )
    }
}
/// Validates build configuration for correctness.
#[allow(dead_code)]
pub struct BuildConfigValidator;
impl BuildConfigValidator {
    /// Validate a build environment.
    #[allow(dead_code)]
    pub fn validate_env(env: &BuildEnvironment) -> Vec<BuildValidationError> {
        let mut errors = vec![];
        if env.jobs == 0 {
            errors.push(BuildValidationError {
                field: "jobs".to_string(),
                message: "jobs must be >= 1".to_string(),
            });
        }
        if env.optimization_level > 3 {
            errors.push(BuildValidationError {
                field: "optimization_level".to_string(),
                message: "optimization_level must be 0-3".to_string(),
            });
        }
        if env.output_dir.is_empty() {
            errors.push(BuildValidationError {
                field: "output_dir".to_string(),
                message: "output_dir must not be empty".to_string(),
            });
        }
        errors
    }
}
/// Environment configuration for building.
#[allow(dead_code)]
#[derive(Clone, Debug)]
pub struct BuildEnvironment {
    pub oxilean_path: String,
    pub stdlib_path: String,
    pub output_dir: String,
    pub cache_dir: String,
    pub jobs: usize,
    pub optimization_level: u8,
    pub debug_info: bool,
    pub warnings_as_errors: bool,
}
impl BuildEnvironment {
    /// Create a development environment.
    #[allow(dead_code)]
    pub fn development() -> Self {
        Self {
            oxilean_path: "/usr/local/oxilean".to_string(),
            stdlib_path: "/usr/local/oxilean/lib".to_string(),
            output_dir: "target/debug".to_string(),
            cache_dir: ".oxilean_cache".to_string(),
            jobs: 4,
            optimization_level: 0,
            debug_info: true,
            warnings_as_errors: false,
        }
    }
    /// Create a release environment.
    #[allow(dead_code)]
    pub fn release() -> Self {
        Self {
            oxilean_path: "/usr/local/oxilean".to_string(),
            stdlib_path: "/usr/local/oxilean/lib".to_string(),
            output_dir: "target/release".to_string(),
            cache_dir: ".oxilean_cache".to_string(),
            jobs: num_cpus_estimate(),
            optimization_level: 3,
            debug_info: false,
            warnings_as_errors: true,
        }
    }
}
/// A diagnostic emitted during the build process.
#[allow(dead_code)]
#[derive(Clone, Debug)]
pub struct BuildDiagnostic {
    pub stage: String,
    pub file: Option<String>,
    pub line: Option<u32>,
    pub column: Option<u32>,
    pub message: String,
    pub severity: BuildDiagnosticSeverity,
}
impl BuildDiagnostic {
    /// Create an error diagnostic.
    #[allow(dead_code)]
    pub fn error(stage: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            stage: stage.into(),
            file: None,
            line: None,
            column: None,
            message: message.into(),
            severity: BuildDiagnosticSeverity::Error,
        }
    }
    /// Create a warning.
    #[allow(dead_code)]
    pub fn warning(stage: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            stage: stage.into(),
            file: None,
            line: None,
            column: None,
            message: message.into(),
            severity: BuildDiagnosticSeverity::Warning,
        }
    }
    /// Add a file location.
    #[allow(dead_code)]
    pub fn at_location(mut self, file: impl Into<String>, line: u32, col: u32) -> Self {
        self.file = Some(file.into());
        self.line = Some(line);
        self.column = Some(col);
        self
    }
    /// Format as a human-readable string.
    #[allow(dead_code)]
    pub fn format(&self) -> String {
        let sev = match self.severity {
            BuildDiagnosticSeverity::Error => "error",
            BuildDiagnosticSeverity::Warning => "warning",
            BuildDiagnosticSeverity::Note => "note",
        };
        if let (Some(file), Some(line)) = (&self.file, self.line) {
            format!(
                "[{}] {}:{}:{}: [{}] {}",
                self.stage,
                file,
                line,
                self.column.unwrap_or(0),
                sev,
                self.message
            )
        } else {
            format!("[{}] [{}] {}", self.stage, sev, self.message)
        }
    }
}
#[allow(dead_code)]
pub struct BuildProgress {
    pub total: usize,
    pub done: usize,
    pub failed: usize,
    pub start: std::time::Instant,
}
#[allow(dead_code)]
impl BuildProgress {
    pub fn new(total: usize) -> Self {
        Self {
            total,
            done: 0,
            failed: 0,
            start: std::time::Instant::now(),
        }
    }
    pub fn complete_one(&mut self) {
        self.done += 1;
    }
    pub fn fail_one(&mut self) {
        self.failed += 1;
    }
    pub fn pct(&self) -> f64 {
        if self.total == 0 {
            return 100.0;
        }
        (self.done + self.failed) as f64 / self.total as f64 * 100.0
    }
    pub fn elapsed_secs(&self) -> f64 {
        self.start.elapsed().as_secs_f64()
    }
    pub fn eta_secs(&self) -> f64 {
        let done = self.done + self.failed;
        if done == 0 {
            return f64::INFINITY;
        }
        let rate = done as f64 / self.elapsed_secs();
        (self.total - done) as f64 / rate
    }
    pub fn status_line(&self) -> String {
        format!(
            "[{}/{} ({:.0}%)] {} failed | {:.1}s elapsed | ETA: {:.0}s",
            self.done + self.failed,
            self.total,
            self.pct(),
            self.failed,
            self.elapsed_secs(),
            self.eta_secs().min(99999.0)
        )
    }
}
#[allow(dead_code)]
#[derive(Debug, Clone, PartialEq)]
pub enum LogLevel {
    Debug,
    Info,
    Warning,
    Error,
}
#[allow(dead_code)]
impl LogLevel {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Debug => "debug",
            Self::Info => "info",
            Self::Warning => "warning",
            Self::Error => "error",
        }
    }
}
#[allow(dead_code)]
#[derive(Debug, Default, Clone)]
pub struct BuildProfile {
    pub lex_ms: f64,
    pub parse_ms: f64,
    pub elab_ms: f64,
    pub typecheck_ms: f64,
    pub codegen_ms: f64,
}
#[allow(dead_code)]
impl BuildProfile {
    pub fn total_ms(&self) -> f64 {
        self.lex_ms + self.parse_ms + self.elab_ms + self.typecheck_ms + self.codegen_ms
    }
    pub fn dominant_stage(&self) -> &'static str {
        let stages = [
            ("lex", self.lex_ms),
            ("parse", self.parse_ms),
            ("elab", self.elab_ms),
            ("typecheck", self.typecheck_ms),
            ("codegen", self.codegen_ms),
        ];
        stages
            .iter()
            .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
            .map(|(s, _)| *s)
            .unwrap_or("none")
    }
    pub fn add(&mut self, other: &BuildProfile) {
        self.lex_ms += other.lex_ms;
        self.parse_ms += other.parse_ms;
        self.elab_ms += other.elab_ms;
        self.typecheck_ms += other.typecheck_ms;
        self.codegen_ms += other.codegen_ms;
    }
}