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
//! Runtime helpers for loading code and emitting diagnostics.

use crate::{
    CompileErrorKind, Diagnostics, Error, ErrorKind, IrErrorKind, LinkerError, QueryErrorKind,
    ResolveErrorKind, Sources, Spanned as _, Warning, WarningKind,
};
use runestick::{Location, Source, SourceId, Span, Unit, VmError, VmErrorKind};
use std::error::Error as _;
use std::fmt;
use std::fmt::Write as _;
use std::io;
use thiserror::Error;

use codespan_reporting::diagnostic::{Diagnostic, Label};
use codespan_reporting::files::{Files, SimpleFiles};
use codespan_reporting::term;
use codespan_reporting::term::termcolor::WriteColor;

pub use codespan_reporting::term::termcolor;

struct StackFrame {
    source_id: SourceId,
    span: Span,
}

/// Errors that can be raised when formatting diagnostics.
#[derive(Debug, Error)]
pub enum DiagnosticsError {
    /// Source Error.
    #[error("I/O error")]
    Io(#[from] io::Error),
    /// Source Error.
    #[error("formatting error")]
    Fmt(#[from] fmt::Error),
    /// Codespan reporting error.
    #[error("codespan reporting error")]
    CodespanReporting(#[from] codespan_reporting::files::Error),
}

/// Helper trait for emitting diagnostics.
///
/// See [load_sources](crate::load_sources) for how to use.
pub trait EmitDiagnostics {
    /// Emit diagnostics for the current type.
    fn emit_diagnostics<O>(&self, out: &mut O, sources: &Sources) -> Result<(), DiagnosticsError>
    where
        O: WriteColor;
}

/// Emit collected diagnostics.
///
/// See [load_sources](crate::load_sources) for how to use.
impl EmitDiagnostics for Diagnostics {
    fn emit_diagnostics<O>(&self, out: &mut O, sources: &Sources) -> Result<(), DiagnosticsError>
    where
        O: WriteColor,
    {
        if self.is_empty() {
            return Ok(());
        }

        let config = codespan_reporting::term::Config::default();
        let mut files = SimpleFiles::new();

        for source in sources.iter() {
            files.add(source.name(), source.as_str());
        }

        for diagnostic in self.diagnostics() {
            match diagnostic {
                crate::Diagnostic::Error(e) => {
                    error_emit_diagnostics_with(e, out, sources, &files, &config)?;
                }
                crate::Diagnostic::Warning(w) => {
                    warning_emit_diagnostics_with(w, out, sources, &files, &config)?;
                }
            }
        }

        Ok(())
    }
}

impl EmitDiagnostics for VmError {
    fn emit_diagnostics<O>(&self, out: &mut O, sources: &Sources) -> Result<(), DiagnosticsError>
    where
        O: WriteColor,
    {
        let mut files = SimpleFiles::new();

        for source in sources.iter() {
            files.add(source.name(), source.as_str());
        }

        let (error, unwound) = self.as_unwound();

        let (unit, ip, frames) = match unwound {
            Some((unit, ip, frames)) => (unit, ip, frames),
            None => {
                writeln!(
                    out,
                    "virtual machine error: {} (no diagnostics available)",
                    error
                )?;

                return Ok(());
            }
        };

        let debug_info = match unit.debug_info() {
            Some(debug_info) => debug_info,
            None => {
                writeln!(out, "virtual machine error: {} (no debug info)", error)?;
                return Ok(());
            }
        };
        let debug_inst = match debug_info.instruction_at(ip) {
            Some(debug_inst) => debug_inst,
            None => {
                writeln!(
                    out,
                    "virtual machine error: {} (no debug instruction)",
                    error
                )?;

                return Ok(());
            }
        };

        let config = codespan_reporting::term::Config::default();

        let mut labels = Vec::new();

        let source_id = debug_inst.source_id;
        let span = debug_inst.span;

        let mut backtrace = vec![StackFrame { source_id, span }];
        let (reason, notes) = match error {
            VmErrorKind::Panic { reason } => {
                labels.push(Label::primary(source_id, span.range()).with_message("panicked"));
                ("panic in runtime".to_owned(), vec![reason.to_string()])
            }
            VmErrorKind::UnsupportedBinaryOperation { lhs, rhs, op } => {
                labels.push(
                    Label::primary(source_id, span.range())
                        .with_message("in this expression".to_string()),
                );

                (
                    format!("type mismatch for operation `{}`", op),
                    vec![
                        format!("left hand side has type `{}`", lhs),
                        format!("right hand side has type `{}`", rhs),
                    ],
                )
            }
            VmErrorKind::BadArgumentCount { actual, expected } => {
                labels.push(
                    Label::primary(source_id, span.range())
                        .with_message("in this function call".to_string()),
                );

                (
                    format!("wrong number of arguments"),
                    vec![
                        format!("expected `{}`", expected),
                        format!("got `{}`", actual),
                    ],
                )
            }
            e => {
                labels.push(
                    Label::primary(source_id, span.range())
                        .with_message("in this expression".to_string()),
                );
                ("internal vm error".to_owned(), vec![e.to_string()])
            }
        };

        for ip in frames.iter().map(|v| v.ip()) {
            let debug_inst = match debug_info.instruction_at(ip) {
                Some(debug_inst) => debug_inst,
                None => {
                    writeln!(
                        out,
                        "virtual machine error: {} (no debug instruction)",
                        error
                    )?;

                    return Ok(());
                }
            };

            let source_id = debug_inst.source_id;
            let span = debug_inst.span;

            backtrace.push(StackFrame { source_id, span });
        }
        let diagnostic = Diagnostic::error()
            .with_message(reason)
            .with_labels(labels)
            .with_notes(notes);

        term::emit(out, &config, &files, &diagnostic)?;

        writeln!(out, "Callstack:")?;
        for frame in &backtrace {
            let line = files
                .line_index(frame.source_id, frame.span.start.into_usize())
                .unwrap();
            let line = files.line_number(frame.source_id, line).unwrap() - 1;
            let line_range = files.line_range(frame.source_id, line).expect("a range");
            let source = files.get(frame.source_id)?;
            let name = source.name();
            let slice = &source.source()[line_range];

            write!(out, "\t{}:{}\n\t\t{}", name, line, slice)?;
        }
        Ok(())
    }
}

/// Helper to emit diagnostics for a warning.
fn warning_emit_diagnostics_with<'a, O>(
    this: &Warning,
    out: &mut O,
    sources: &'a Sources,
    files: &'a impl Files<'a, FileId = SourceId>,
    config: &codespan_reporting::term::Config,
) -> Result<(), DiagnosticsError>
where
    O: WriteColor,
{
    let mut notes = Vec::new();
    let mut labels = Vec::new();

    let context = match this.kind() {
        WarningKind::NotUsed { span, context } => {
            labels.push(Label::primary(this.source_id(), span.range()).with_message("not used"));

            *context
        }
        WarningKind::LetPatternMightPanic { span, context } => {
            labels.push(
                Label::primary(this.source_id(), span.range())
                    .with_message("let binding might panic"),
            );

            let binding = sources
                .source_at(this.source_id())
                .and_then(|s| s.source(*span));

            if let Some(binding) = binding {
                let mut note = String::new();
                writeln!(note, "Hint: Rewrite to:")?;
                writeln!(note, "if {} {{", binding)?;
                writeln!(note, "    // ..")?;
                writeln!(note, "}}")?;
                notes.push(note);
            }

            *context
        }
        WarningKind::TemplateWithoutExpansions { span, context } => {
            labels.push(
                Label::primary(this.source_id(), span.range())
                    .with_message("template string without expansions like `${1 + 2}`"),
            );

            *context
        }
        WarningKind::RemoveTupleCallParams {
            span,
            variant,
            context,
        } => {
            labels.push(
                Label::secondary(this.source_id(), span.range())
                    .with_message("constructing this variant could be done without parentheses"),
            );

            let variant = sources
                .source_at(this.source_id())
                .and_then(|s| s.source(*variant));

            if let Some(variant) = variant {
                let mut note = String::new();
                writeln!(note, "Hint: Rewrite to `{}`", variant)?;
                notes.push(note);
            }

            *context
        }
        WarningKind::UnecessarySemiColon { span } => {
            labels.push(
                Label::primary(this.source_id(), span.range())
                    .with_message("unnecessary semicolon"),
            );

            None
        }
    };

    if let Some(context) = context {
        labels.push(
            Label::secondary(this.source_id(), context.range()).with_message("in this context"),
        );
    }

    let diagnostic = Diagnostic::warning()
        .with_message("warning")
        .with_labels(labels)
        .with_notes(notes);

    term::emit(out, &config, files, &diagnostic)?;
    Ok(())
}

/// Custom shared helper for emitting diagnostics for a single error.
fn error_emit_diagnostics_with<O>(
    this: &Error,
    out: &mut O,
    sources: &Sources,
    files: &SimpleFiles<&str, &str>,
    config: &codespan_reporting::term::Config,
) -> Result<(), DiagnosticsError>
where
    O: WriteColor,
{
    let mut labels = Vec::new();
    let mut notes = Vec::new();

    let span = match this.kind() {
        ErrorKind::Internal(message) => {
            writeln!(out, "internal error: {}", message)?;
            return Ok(());
        }
        ErrorKind::BuildError(error) => {
            writeln!(out, "build error: {}", error)?;
            return Ok(());
        }
        ErrorKind::LinkError(error) => {
            match error {
                LinkerError::MissingFunction { hash, spans } => {
                    let mut labels = Vec::new();

                    for (span, source_id) in spans {
                        labels.push(
                            Label::primary(*source_id, span.range()).with_message("called here."),
                        );
                    }

                    let diagnostic = Diagnostic::error()
                        .with_message(format!(
                            "linker error: missing function with hash `{}`",
                            hash
                        ))
                        .with_labels(labels);

                    term::emit(out, config, files, &diagnostic)?;
                }
            }

            return Ok(());
        }
        ErrorKind::ParseError(error) => error.span(),
        ErrorKind::CompileError(error) => {
            format_compile_error(
                this,
                sources,
                error.span(),
                error.kind(),
                &mut labels,
                &mut notes,
            )?;

            error.span()
        }
        ErrorKind::QueryError(error) => {
            format_query_error(
                this,
                sources,
                error.span(),
                error.kind(),
                &mut labels,
                &mut notes,
            )?;

            error.span()
        }
    };

    if let Some(e) = this.kind().source() {
        labels.push(Label::primary(this.source_id(), span.range()).with_message(e.to_string()));
    }

    let diagnostic = Diagnostic::error()
        .with_message(this.kind().to_string())
        .with_labels(labels)
        .with_notes(notes);

    term::emit(out, config, files, &diagnostic)?;
    return Ok(());

    fn format_compile_error(
        this: &Error,
        sources: &Sources,
        error_span: Span,
        kind: &CompileErrorKind,
        labels: &mut Vec<Label<SourceId>>,
        notes: &mut Vec<String>,
    ) -> fmt::Result {
        match kind {
            CompileErrorKind::QueryError { error } => {
                format_query_error(this, sources, error_span, error, labels, notes)?;
            }
            CompileErrorKind::DuplicateObjectKey { existing, object } => {
                labels.push(
                    Label::secondary(this.source_id(), existing.range())
                        .with_message("previously defined here"),
                );

                labels.push(
                    Label::secondary(this.source_id(), object.range())
                        .with_message("object being defined here"),
                );
            }
            CompileErrorKind::ModAlreadyLoaded { existing, .. } => {
                let (existing_source_id, existing_span) = *existing;

                labels.push(
                    Label::secondary(existing_source_id, existing_span.range())
                        .with_message("previously loaded here"),
                );
            }
            CompileErrorKind::ExpectedBlockSemiColon { followed_span } => {
                labels.push(
                    Label::secondary(this.source_id(), followed_span.range())
                        .with_message("because this immediately follows"),
                );

                let binding = sources
                    .source_at(this.source_id())
                    .and_then(|s| s.source(error_span));

                if let Some(binding) = binding {
                    let mut note = String::new();
                    writeln!(note, "Hint: Rewrite to `{};`", binding)?;
                    notes.push(note);
                }
            }
            CompileErrorKind::VariableMoved { moved_at, .. } => {
                labels.push(
                    Label::secondary(this.source_id(), moved_at.range()).with_message("moved here"),
                );
            }
            CompileErrorKind::CallMacroError { item, .. } => {
                notes.push(format!("Error originated in the `{}` macro", item).into());
            }
            CompileErrorKind::NestedTest { nested_span } => {
                labels.push(
                    Label::secondary(this.source_id(), nested_span.range())
                        .with_message("nested in here"),
                );
            }
            _ => (),
        }

        Ok(())
    }

    fn format_query_error(
        this: &Error,
        sources: &Sources,
        error_span: Span,
        kind: &QueryErrorKind,
        labels: &mut Vec<Label<SourceId>>,
        notes: &mut Vec<String>,
    ) -> fmt::Result {
        match kind {
            QueryErrorKind::ResolveError { error } => {
                format_resolve_error(this, sources, error_span, error, labels, notes)?;
            }
            QueryErrorKind::IrError { error } => {
                format_ir_error(this, sources, error_span, error, labels, notes)?;
            }
            QueryErrorKind::ImportCycle { path } => {
                let mut it = path.iter();
                let last = it.next_back();

                for (step, entry) in (1..).zip(it) {
                    labels.push(
                        Label::secondary(entry.location.source_id, entry.location.span.range())
                            .with_message(format!("step #{} for `{}`", step, entry.item)),
                    );
                }

                if let Some(entry) = last {
                    labels.push(
                        Label::secondary(entry.location.source_id, entry.location.span.range())
                            .with_message(format!("final step cycling back to `{}`", entry.item)),
                    );
                }
            }
            QueryErrorKind::ItemConflict {
                other: Location { source_id, span },
                ..
            } => {
                labels.push(
                    Label::secondary(*source_id, span.range())
                        .with_message("previously defined here"),
                );
            }
            QueryErrorKind::NotVisible {
                chain,
                location: Location { source_id, span },
                ..
            } => {
                for Location { source_id, span } in chain {
                    labels.push(
                        Label::secondary(*source_id, span.range()).with_message("re-exported here"),
                    );
                }

                labels
                    .push(Label::secondary(*source_id, span.range()).with_message("defined here"));
            }
            QueryErrorKind::NotVisibleMod {
                chain,
                location: Location { source_id, span },
                ..
            } => {
                for Location { source_id, span } in chain {
                    labels.push(
                        Label::secondary(*source_id, span.range()).with_message("re-exported here"),
                    );
                }

                labels.push(
                    Label::secondary(*source_id, span.range()).with_message("module defined here"),
                );
            }
            QueryErrorKind::AmbiguousItem { locations, .. } => {
                for (Location { source_id, span }, item) in locations {
                    labels.push(
                        Label::secondary(*source_id, span.range())
                            .with_message(format!("here as `{}`", item)),
                    );
                }
            }
            _ => (),
        }

        Ok(())
    }

    fn format_ir_error(
        this: &Error,
        sources: &Sources,
        error_span: Span,
        kind: &IrErrorKind,
        labels: &mut Vec<Label<SourceId>>,
        notes: &mut Vec<String>,
    ) -> fmt::Result {
        if let IrErrorKind::QueryError { error } = kind {
            format_query_error(this, sources, error_span, error, labels, notes)?;
        }

        Ok(())
    }

    fn format_resolve_error(
        _: &Error,
        _: &Sources,
        _: Span,
        _: &ResolveErrorKind,
        _: &mut Vec<Label<SourceId>>,
        _: &mut Vec<String>,
    ) -> fmt::Result {
        Ok(())
    }
}

impl EmitDiagnostics for Error {
    fn emit_diagnostics<O>(&self, out: &mut O, sources: &Sources) -> Result<(), DiagnosticsError>
    where
        O: WriteColor,
    {
        let config = codespan_reporting::term::Config::default();

        let mut files = SimpleFiles::new();

        for source in sources.iter() {
            files.add(source.name(), source.as_str());
        }

        error_emit_diagnostics_with(self, out, sources, &files, &config)
    }
}

/// Get the line number and source line for the given source and span.
pub fn line_for(source: &Source, span: Span) -> Option<(usize, &str, Span)> {
    let line_starts = source.line_starts();

    let line = match line_starts.binary_search(&span.start.into_usize()) {
        Ok(n) => n,
        Err(n) => n.saturating_sub(1),
    };

    let start = *line_starts.get(line)?;
    let end = line.checked_add(1)?;

    let s = if let Some(end) = line_starts.get(end) {
        source.get(start..*end)?
    } else {
        source.get(start..)?
    };

    Some((
        line,
        s,
        Span::new(
            span.start.into_usize() - start,
            span.end.into_usize() - start,
        ),
    ))
}

/// Trait to dump the instructions of a unit to the given writer.
///
/// This is implemented for [Unit].
pub trait DumpInstructions {
    /// Dump the instructions of the current unit to the given writer.
    fn dump_instructions<O>(
        &self,
        out: &mut O,
        sources: &Sources,
        with_source: bool,
    ) -> io::Result<()>
    where
        O: WriteColor;
}

impl DumpInstructions for Unit {
    fn dump_instructions<O>(
        &self,
        out: &mut O,
        sources: &Sources,
        with_source: bool,
    ) -> io::Result<()>
    where
        O: WriteColor,
    {
        let mut first_function = true;

        for (n, inst) in self.iter_instructions().enumerate() {
            let debug = self.debug_info().and_then(|d| d.instruction_at(n));

            if let Some((hash, signature)) = self.debug_info().and_then(|d| d.function_at(n)) {
                if !std::mem::take(&mut first_function) {
                    writeln!(out)?;
                }

                writeln!(out, "fn {} ({}):", signature, hash)?;
            }

            if with_source {
                if let Some((source, span)) =
                    debug.and_then(|d| sources.get(d.source_id).map(|s| (s, d.span)))
                {
                    source.emit_source_line(out, span)?;
                }
            }

            if let Some(label) = debug.and_then(|d| d.label.as_ref()) {
                writeln!(out, "{}:", label)?;
            }

            write!(out, "  {:04} = {}", n, inst)?;

            if let Some(comment) = debug.and_then(|d| d.comment.as_ref()) {
                write!(out, " // {}", comment)?;
            }

            writeln!(out)?;
        }

        Ok(())
    }
}

/// Helper trait to emit source code locations.
///
/// These are implemented for [Source], so that you can print diagnostics about
/// a source conveniently.
pub trait EmitSource {
    /// Emit the source location as a single line of the given writer.
    fn emit_source_line<O>(&self, out: &mut O, span: Span) -> io::Result<()>
    where
        O: WriteColor;
}

impl EmitSource for Source {
    fn emit_source_line<O>(&self, out: &mut O, span: Span) -> io::Result<()>
    where
        O: WriteColor,
    {
        let mut highlight = termcolor::ColorSpec::new();
        highlight.set_fg(Some(termcolor::Color::Blue));

        let diagnostics = line_for(self, span);

        if let Some((count, line, span)) = diagnostics {
            let line = line.trim_end();
            let end = usize::min(span.end.into_usize(), line.len());

            let before = &line[0..span.start.into_usize()];
            let inner = &line[span.start.into_usize()..end];
            let after = &line[end..];

            write!(out, "  {}:{: <3} - {}", self.name(), count + 1, before,)?;

            out.set_color(&highlight)?;
            write!(out, "{}", inner)?;
            out.reset()?;
            write!(out, "{}", after)?;

            if span.end != end {
                write!(out, " .. trimmed")?;
            }

            writeln!(out)?;
        }

        Ok(())
    }
}