-
Notifications
You must be signed in to change notification settings - Fork 407
Expand file tree
/
Copy pathdiagnostic.rs
More file actions
587 lines (511 loc) · 18.7 KB
/
diagnostic.rs
File metadata and controls
587 lines (511 loc) · 18.7 KB
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
//! Unified diagnostic type for all BAML compiler phases.
//!
//! This module provides a single `Diagnostic` type that can represent any
//! compiler error across all phases (parsing, HIR lowering, type checking).
//! This enables centralized rendering and consistent error handling.
use baml_base::{FileId, Span};
// ============================================================================
// DiagnosticPhase - Tracks which compiler phase produced a diagnostic
// ============================================================================
/// The compiler phase that produced a diagnostic.
///
/// This enables grouping diagnostics by phase for display purposes
/// (e.g., in `tools_onionskin` TUI or `baml_tests` snapshots).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum DiagnosticPhase {
/// Parsing phase errors (syntax errors from the parser)
#[default]
Parse,
/// HIR lowering phase (per-file validation like duplicate fields)
Hir,
/// Cross-file validation (duplicate names across files)
Validation,
/// Type inference phase (type mismatches, unknown variables)
Type,
}
impl DiagnosticPhase {
/// Get a short display name for the phase.
pub fn name(&self) -> &'static str {
match self {
DiagnosticPhase::Parse => "parse",
DiagnosticPhase::Hir => "hir",
DiagnosticPhase::Validation => "validation",
DiagnosticPhase::Type => "type",
}
}
}
/// Unique identifier for a diagnostic category.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DiagnosticId {
// Parse errors (E0009, E0010)
UnexpectedEof,
UnexpectedToken,
InvalidSyntax,
// Type errors (E0001-E0008)
TypeMismatch,
UnknownType,
UnknownVariable,
InvalidOperator,
ArgumentCountMismatch,
NotCallable,
NoSuchField,
NotIndexable,
InvalidMapKeyType,
// Name errors (E0011)
DuplicateName,
// HIR diagnostics (E0012-E0027)
DuplicateField,
DuplicateVariant,
DuplicateMethod,
DuplicateBinding,
DuplicateAttribute,
UnknownAttribute,
InvalidAttributeContext,
UnknownGeneratorProperty,
MissingGeneratorProperty,
InvalidGeneratorPropertyValue,
ReservedFieldName,
FieldNameMatchesTypeName,
InvalidClientResponseType,
HttpConfigNotBlock,
UnknownHttpConfigField,
NegativeTimeout,
MissingProvider,
UnknownClientProperty,
/// `remap_roles` must be a map.
RemapRolesNotMap,
/// `remap_role` values must be strings.
RemapRoleValueNotString,
/// Invalid role not in `allowed_roles` list.
RemapRoleNotAllowed,
/// `allowed_roles` must not be empty.
AllowedRolesEmpty,
/// `allowed_roles` values must be strings.
AllowedRoleNotString,
/// Composite client has empty strategy.
EmptyStrategy,
/// Unknown retry policy reference.
UnknownRetryPolicy,
/// Strategy array element is not a valid client name.
InvalidStrategyElement,
// Pattern matching errors (E0062-E0066)
NonExhaustiveMatch,
UnreachableArm,
NonExhaustiveCatch,
UnreachableCatchArm,
UnknownEnumVariant,
WatchOnNonVariable,
WatchOnUnwatchedVariable,
// Syntax errors (E0028-E0031)
MissingSemicolon,
MissingConditionParens,
UnmatchedDelimiter,
// Return expression errors (E0029)
MissingReturnExpression,
// Constraint attribute errors (E0032)
InvalidConstraintSyntax,
// Attribute value errors (E0037-E0038, E0101)
InvalidAttributeArg,
UnexpectedAttributeArg,
ConflictingStreamAttributes,
// Type literal errors (E0033)
UnsupportedFloatLiteral,
// Map type errors (E0039)
InvalidMapArity,
// Test diagnostics (E0034-E0036, E0088)
UnknownTestProperty,
MissingTestProperty,
TestFieldAttribute,
UnknownFunctionInTest,
// Type builder diagnostics (E0040-E0043)
TypeBuilderInNonTestContext,
DuplicateTypeBuilderBlock,
IncompleteDynamicDefinition,
TypeBuilderSyntaxError,
// Reserved prefix diagnostics
ReservedStreamPrefix,
// Cycle detection diagnostics (E0068-E0069)
AliasCycle,
ClassCycle,
// Jinja template diagnostics (E0070-E0086)
JinjaUnresolvedVariable,
JinjaFunctionReferenceWithoutCall,
JinjaInvalidFilter,
JinjaInvalidType,
JinjaPropertyNotDefined,
JinjaEnumValuePropertyAccess,
JinjaEnumStringComparison,
JinjaPropertyNotFoundInUnion,
JinjaPropertyTypeMismatchInUnion,
JinjaNonClassInUnion,
JinjaWrongArgCount,
JinjaMissingArg,
JinjaUnknownArg,
JinjaWrongArgType,
JinjaParseError,
JinjaUnsupportedFeature,
JinjaInvalidSyntax,
JinjaInvalidTest,
// Catch binding errors (E0093)
InvalidCatchBindingType,
// Throws contract errors (E0096-E0097)
ThrowsContractViolation,
ThrowsContractExtraneous,
// VIR lowering errors (E0089)
LoweringError,
// Removed feature errors (E0098)
InstanceofRemoved,
}
impl DiagnosticId {
/// Returns the error code as a string (e.g., "E0001").
pub fn code(&self) -> &'static str {
match self {
// Parse errors
DiagnosticId::UnexpectedEof => "E0009",
DiagnosticId::UnexpectedToken => "E0010",
DiagnosticId::InvalidSyntax => "E0010",
// Type errors
DiagnosticId::TypeMismatch => "E0001",
DiagnosticId::UnknownType => "E0002",
DiagnosticId::UnknownVariable => "E0003",
DiagnosticId::InvalidOperator => "E0004",
DiagnosticId::ArgumentCountMismatch => "E0005",
DiagnosticId::NotCallable => "E0006",
DiagnosticId::NoSuchField => "E0007",
DiagnosticId::NotIndexable => "E0008",
DiagnosticId::InvalidMapKeyType => "E0067",
// Name errors
DiagnosticId::DuplicateName => "E0011",
// HIR diagnostics
DiagnosticId::DuplicateField => "E0012",
DiagnosticId::DuplicateVariant => "E0013",
DiagnosticId::DuplicateMethod => "E0093",
DiagnosticId::DuplicateBinding => "E0094",
DiagnosticId::DuplicateAttribute => "E0014",
DiagnosticId::UnknownAttribute => "E0015",
DiagnosticId::InvalidAttributeContext => "E0016",
DiagnosticId::UnknownGeneratorProperty => "E0017",
DiagnosticId::MissingGeneratorProperty => "E0018",
DiagnosticId::InvalidGeneratorPropertyValue => "E0019",
DiagnosticId::ReservedFieldName => "E0020",
DiagnosticId::FieldNameMatchesTypeName => "E0021",
DiagnosticId::InvalidClientResponseType => "E0022",
DiagnosticId::HttpConfigNotBlock => "E0023",
DiagnosticId::UnknownHttpConfigField => "E0024",
DiagnosticId::NegativeTimeout => "E0025",
DiagnosticId::MissingProvider => "E0026",
DiagnosticId::UnknownClientProperty => "E0027",
DiagnosticId::RemapRolesNotMap
| DiagnosticId::RemapRoleValueNotString
| DiagnosticId::RemapRoleNotAllowed
| DiagnosticId::AllowedRolesEmpty
| DiagnosticId::AllowedRoleNotString => "E0044",
DiagnosticId::EmptyStrategy => "E0090",
DiagnosticId::UnknownRetryPolicy => "E0091",
DiagnosticId::InvalidStrategyElement => "E0092",
// Pattern matching errors
DiagnosticId::NonExhaustiveMatch => "E0062",
DiagnosticId::UnreachableArm => "E0063",
DiagnosticId::NonExhaustiveCatch => "E0094",
DiagnosticId::UnreachableCatchArm => "E0095",
DiagnosticId::UnknownEnumVariant => "E0064",
DiagnosticId::WatchOnNonVariable => "E0065",
DiagnosticId::WatchOnUnwatchedVariable => "E0066",
// Syntax errors
DiagnosticId::MissingSemicolon => "E0028",
DiagnosticId::MissingConditionParens => "E0030",
DiagnosticId::UnmatchedDelimiter => "E0031",
// Return expression errors
DiagnosticId::MissingReturnExpression => "E0029",
// Constraint attribute errors
DiagnosticId::InvalidConstraintSyntax => "E0032",
// Attribute value errors
DiagnosticId::InvalidAttributeArg => "E0037",
DiagnosticId::UnexpectedAttributeArg => "E0038",
DiagnosticId::ConflictingStreamAttributes => "E0101",
// Type literal errors
DiagnosticId::UnsupportedFloatLiteral => "E0033",
// Map type errors
DiagnosticId::InvalidMapArity => "E0039",
// Test diagnostics
DiagnosticId::UnknownTestProperty => "E0034",
DiagnosticId::MissingTestProperty => "E0035",
DiagnosticId::TestFieldAttribute => "E0036",
DiagnosticId::UnknownFunctionInTest => "E0088",
// Type builder diagnostics
DiagnosticId::TypeBuilderInNonTestContext => "E0040",
DiagnosticId::DuplicateTypeBuilderBlock => "E0041",
DiagnosticId::IncompleteDynamicDefinition => "E0042",
DiagnosticId::TypeBuilderSyntaxError => "E0043",
// Cycle detection diagnostics
DiagnosticId::AliasCycle => "E0068",
DiagnosticId::ClassCycle => "E0069",
// Jinja template diagnostics
DiagnosticId::JinjaUnresolvedVariable => "E0070",
DiagnosticId::JinjaFunctionReferenceWithoutCall => "E0071",
DiagnosticId::JinjaInvalidFilter => "E0072",
DiagnosticId::JinjaInvalidType => "E0073",
DiagnosticId::JinjaPropertyNotDefined => "E0074",
DiagnosticId::JinjaEnumValuePropertyAccess => "E0075",
DiagnosticId::JinjaEnumStringComparison => "E0076",
DiagnosticId::JinjaPropertyNotFoundInUnion => "E0077",
DiagnosticId::JinjaPropertyTypeMismatchInUnion => "E0078",
DiagnosticId::JinjaNonClassInUnion => "E0079",
DiagnosticId::JinjaWrongArgCount => "E0080",
DiagnosticId::JinjaMissingArg => "E0081",
DiagnosticId::JinjaUnknownArg => "E0082",
DiagnosticId::JinjaWrongArgType => "E0083",
DiagnosticId::JinjaParseError => "E0084",
DiagnosticId::JinjaUnsupportedFeature => "E0085",
DiagnosticId::JinjaInvalidSyntax => "E0086",
DiagnosticId::JinjaInvalidTest => "E0087",
// Reserved prefix errors
DiagnosticId::ReservedStreamPrefix => "E0100",
// Catch binding errors
DiagnosticId::InvalidCatchBindingType => "E0093",
// Throws contract errors
DiagnosticId::ThrowsContractViolation => "E0096",
DiagnosticId::ThrowsContractExtraneous => "E0097",
// VIR lowering errors
DiagnosticId::LoweringError => "E0089",
// Removed feature errors
DiagnosticId::InstanceofRemoved => "E0098",
}
}
}
/// Severity level of a diagnostic.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Severity {
/// An error that prevents compilation.
Error,
/// A warning that doesn't prevent compilation.
Warning,
/// Informational message.
Info,
}
/// An annotation pointing to a span in the source code.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Annotation {
/// The span this annotation refers to.
pub span: Span,
/// Message for this annotation (optional).
pub message: Option<String>,
/// Whether this is the primary annotation.
pub is_primary: bool,
}
impl Annotation {
/// Create a primary annotation with a message.
pub fn primary(span: Span, message: impl Into<String>) -> Self {
Self {
span,
message: Some(message.into()),
is_primary: true,
}
}
/// Create a primary annotation without a message.
pub fn primary_no_msg(span: Span) -> Self {
Self {
span,
message: None,
is_primary: true,
}
}
/// Create a secondary annotation with a message.
pub fn secondary(span: Span, message: impl Into<String>) -> Self {
Self {
span,
message: Some(message.into()),
is_primary: false,
}
}
}
/// Related diagnostic information (for cross-file references).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RelatedInfo {
/// The span of the related location.
pub span: Span,
/// The message describing this related location.
pub message: String,
/// Optional file path for display purposes.
pub file_path: Option<String>,
}
impl RelatedInfo {
/// Create a new related info with a span and message.
pub fn new(span: Span, message: impl Into<String>) -> Self {
Self {
span,
message: message.into(),
file_path: None,
}
}
/// Create a new related info with file path for display.
pub fn with_path(span: Span, message: impl Into<String>, path: impl Into<String>) -> Self {
Self {
span,
message: message.into(),
file_path: Some(path.into()),
}
}
}
/// A unified diagnostic that can represent any BAML compiler error.
///
/// This type is inspired by `ruff_db::Diagnostic` and enables:
/// - Centralized diagnostic collection via `Project::check()`
/// - Multi-format rendering (Ariadne for CLI, LSP types for editors)
/// - Consistent error handling across all compiler phases
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Diagnostic {
/// The diagnostic category/id.
pub id: DiagnosticId,
/// The severity level.
pub severity: Severity,
/// The main error message.
pub message: String,
/// Annotations pointing to relevant source locations.
pub annotations: Vec<Annotation>,
/// Related information (e.g., "first defined here").
pub related_info: Vec<RelatedInfo>,
/// The compiler phase that produced this diagnostic.
pub phase: DiagnosticPhase,
}
impl Diagnostic {
/// Create a new diagnostic with a single primary span.
pub fn new(id: DiagnosticId, severity: Severity, message: impl Into<String>) -> Self {
Self {
id,
severity,
message: message.into(),
annotations: Vec::new(),
related_info: Vec::new(),
phase: DiagnosticPhase::default(),
}
}
/// Create an error diagnostic.
pub fn error(id: DiagnosticId, message: impl Into<String>) -> Self {
Self::new(id, Severity::Error, message)
}
/// Create a warning diagnostic.
pub fn warning(id: DiagnosticId, message: impl Into<String>) -> Self {
Self::new(id, Severity::Warning, message)
}
/// Set the compiler phase for this diagnostic.
#[must_use]
pub fn with_phase(mut self, phase: DiagnosticPhase) -> Self {
self.phase = phase;
self
}
/// Add a primary annotation at a span with a message.
#[must_use]
pub fn with_primary(mut self, span: Span, message: impl Into<String>) -> Self {
self.annotations.push(Annotation::primary(span, message));
self
}
/// Add a primary annotation at a span using the main message.
#[must_use]
pub fn with_primary_span(mut self, span: Span) -> Self {
self.annotations
.push(Annotation::primary(span, self.message.clone()));
self
}
/// Add a secondary annotation at a span.
#[must_use]
pub fn with_secondary(mut self, span: Span, message: impl Into<String>) -> Self {
self.annotations.push(Annotation::secondary(span, message));
self
}
/// Add related information.
#[must_use]
pub fn with_related(mut self, span: Span, message: impl Into<String>) -> Self {
self.related_info.push(RelatedInfo::new(span, message));
self
}
/// Add related information with file path.
#[must_use]
pub fn with_related_path(
mut self,
span: Span,
message: impl Into<String>,
path: impl Into<String>,
) -> Self {
self.related_info
.push(RelatedInfo::with_path(span, message, path));
self
}
/// Get the error code string.
pub fn code(&self) -> &'static str {
self.id.code()
}
/// Get the primary span (first primary annotation).
pub fn primary_span(&self) -> Option<Span> {
self.annotations
.iter()
.find(|a| a.is_primary)
.map(|a| a.span)
}
/// Get the primary file ID.
pub fn file_id(&self) -> Option<FileId> {
self.primary_span().map(|s| s.file_id)
}
}
/// Trait for converting error types to the unified Diagnostic type.
pub trait ToDiagnostic {
/// Convert this error to a unified Diagnostic.
fn to_diagnostic(&self) -> Diagnostic;
}
#[cfg(test)]
mod tests {
use text_size::TextRange;
use super::*;
fn test_span() -> Span {
Span {
file_id: FileId::new(0),
range: TextRange::new(0.into(), 10.into()),
}
}
#[test]
fn test_diagnostic_builder() {
let diag = Diagnostic::error(DiagnosticId::TypeMismatch, "Expected int, found string")
.with_primary_span(test_span());
assert_eq!(diag.severity, Severity::Error);
assert_eq!(diag.code(), "E0001");
assert_eq!(diag.message, "Expected int, found string");
assert_eq!(diag.annotations.len(), 1);
assert!(diag.annotations[0].is_primary);
}
#[test]
fn test_diagnostic_with_related() {
let first_span = test_span();
let second_span = Span {
file_id: FileId::new(1),
range: TextRange::new(20.into(), 30.into()),
};
let diag = Diagnostic::error(DiagnosticId::DuplicateName, "Duplicate class 'Foo'")
.with_primary_span(second_span)
.with_related(first_span, "First defined here");
assert_eq!(diag.related_info.len(), 1);
assert_eq!(diag.related_info[0].message, "First defined here");
}
#[test]
fn test_all_error_codes() {
// Ensure all DiagnosticId variants have unique error codes
let ids = vec![
DiagnosticId::TypeMismatch,
DiagnosticId::UnknownType,
DiagnosticId::UnknownVariable,
DiagnosticId::InvalidOperator,
DiagnosticId::ArgumentCountMismatch,
DiagnosticId::NotCallable,
DiagnosticId::NoSuchField,
DiagnosticId::NotIndexable,
DiagnosticId::UnexpectedEof,
DiagnosticId::UnexpectedToken,
DiagnosticId::DuplicateName,
DiagnosticId::LoweringError,
DiagnosticId::InstanceofRemoved,
];
for id in ids {
let code = id.code();
assert!(code.starts_with('E'), "Code should start with E: {code}");
}
}
}