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
use crate::code_model::StructKind;
use crate::in_file::InFile;
use crate::{FileId, HirDatabase, IntTy, Name, Ty};
use mun_syntax::{ast, AstPtr, SmolStr, SyntaxNode, SyntaxNodePtr, TextRange};
use std::{any::Any, fmt};

/// Diagnostic defines hir API for errors and warnings.
///
/// It is used as a `dyn` object, which you can downcast to concrete diagnostics. DiagnosticSink
/// are structured, meaning that they include rich information which can be used by IDE to create
/// fixes.
///
/// Internally, various subsystems of HIR produce diagnostics specific to a subsystem (typically,
/// an `enum`), which are safe to store in salsa but do not include source locations. Such internal
/// diagnostics are transformed into an instance of `Diagnostic` on demand.
pub trait Diagnostic: Any + Send + Sync + fmt::Debug + 'static {
    fn message(&self) -> String;
    fn source(&self) -> InFile<SyntaxNodePtr>;
    fn highlight_range(&self) -> TextRange {
        self.source().value.range()
    }
    fn as_any(&self) -> &(dyn Any + Send + 'static);
}

pub trait AstDiagnostic {
    type AST;
    fn ast(&self, db: &dyn HirDatabase) -> Self::AST;
}

impl dyn Diagnostic {
    pub fn syntax_node(&self, db: &dyn HirDatabase) -> SyntaxNode {
        let node = db.parse(self.source().file_id).syntax_node();
        self.source().value.to_node(&node)
    }

    pub fn downcast_ref<D: Diagnostic>(&self) -> Option<&D> {
        self.as_any().downcast_ref()
    }
}

type DiagnosticCallback<'a> = Box<dyn FnMut(&dyn Diagnostic) -> Result<(), ()> + 'a>;

pub struct DiagnosticSink<'a> {
    callbacks: Vec<DiagnosticCallback<'a>>,
    default_callback: Box<dyn FnMut(&dyn Diagnostic) + 'a>,
}

impl<'a> DiagnosticSink<'a> {
    pub fn new(cb: impl FnMut(&dyn Diagnostic) + 'a) -> DiagnosticSink<'a> {
        DiagnosticSink {
            callbacks: Vec::new(),
            default_callback: Box::new(cb),
        }
    }

    pub fn on<D: Diagnostic, F: FnMut(&D) + 'a>(mut self, mut cb: F) -> DiagnosticSink<'a> {
        let cb = move |diag: &dyn Diagnostic| match diag.downcast_ref::<D>() {
            Some(d) => {
                cb(d);
                Ok(())
            }
            None => Err(()),
        };
        self.callbacks.push(Box::new(cb));
        self
    }

    pub(crate) fn push(&mut self, d: impl Diagnostic) {
        let d: &dyn Diagnostic = &d;
        for cb in self.callbacks.iter_mut() {
            match cb(d) {
                Ok(()) => return,
                Err(()) => (),
            }
        }
        (self.default_callback)(d)
    }
}

#[derive(Debug)]
pub struct UnresolvedValue {
    pub file: FileId,
    pub expr: SyntaxNodePtr,
}

impl Diagnostic for UnresolvedValue {
    fn message(&self) -> String {
        "undefined value".to_string()
    }

    fn source(&self) -> InFile<SyntaxNodePtr> {
        InFile::new(self.file, self.expr)
    }

    fn as_any(&self) -> &(dyn Any + Send + 'static) {
        self
    }
}

#[derive(Debug)]
pub struct UnresolvedType {
    pub file: FileId,
    pub type_ref: AstPtr<ast::TypeRef>,
}

impl Diagnostic for UnresolvedType {
    fn message(&self) -> String {
        "undefined type".to_string()
    }

    fn source(&self) -> InFile<SyntaxNodePtr> {
        InFile::new(self.file, self.type_ref.syntax_node_ptr())
    }

    fn as_any(&self) -> &(dyn Any + Send + 'static) {
        self
    }
}

#[derive(Debug)]
pub struct CyclicType {
    pub file: FileId,
    pub type_ref: AstPtr<ast::TypeRef>,
}

impl Diagnostic for CyclicType {
    fn message(&self) -> String {
        "cyclic type".to_string()
    }

    fn source(&self) -> InFile<SyntaxNodePtr> {
        InFile::new(self.file, self.type_ref.syntax_node_ptr())
    }

    fn as_any(&self) -> &(dyn Any + Send + 'static) {
        self
    }
}

#[derive(Debug)]
pub struct PrivateAccess {
    pub file: FileId,
    pub expr: SyntaxNodePtr,
}

impl Diagnostic for PrivateAccess {
    fn message(&self) -> String {
        "access of private type".to_string()
    }

    fn source(&self) -> InFile<SyntaxNodePtr> {
        InFile::new(self.file, self.expr)
    }

    fn as_any(&self) -> &(dyn Any + Send + 'static) {
        self
    }
}

#[derive(Debug)]
pub struct ExpectedFunction {
    pub file: FileId,
    pub expr: SyntaxNodePtr,
    pub found: Ty,
}

impl Diagnostic for ExpectedFunction {
    fn message(&self) -> String {
        "expected function type".to_string()
    }

    fn source(&self) -> InFile<SyntaxNodePtr> {
        InFile::new(self.file, self.expr)
    }

    fn as_any(&self) -> &(dyn Any + Send + 'static) {
        self
    }
}

#[derive(Debug)]
pub struct ParameterCountMismatch {
    pub file: FileId,
    pub expr: SyntaxNodePtr,
    pub expected: usize,
    pub found: usize,
}

impl Diagnostic for ParameterCountMismatch {
    fn message(&self) -> String {
        format!(
            "this function takes {} parameters but {} parameters was supplied",
            self.expected, self.found
        )
    }

    fn source(&self) -> InFile<SyntaxNodePtr> {
        InFile::new(self.file, self.expr)
    }

    fn as_any(&self) -> &(dyn Any + Send + 'static) {
        self
    }
}

#[derive(Debug)]
pub struct MismatchedType {
    pub file: FileId,
    pub expr: SyntaxNodePtr,
    pub expected: Ty,
    pub found: Ty,
}

impl Diagnostic for MismatchedType {
    fn message(&self) -> String {
        "mismatched type".to_string()
    }

    fn source(&self) -> InFile<SyntaxNodePtr> {
        InFile::new(self.file, self.expr)
    }

    fn as_any(&self) -> &(dyn Any + Send + 'static) {
        self
    }
}

#[derive(Debug)]
pub struct IncompatibleBranch {
    pub file: FileId,
    pub if_expr: SyntaxNodePtr,
    pub expected: Ty,
    pub found: Ty,
}

impl Diagnostic for IncompatibleBranch {
    fn message(&self) -> String {
        "mismatched branches".to_string()
    }

    fn source(&self) -> InFile<SyntaxNodePtr> {
        InFile::new(self.file, self.if_expr)
    }

    fn as_any(&self) -> &(dyn Any + Send + 'static) {
        self
    }
}

#[derive(Debug)]
pub struct InvalidLHS {
    /// The file that contains the expressions
    pub file: FileId,

    /// The expression containing the `lhs`
    pub expr: SyntaxNodePtr,

    /// The left-hand side of the expression.
    pub lhs: SyntaxNodePtr,
}

impl Diagnostic for InvalidLHS {
    fn message(&self) -> String {
        "invalid left hand side of expression".to_string()
    }

    fn source(&self) -> InFile<SyntaxNodePtr> {
        InFile::new(self.file, self.lhs)
    }

    fn as_any(&self) -> &(dyn Any + Send + 'static) {
        self
    }
}

#[derive(Debug)]
pub struct MissingElseBranch {
    pub file: FileId,
    pub if_expr: SyntaxNodePtr,
    pub found: Ty,
}

impl Diagnostic for MissingElseBranch {
    fn message(&self) -> String {
        "missing else branch".to_string()
    }

    fn source(&self) -> InFile<SyntaxNodePtr> {
        InFile::new(self.file, self.if_expr)
    }

    fn as_any(&self) -> &(dyn Any + Send + 'static) {
        self
    }
}

#[derive(Debug)]
pub struct CannotApplyBinaryOp {
    pub file: FileId,
    pub expr: SyntaxNodePtr,
    pub lhs: Ty,
    pub rhs: Ty,
}

impl Diagnostic for CannotApplyBinaryOp {
    fn message(&self) -> String {
        "cannot apply binary operator".to_string()
    }

    fn source(&self) -> InFile<SyntaxNodePtr> {
        InFile::new(self.file, self.expr)
    }

    fn as_any(&self) -> &(dyn Any + Send + 'static) {
        self
    }
}

#[derive(Debug)]
pub struct CannotApplyUnaryOp {
    pub file: FileId,
    pub expr: SyntaxNodePtr,
    pub ty: Ty,
}

impl Diagnostic for CannotApplyUnaryOp {
    fn message(&self) -> String {
        "cannot apply unary operator".to_string()
    }

    fn source(&self) -> InFile<SyntaxNodePtr> {
        InFile::new(self.file, self.expr)
    }

    fn as_any(&self) -> &(dyn Any + Send + 'static) {
        self
    }
}

#[derive(Debug)]
pub struct DuplicateDefinition {
    pub file: FileId,
    pub name: String,
    pub first_definition: SyntaxNodePtr,
    pub definition: SyntaxNodePtr,
}

impl Diagnostic for DuplicateDefinition {
    fn message(&self) -> String {
        format!("the name `{}` is defined multiple times", self.name)
    }

    fn source(&self) -> InFile<SyntaxNodePtr> {
        InFile::new(self.file, self.definition)
    }

    fn as_any(&self) -> &(dyn Any + Send + 'static) {
        self
    }
}

#[derive(Debug)]
pub struct ReturnMissingExpression {
    pub file: FileId,
    pub return_expr: SyntaxNodePtr,
}

impl Diagnostic for ReturnMissingExpression {
    fn message(&self) -> String {
        "`return;` in a function whose return type is not `()`".to_owned()
    }

    fn source(&self) -> InFile<SyntaxNodePtr> {
        InFile::new(self.file, self.return_expr)
    }

    fn as_any(&self) -> &(dyn Any + Send + 'static) {
        self
    }
}

#[derive(Debug)]
pub struct BreakOutsideLoop {
    pub file: FileId,
    pub break_expr: SyntaxNodePtr,
}

impl Diagnostic for BreakOutsideLoop {
    fn message(&self) -> String {
        "`break` outside of a loop".to_owned()
    }

    fn source(&self) -> InFile<SyntaxNodePtr> {
        InFile::new(self.file, self.break_expr)
    }

    fn as_any(&self) -> &(dyn Any + Send + 'static) {
        self
    }
}

#[derive(Debug)]
pub struct BreakWithValueOutsideLoop {
    pub file: FileId,
    pub break_expr: SyntaxNodePtr,
}

impl Diagnostic for BreakWithValueOutsideLoop {
    fn message(&self) -> String {
        "`break` with value can only appear in a `loop`".to_owned()
    }

    fn source(&self) -> InFile<SyntaxNodePtr> {
        InFile::new(self.file, self.break_expr)
    }

    fn as_any(&self) -> &(dyn Any + Send + 'static) {
        self
    }
}

#[derive(Debug)]
pub struct AccessUnknownField {
    pub file: FileId,
    pub expr: SyntaxNodePtr,
    pub receiver_ty: Ty,
    pub name: Name,
}

impl Diagnostic for AccessUnknownField {
    fn message(&self) -> String {
        "attempted to access a non-existent field in a struct.".to_string()
    }

    fn source(&self) -> InFile<SyntaxNodePtr> {
        InFile::new(self.file, self.expr)
    }

    fn as_any(&self) -> &(dyn Any + Send + 'static) {
        self
    }
}

#[derive(Debug)]
pub struct FieldCountMismatch {
    pub file: FileId,
    pub expr: SyntaxNodePtr,
    pub expected: usize,
    pub found: usize,
}

impl Diagnostic for FieldCountMismatch {
    fn message(&self) -> String {
        format!(
            "this tuple struct literal has {} field{} but {} field{} supplied",
            self.expected,
            if self.expected == 1 { "" } else { "s" },
            self.found,
            if self.found == 1 { " was" } else { "s were" },
        )
    }

    fn source(&self) -> InFile<SyntaxNodePtr> {
        InFile::new(self.file, self.expr)
    }

    fn as_any(&self) -> &(dyn Any + Send + 'static) {
        self
    }
}

#[derive(Debug)]
pub struct MissingFields {
    pub file: FileId,
    pub fields: SyntaxNodePtr,
    pub struct_ty: Ty,
    pub field_names: Vec<Name>,
}

impl Diagnostic for MissingFields {
    fn message(&self) -> String {
        use std::fmt::Write;
        let mut message = "missing record fields:\n".to_string();
        for field in &self.field_names {
            writeln!(message, "- {}", field).unwrap();
        }
        message
    }

    fn source(&self) -> InFile<SyntaxNodePtr> {
        InFile::new(self.file, self.fields)
    }

    fn as_any(&self) -> &(dyn Any + Send + 'static) {
        self
    }
}

#[derive(Debug)]
pub struct MismatchedStructLit {
    pub file: FileId,
    pub expr: SyntaxNodePtr,
    pub expected: StructKind,
    pub found: StructKind,
}

impl Diagnostic for MismatchedStructLit {
    fn message(&self) -> String {
        format!(
            "mismatched struct literal kind. expected `{}`, found `{}`",
            self.expected, self.found
        )
    }

    fn source(&self) -> InFile<SyntaxNodePtr> {
        InFile::new(self.file, self.expr)
    }

    fn as_any(&self) -> &(dyn Any + Send + 'static) {
        self
    }
}

#[derive(Debug)]
pub struct NoFields {
    pub file: FileId,
    pub receiver_expr: SyntaxNodePtr,
    pub found: Ty,
}

impl Diagnostic for NoFields {
    fn message(&self) -> String {
        "attempted to access a field on a primitive type.".to_string()
    }

    fn source(&self) -> InFile<SyntaxNodePtr> {
        InFile::new(self.file, self.receiver_expr)
    }

    fn as_any(&self) -> &(dyn Any + Send + 'static) {
        self
    }
}
#[derive(Debug)]
pub struct NoSuchField {
    pub file: FileId,
    pub field: SyntaxNodePtr,
}

impl Diagnostic for NoSuchField {
    fn message(&self) -> String {
        "no such field".to_string()
    }

    fn source(&self) -> InFile<SyntaxNodePtr> {
        InFile::new(self.file, self.field)
    }

    fn as_any(&self) -> &(dyn Any + Send + 'static) {
        self
    }
}

#[derive(Debug)]
pub struct PossiblyUninitializedVariable {
    pub file: FileId,
    pub pat: SyntaxNodePtr,
}

impl Diagnostic for PossiblyUninitializedVariable {
    fn message(&self) -> String {
        "use of possibly-uninitialized variable".to_string()
    }

    fn source(&self) -> InFile<SyntaxNodePtr> {
        InFile::new(self.file, self.pat)
    }

    fn as_any(&self) -> &(dyn Any + Send + 'static) {
        self
    }
}

#[derive(Debug)]
pub struct ExternCannotHaveBody {
    pub func: InFile<SyntaxNodePtr>,
}

impl Diagnostic for ExternCannotHaveBody {
    fn message(&self) -> String {
        "extern functions cannot have bodies".to_string()
    }

    fn source(&self) -> InFile<SyntaxNodePtr> {
        self.func
    }

    fn as_any(&self) -> &(dyn Any + Send + 'static) {
        self
    }
}

#[derive(Debug)]
pub struct ExternNonPrimitiveParam {
    pub param: InFile<SyntaxNodePtr>,
}

impl Diagnostic for ExternNonPrimitiveParam {
    fn message(&self) -> String {
        "extern functions can only have primitives as parameter- and return types".to_string()
    }

    fn source(&self) -> InFile<SyntaxNodePtr> {
        self.param
    }

    fn as_any(&self) -> &(dyn Any + Send + 'static) {
        self
    }
}

/// An error that is emitted if a literal is too large to even parse
#[derive(Debug)]
pub struct IntLiteralTooLarge {
    pub literal: InFile<AstPtr<ast::Literal>>,
}

impl Diagnostic for IntLiteralTooLarge {
    fn message(&self) -> String {
        "int literal is too large".to_owned()
    }

    fn source(&self) -> InFile<SyntaxNodePtr> {
        self.literal.map(|ptr| ptr.into())
    }

    fn as_any(&self) -> &(dyn Any + Send + 'static) {
        self
    }
}

/// An error that is emitted if a literal is too large for its suffix
#[derive(Debug)]
pub struct LiteralOutOfRange {
    pub literal: InFile<AstPtr<ast::Literal>>,
    pub int_ty: IntTy,
}

impl Diagnostic for LiteralOutOfRange {
    fn message(&self) -> String {
        format!("literal out of range for `{}`", self.int_ty.as_str())
    }

    fn source(&self) -> InFile<SyntaxNodePtr> {
        self.literal.map(|ptr| ptr.into())
    }

    fn as_any(&self) -> &(dyn Any + Send + 'static) {
        self
    }
}

/// An error that is emitted for a literal with an invalid suffix (e.g. `123_foo`)
#[derive(Debug)]
pub struct InvalidLiteralSuffix {
    pub literal: InFile<AstPtr<ast::Literal>>,
    pub suffix: SmolStr,
}

impl Diagnostic for InvalidLiteralSuffix {
    fn message(&self) -> String {
        format!("invalid suffix `{}`", self.suffix)
    }

    fn source(&self) -> InFile<SyntaxNodePtr> {
        self.literal.map(|ptr| ptr.into())
    }

    fn as_any(&self) -> &(dyn Any + Send + 'static) {
        self
    }
}

/// An error that is emitted for a literal with a floating point suffix with a non 10 base (e.g.
/// `0x123_f32`)
#[derive(Debug)]
pub struct InvalidFloatingPointLiteral {
    pub literal: InFile<AstPtr<ast::Literal>>,
    pub base: u32,
}

impl Diagnostic for InvalidFloatingPointLiteral {
    fn message(&self) -> String {
        match self.base {
            2 => "binary float literal is not supported".to_owned(),
            8 => "octal float literal is not supported".to_owned(),
            16 => "hexadecimal float literal is not supported".to_owned(),
            _ => "unsupported base for floating pointer literal".to_owned(),
        }
    }

    fn source(&self) -> InFile<SyntaxNodePtr> {
        self.literal.map(|ptr| ptr.into())
    }

    fn as_any(&self) -> &(dyn Any + Send + 'static) {
        self
    }
}

/// An error that is emitted for a malformed literal (e.g. `0b22222`)
#[derive(Debug)]
pub struct InvalidLiteral {
    pub literal: InFile<AstPtr<ast::Literal>>,
}

impl Diagnostic for InvalidLiteral {
    fn message(&self) -> String {
        "invalid literal value".to_owned()
    }

    fn source(&self) -> InFile<SyntaxNodePtr> {
        self.literal.map(|ptr| ptr.into())
    }

    fn as_any(&self) -> &(dyn Any + Send + 'static) {
        self
    }
}

#[derive(Debug)]
pub struct FreeTypeAliasWithoutTypeRef {
    pub type_alias_def: InFile<SyntaxNodePtr>,
}

impl Diagnostic for FreeTypeAliasWithoutTypeRef {
    fn message(&self) -> String {
        "free type alias without type ref".to_string()
    }

    fn source(&self) -> InFile<SyntaxNodePtr> {
        self.type_alias_def
    }

    fn as_any(&self) -> &(dyn Any + Send + 'static) {
        self
    }
}

#[derive(Debug)]
pub struct UnresolvedImport {
    pub use_tree: InFile<AstPtr<ast::UseTree>>,
}

impl Diagnostic for UnresolvedImport {
    fn message(&self) -> String {
        "unresolved import".to_string()
    }

    fn source(&self) -> InFile<SyntaxNodePtr> {
        self.use_tree.map(Into::into)
    }

    fn as_any(&self) -> &(dyn Any + Send) {
        self
    }
}

#[derive(Debug)]
pub struct ImportDuplicateDefinition {
    pub use_tree: InFile<AstPtr<ast::UseTree>>,
}

impl Diagnostic for ImportDuplicateDefinition {
    fn message(&self) -> String {
        "a second item with the same name imported. Try to use an alias.".to_string()
    }

    fn source(&self) -> InFile<SyntaxNodePtr> {
        self.use_tree.map(Into::into)
    }

    fn as_any(&self) -> &(dyn Any + Send) {
        self
    }
}