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

use crate::{CompileError, LoadError, LoadErrorKind, WarningKind, Warnings};
use runestick::{LinkerError, Unit, VmError};
use std::error::Error as _;
use std::fmt;
use std::io;
use thiserror::Error;

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

pub use codespan_reporting::term::termcolor;

/// 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),
}

/// Emit warning diagnostics.
///
/// See [load_path](crate::load_path) for how to use.
pub fn emit_warning_diagnostics<O>(
    out: &mut O,
    warnings: &Warnings,
    unit: &Unit,
) -> Result<(), DiagnosticsError>
where
    O: WriteColor,
{
    use std::fmt::Write as _;

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

    if let Some(debug_info) = unit.debug_info() {
        for (source_id, source) in debug_info.sources() {
            let file_id = files.add(source.name(), source.as_str());
            debug_assert!(file_id == source_id);
        }
    }

    let mut labels = Vec::new();
    let mut notes = Vec::new();

    for w in warnings {
        let context = match &w.kind {
            WarningKind::NotUsed { span, context } => {
                labels.push(
                    Label::primary(w.source_id, span.start..span.end)
                        .with_message("value not used"),
                );

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

                let binding = unit
                    .debug_info()
                    .and_then(|dbg| dbg.source_at(w.source_id))
                    .and_then(|s| s.source(*span));

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

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

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

                let variant = unit
                    .debug_info()
                    .and_then(|dbg| dbg.source_at(w.source_id))
                    .and_then(|s| s.source(*variant));

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

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

                None
            }
        };

        if let Some(context) = context {
            labels.push(
                Label::secondary(w.source_id, context.start..context.end)
                    .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(())
}

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

impl EmitDiagnostics for VmError {
    fn emit_diagnostics<O>(self, out: &mut O) -> Result<(), DiagnosticsError>
    where
        O: WriteColor,
    {
        let (error, unwound) = self.into_unwound();

        let (unit, ip) = match unwound {
            Some((unit, ip)) => (unit, ip),
            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 source = match debug_info.source_at(debug_inst.source_id) {
            Some(source) => source,
            None => {
                writeln!(
                    out,
                    "virtual machine error: {} (no source available)",
                    error
                )?;

                return Ok(());
            }
        };

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

        let mut files = SimpleFiles::new();
        let id = files.add(source.name(), source.as_str());

        let mut labels = Vec::new();
        let span = debug_inst.span;

        labels.push(Label::primary(id, span.start..span.end).with_message(error.to_string()));

        let diagnostic = Diagnostic::error()
            .with_message("virtual machine error")
            .with_labels(labels);

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

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

        let mut labels = Vec::new();

        let (span, source) = match self.kind() {
            LoadErrorKind::ReadFile { error, path } => {
                writeln!(out, "failed to read file: {}: {}", path.display(), error)?;
                return Ok(());
            }
            LoadErrorKind::LinkError {
                errors,
                code_source: source,
            } => {
                let mut files = SimpleFiles::new();
                let source_id = files.add(source.name(), source.as_str());

                for error in errors {
                    match error {
                        LinkerError::MissingFunction { hash, spans } => {
                            let mut labels = Vec::new();

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

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

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

                return Ok(());
            }
            LoadErrorKind::CompileError {
                error,
                code_source: source,
            } => {
                let span = match error {
                    CompileError::ReturnLocalReferences {
                        block,
                        references_at,
                        span,
                        ..
                    } => {
                        for ref_span in references_at {
                            if span.overlaps(*ref_span) {
                                continue;
                            }

                            labels.push(
                                Label::secondary(0, ref_span.start..ref_span.end)
                                    .with_message("reference created here"),
                            );
                        }

                        labels.push(
                            Label::secondary(0, block.start..block.end)
                                .with_message("block returned from"),
                        );

                        *span
                    }
                    CompileError::DuplicateObjectKey {
                        span,
                        existing,
                        object,
                    } => {
                        labels.push(
                            Label::secondary(0, existing.start..existing.end)
                                .with_message("previously defined here"),
                        );

                        labels.push(
                            Label::secondary(0, object.start..object.end)
                                .with_message("object being defined here"),
                        );

                        *span
                    }
                    error => error.span(),
                };

                (span, source)
            }
        };

        let mut files = SimpleFiles::new();
        let source_id = files.add(source.name(), source.as_str());

        if let Some(e) = self.source() {
            labels
                .push(Label::primary(source_id, span.start..span.end).with_message(e.to_string()));
        }

        let diagnostic = Diagnostic::error()
            .with_message(self.to_string())
            .with_labels(labels);

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