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
//! Check result types for LightGraphCheck.
use std::fmt;
/// Result of a lightweight graph-based check.
#[derive(Debug, Clone, Default)]
pub enum CheckResult {
/// Check passed.
#[default]
Ok,
/// Check passed with warnings (proceed with caution).
Warning(Vec<CheckWarning>),
/// Check failed (mutation should be aborted or cascaded).
Error(Vec<CheckError>),
}
impl CheckResult {
/// Returns true if the check passed (Ok or Warning).
#[inline]
pub fn is_ok(&self) -> bool {
matches!(self, Self::Ok | Self::Warning(_))
}
/// Returns true if the check failed.
#[inline]
pub fn is_err(&self) -> bool {
matches!(self, Self::Error(_))
}
/// Get errors if any.
pub fn errors(&self) -> &[CheckError] {
match self {
Self::Error(errors) => errors,
_ => &[],
}
}
/// Get warnings if any.
pub fn warnings(&self) -> &[CheckWarning] {
match self {
Self::Warning(warnings) => warnings,
_ => &[],
}
}
/// Merge two results, keeping the worse outcome.
pub fn merge(self, other: Self) -> Self {
match (self, other) {
// Both Ok
(Self::Ok, Self::Ok) => Self::Ok,
// Error takes precedence
(Self::Error(mut e1), Self::Error(e2)) => {
e1.extend(e2);
Self::Error(e1)
}
(Self::Error(e), _) | (_, Self::Error(e)) => Self::Error(e),
// Warning merges
(Self::Warning(mut w1), Self::Warning(w2)) => {
w1.extend(w2);
Self::Warning(w1)
}
(Self::Warning(w), Self::Ok) | (Self::Ok, Self::Warning(w)) => Self::Warning(w),
}
}
}
/// Warning from a light check.
#[derive(Debug, Clone)]
pub struct CheckWarning {
/// Warning message.
pub message: String,
/// Location context (if available).
pub location: Option<String>,
}
impl CheckWarning {
/// Create a new warning.
pub fn new(message: impl Into<String>) -> Self {
Self {
message: message.into(),
location: None,
}
}
/// Create a warning with location context.
pub fn with_location(message: impl Into<String>, location: impl Into<String>) -> Self {
Self {
message: message.into(),
location: Some(location.into()),
}
}
/// Create an unused symbol warning.
pub fn unused_symbol(name: impl Into<String>, reason: impl Into<String>) -> Self {
Self {
message: format!("unused symbol '{}': {}", name.into(), reason.into()),
location: None,
}
}
/// Create a warning for symbol that would become unused.
pub fn would_become_unused(name: impl Into<String>, reason: impl Into<String>) -> Self {
Self {
message: format!(
"symbol '{}' would become unused: {}",
name.into(),
reason.into()
),
location: None,
}
}
}
impl fmt::Display for CheckWarning {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(loc) = &self.location {
write!(f, "{}: {}", loc, self.message)
} else {
write!(f, "{}", self.message)
}
}
}
/// Error from a light check.
#[derive(Debug, Clone)]
pub enum CheckError {
/// Unresolved symbol reference.
UnresolvedRef {
/// The symbol name that couldn't be resolved.
name: String,
/// Location context (if available).
location: Option<String>,
/// Suggested alternatives (if any).
suggestions: Vec<String>,
},
/// Derive macro cannot be applied.
DeriveFailed {
/// Target type name.
target: String,
/// Trait that cannot be derived.
trait_name: String,
/// Field types missing the required trait implementation.
missing_impls: Vec<String>,
},
/// Type not found in registry.
TypeNotFound {
/// The type name that wasn't found.
type_name: String,
},
/// Trait not implemented for type.
TraitNotImplemented {
/// Type that doesn't implement the trait.
type_name: String,
/// Trait that isn't implemented.
trait_name: String,
},
// === Borrow Checking Errors (Rust-specific) ===
/// Simultaneous mutable borrows of the same variable.
SimultaneousMutBorrow {
/// Variable name.
variable: String,
/// Line of the first mutable borrow.
first_borrow_line: u32,
/// Line of the second mutable borrow.
second_borrow_line: u32,
},
/// Conflict between mutable and shared borrows.
BorrowConflict {
/// Variable name.
variable: String,
/// Existing borrow kind ("mutable" or "shared").
existing_kind: String,
/// Line of the existing borrow.
existing_line: u32,
/// New borrow kind.
new_kind: String,
/// Line of the new borrow.
new_line: u32,
},
/// Use of a variable after it has been moved.
UseAfterMove {
/// Variable name.
variable: String,
/// Line where the move occurred.
moved_at: u32,
/// Line where the invalid use occurred.
used_at: u32,
},
/// Dangling reference (reference to dropped value).
DanglingReference {
/// Reference variable name.
reference: String,
/// Source variable name (the dropped value).
source: String,
/// Line where the source was dropped.
dropped_at: u32,
/// Line where the reference was used.
used_at: u32,
},
/// Cannot mutate through a shared reference.
CannotMutateThroughSharedRef {
/// Variable name.
variable: String,
/// Line where mutation was attempted.
at_line: u32,
},
// === Member Access Errors ===
/// Field not found on a type.
FieldNotFound {
/// Type that was accessed.
type_name: String,
/// Field name that wasn't found.
field_name: String,
/// Available fields (for suggestions).
available_fields: Vec<String>,
},
/// Method not found on a type.
MethodNotFound {
/// Type that was accessed.
type_name: String,
/// Method name that wasn't found.
method_name: String,
/// Available methods (for suggestions).
available_methods: Vec<String>,
},
/// Enum variant not found.
EnumVariantNotFound {
/// Enum type name.
enum_name: String,
/// Variant name that wasn't found.
variant_name: String,
/// Available variants (for suggestions).
available_variants: Vec<String>,
},
/// Missing required field in struct literal.
MissingRequiredField {
/// Struct type name.
struct_name: String,
/// Missing field names.
missing_fields: Vec<String>,
},
/// Function argument count mismatch.
ArgumentCountMismatch {
/// Function name.
function_name: String,
/// Expected argument count.
expected: usize,
/// Actual argument count.
actual: usize,
},
/// Ambiguous target - multiple symbols match the given name.
AmbiguousTarget {
/// The name that matched multiple symbols.
name: String,
/// The matching symbol paths.
candidates: Vec<String>,
},
/// Type change has impact on other parts of the codebase.
TypeImpact {
/// Description of the impact.
description: String,
/// Details about the affected areas.
details: String,
},
/// Reference integrity issue (dangling references, missing fields, etc.).
ReferenceIntegrity {
/// Description of the issue.
description: String,
/// Details about the affected areas.
details: String,
},
/// Generic check failure.
Other {
/// Error message.
message: String,
},
}
impl CheckError {
/// Create an unresolved reference error.
pub fn unresolved(name: impl Into<String>) -> Self {
Self::UnresolvedRef {
name: name.into(),
location: None,
suggestions: Vec::new(),
}
}
/// Create an unresolved reference error with location.
pub fn unresolved_at(name: impl Into<String>, location: impl Into<String>) -> Self {
Self::UnresolvedRef {
name: name.into(),
location: Some(location.into()),
suggestions: Vec::new(),
}
}
/// Create a type not found error.
pub fn type_not_found(type_name: impl Into<String>) -> Self {
Self::TypeNotFound {
type_name: type_name.into(),
}
}
/// Create a derive failed error.
pub fn derive_failed(
target: impl Into<String>,
trait_name: impl Into<String>,
missing_impls: Vec<String>,
) -> Self {
Self::DeriveFailed {
target: target.into(),
trait_name: trait_name.into(),
missing_impls,
}
}
/// Create a trait not implemented error.
pub fn trait_not_impl(type_name: impl Into<String>, trait_name: impl Into<String>) -> Self {
Self::TraitNotImplemented {
type_name: type_name.into(),
trait_name: trait_name.into(),
}
}
// === Borrow Error Constructors ===
/// Create a simultaneous mutable borrow error.
pub fn simultaneous_mut_borrow(
variable: impl Into<String>,
first_borrow_line: u32,
second_borrow_line: u32,
) -> Self {
Self::SimultaneousMutBorrow {
variable: variable.into(),
first_borrow_line,
second_borrow_line,
}
}
/// Create a borrow conflict error.
pub fn borrow_conflict(
variable: impl Into<String>,
existing_kind: impl Into<String>,
existing_line: u32,
new_kind: impl Into<String>,
new_line: u32,
) -> Self {
Self::BorrowConflict {
variable: variable.into(),
existing_kind: existing_kind.into(),
existing_line,
new_kind: new_kind.into(),
new_line,
}
}
/// Create a use after move error.
pub fn use_after_move(variable: impl Into<String>, moved_at: u32, used_at: u32) -> Self {
Self::UseAfterMove {
variable: variable.into(),
moved_at,
used_at,
}
}
/// Create a dangling reference error.
pub fn dangling_reference(
reference: impl Into<String>,
source: impl Into<String>,
dropped_at: u32,
used_at: u32,
) -> Self {
Self::DanglingReference {
reference: reference.into(),
source: source.into(),
dropped_at,
used_at,
}
}
/// Create a cannot mutate through shared ref error.
pub fn cannot_mutate_shared(variable: impl Into<String>, at_line: u32) -> Self {
Self::CannotMutateThroughSharedRef {
variable: variable.into(),
at_line,
}
}
// === Member Access Error Constructors ===
/// Create a field not found error.
pub fn field_not_found(
type_name: impl Into<String>,
field_name: impl Into<String>,
available_fields: Vec<String>,
) -> Self {
Self::FieldNotFound {
type_name: type_name.into(),
field_name: field_name.into(),
available_fields,
}
}
/// Create a method not found error.
pub fn method_not_found(
type_name: impl Into<String>,
method_name: impl Into<String>,
available_methods: Vec<String>,
) -> Self {
Self::MethodNotFound {
type_name: type_name.into(),
method_name: method_name.into(),
available_methods,
}
}
/// Create an enum variant not found error.
pub fn variant_not_found(
enum_name: impl Into<String>,
variant_name: impl Into<String>,
available_variants: Vec<String>,
) -> Self {
Self::EnumVariantNotFound {
enum_name: enum_name.into(),
variant_name: variant_name.into(),
available_variants,
}
}
/// Create a missing required field error.
pub fn missing_fields(struct_name: impl Into<String>, missing_fields: Vec<String>) -> Self {
Self::MissingRequiredField {
struct_name: struct_name.into(),
missing_fields,
}
}
/// Create an argument count mismatch error.
pub fn arg_count_mismatch(
function_name: impl Into<String>,
expected: usize,
actual: usize,
) -> Self {
Self::ArgumentCountMismatch {
function_name: function_name.into(),
expected,
actual,
}
}
/// Create an ambiguous target error.
pub fn ambiguous_target(name: impl Into<String>, candidates: Vec<String>) -> Self {
Self::AmbiguousTarget {
name: name.into(),
candidates,
}
}
/// Create a type impact error.
pub fn type_impact(description: impl Into<String>, details: impl Into<String>) -> Self {
Self::TypeImpact {
description: description.into(),
details: details.into(),
}
}
/// Create a reference integrity error.
pub fn reference_integrity(description: impl Into<String>, details: impl Into<String>) -> Self {
Self::ReferenceIntegrity {
description: description.into(),
details: details.into(),
}
}
}
impl fmt::Display for CheckError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::UnresolvedRef {
name,
location,
suggestions,
} => {
if let Some(loc) = location {
write!(f, "{}: ", loc)?;
}
write!(f, "unresolved reference: `{}`", name)?;
if !suggestions.is_empty() {
write!(f, " (did you mean: {}?)", suggestions.join(", "))?;
}
Ok(())
}
Self::DeriveFailed {
target,
trait_name,
missing_impls,
} => {
write!(
f,
"cannot derive `{}` for `{}`: missing impl on {}",
trait_name,
target,
missing_impls.join(", ")
)
}
Self::TypeNotFound { type_name } => {
write!(f, "type not found: `{}`", type_name)
}
Self::TraitNotImplemented {
type_name,
trait_name,
} => {
write!(f, "`{}` does not implement `{}`", type_name, trait_name)
}
// === Borrow Errors ===
Self::SimultaneousMutBorrow {
variable,
first_borrow_line,
second_borrow_line,
} => {
write!(
f,
"cannot borrow `{}` as mutable more than once: \
first borrow at line {}, second borrow at line {}",
variable, first_borrow_line, second_borrow_line
)
}
Self::BorrowConflict {
variable,
existing_kind,
existing_line,
new_kind,
new_line,
} => {
write!(
f,
"cannot borrow `{}` as {} because it is already borrowed as {}: \
existing borrow at line {}, new borrow at line {}",
variable, new_kind, existing_kind, existing_line, new_line
)
}
Self::UseAfterMove {
variable,
moved_at,
used_at,
} => {
write!(
f,
"use of moved value `{}`: moved at line {}, used at line {}",
variable, moved_at, used_at
)
}
Self::DanglingReference {
reference,
source,
dropped_at,
used_at,
} => {
write!(
f,
"dangling reference `{}`: source `{}` dropped at line {}, \
reference used at line {}",
reference, source, dropped_at, used_at
)
}
Self::CannotMutateThroughSharedRef { variable, at_line } => {
write!(
f,
"cannot mutate `{}` through a shared reference at line {}",
variable, at_line
)
}
// === Member Access Errors ===
Self::FieldNotFound {
type_name,
field_name,
available_fields,
} => {
write!(
f,
"field `{}` not found on type `{}`",
field_name, type_name
)?;
if !available_fields.is_empty() {
write!(f, " (available: {})", available_fields.join(", "))?;
}
Ok(())
}
Self::MethodNotFound {
type_name,
method_name,
available_methods,
} => {
write!(
f,
"method `{}` not found on type `{}`",
method_name, type_name
)?;
if !available_methods.is_empty() {
write!(f, " (available: {})", available_methods.join(", "))?;
}
Ok(())
}
Self::EnumVariantNotFound {
enum_name,
variant_name,
available_variants,
} => {
write!(
f,
"variant `{}` not found in enum `{}`",
variant_name, enum_name
)?;
if !available_variants.is_empty() {
write!(f, " (available: {})", available_variants.join(", "))?;
}
Ok(())
}
Self::MissingRequiredField {
struct_name,
missing_fields,
} => {
write!(
f,
"missing required field(s) in struct `{}`: {}",
struct_name,
missing_fields.join(", ")
)
}
Self::ArgumentCountMismatch {
function_name,
expected,
actual,
} => {
write!(
f,
"function `{}` expects {} argument(s), but {} provided",
function_name, expected, actual
)
}
Self::AmbiguousTarget { name, candidates } => {
write!(
f,
"ambiguous target `{}`: multiple symbols found ({})",
name,
candidates.join(", ")
)
}
Self::TypeImpact {
description,
details,
} => {
write!(f, "type impact: {} ({})", description, details)
}
Self::ReferenceIntegrity {
description,
details,
} => {
write!(f, "reference integrity: {} ({})", description, details)
}
Self::Other { message } => write!(f, "{}", message),
}
}
}
impl std::error::Error for CheckError {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_check_result_is_ok() {
assert!(CheckResult::Ok.is_ok());
assert!(CheckResult::Warning(vec![]).is_ok());
assert!(!CheckResult::Error(vec![]).is_ok());
}
#[test]
fn test_check_result_merge() {
let ok1 = CheckResult::Ok;
let ok2 = CheckResult::Ok;
assert!(matches!(ok1.merge(ok2), CheckResult::Ok));
let ok = CheckResult::Ok;
let err = CheckResult::Error(vec![CheckError::type_not_found("Foo")]);
assert!(matches!(ok.merge(err), CheckResult::Error(_)));
let warn1 = CheckResult::Warning(vec![CheckWarning::new("w1")]);
let warn2 = CheckResult::Warning(vec![CheckWarning::new("w2")]);
let merged = warn1.merge(warn2);
assert!(matches!(merged, CheckResult::Warning(ref w) if w.len() == 2));
}
#[test]
fn test_check_error_display() {
let err = CheckError::unresolved("foo");
assert_eq!(format!("{}", err), "unresolved reference: `foo`");
let err = CheckError::derive_failed("MyStruct", "Default", vec!["SomeField".to_string()]);
assert!(format!("{}", err).contains("cannot derive"));
}
}