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
#![warn(
    clippy::print_stdout,
    clippy::unimplemented,
    clippy::doc_markdown,
    clippy::items_after_statements,
    clippy::match_same_arms,
    clippy::similar_names,
    clippy::single_match_else,
    clippy::use_self,
    clippy::use_debug
)]

//! The diagnostics object controls the output of warnings and errors generated
//! by the compiler during the lexing, parsing and semantic analysis phases.
//! It also tracks the number of warnings and errors generated for flow control.
//!
//! This implementation is NOT thread-safe. Messages from different threads may
//! be interleaved.
use asciifile::{MaybeSpanned, Span, Spanned};
use failure::Error;
use std::{ascii::escape_default, cell::RefCell, collections::HashMap, fmt::Display};
use termcolor::{Color, WriteColor};
use utils::color::ColorOutput;

pub mod lint;

pub fn u8_to_printable_representation(byte: u8) -> String {
    let bytes = escape_default(byte).collect::<Vec<u8>>();
    let rep = unsafe { std::str::from_utf8_unchecked(&bytes) };
    rep.to_owned()
}

/// This abstraction allows us to call the diagnostics API with pretty
/// much everything.
///
/// The following examples are all equivalent and will print a warning
/// without a source code snippet below the message:
///
/// ```rust,ignore
/// context.diagnostics.warning(&"Something went wrong");
/// context
///     .diagnostics
///     .warning(&WithoutSpan("Something went wrong"));
/// ```
///
/// The following examples will print a message with a source code
/// snippet. Note that all errors generated by the compiler are
/// a `Spanned<_, Fail>` and can therefore be directly passed to
/// the diagnostics API.
///
/// ```rust,ignore
/// // `lexer_error` is the `Err` returned by `Lexer::next`
/// context.diagnostics.error(&lexer_error);
/// // `span` is some `asciifile::Span`
/// context.diagnostics.error({
///     span: span,
///     data: "something went wrong"
/// });
/// ```
pub trait Printable<'a, 'b> {
    fn as_maybe_spanned(&'b self) -> MaybeSpanned<'a, &'b dyn Display>;
}

// TODO: implementing on `str` (which is what you would like to do, to
// support calls with warning("aa") instead of warning(&"aa").
impl<'a, 'b> Printable<'a, 'b> for &'b str {
    fn as_maybe_spanned(&'b self) -> MaybeSpanned<'a, &'b dyn Display> {
        MaybeSpanned::WithoutSpan(self)
    }
}

impl<'a, 'b, T: Display + 'b> Printable<'a, 'b> for Spanned<'a, T> {
    fn as_maybe_spanned(&'b self) -> MaybeSpanned<'a, &'b dyn Display> {
        MaybeSpanned::WithSpan(Spanned {
            span: self.span,
            data: &self.data,
        })
    }
}

impl<'a, 'b, T: Display + 'b> Printable<'a, 'b> for MaybeSpanned<'a, T> {
    fn as_maybe_spanned(&'b self) -> MaybeSpanned<'a, &'b dyn Display> {
        match self {
            MaybeSpanned::WithSpan(ref spanned) => MaybeSpanned::WithSpan(Spanned {
                span: spanned.span,
                data: &spanned.data,
            }),
            MaybeSpanned::WithoutSpan(ref data) => MaybeSpanned::WithoutSpan(data),
        }
    }
}

/// Width of tabs in error and warning messages
const TAB_WIDTH: usize = 4;

/// Color used for rendering line numbers, escape sequences
/// and others...
const HIGHLIGHT_COLOR: Option<Color> = Some(Color::Cyan);

// TODO reimplement line truncation

/// Instead of writing errors, warnings and lints generated in the different
/// compiler stages directly to stdout, they are collected in this object.
///
/// This has several advantages:
/// - the output level can be adapted by users.
/// - we have a single source responsible for formatting compiler messages.
pub struct Diagnostics {
    message_count: RefCell<HashMap<MessageLevel, usize>>,
    writer: RefCell<Box<dyn WriteColor>>,
}

impl Diagnostics {
    pub fn new(writer: Box<dyn WriteColor>) -> Self {
        Self {
            writer: RefCell::new(writer),
            message_count: RefCell::new(HashMap::new()),
        }
    }

    /// True when an error message was emitted, false
    /// if only warnings were emitted.
    pub fn errored(&self) -> bool {
        self.message_count
            .borrow()
            .get(&MessageLevel::Error)
            .is_some()
    }

    pub fn count(&self, level: MessageLevel) -> usize {
        self.message_count
            .borrow()
            .get(&level)
            .cloned()
            .unwrap_or(0)
    }

    pub fn write_statistics(&self) {
        let mut writer = self.writer.borrow_mut();
        let mut output = ColorOutput::new(&mut **writer);

        output.set_bold(true);

        if self.errored() {
            output.set_color(MessageLevel::Error.color());
            writeln!(
                output.writer(),
                "Compilation aborted due to {}",
                match self.count(MessageLevel::Error) {
                    1 => "an error".to_string(),
                    n => format!("{} errors", n),
                }
            )
            .ok();
        } else {
            output.set_color(Some(Color::Green));
            writeln!(
                output.writer(),
                "Compilation finished successfully {}",
                match self.count(MessageLevel::Warning) {
                    0 => "without warnings".to_string(),
                    1 => "with a warning".to_string(),
                    n => format!("with {} warnings", n),
                }
            )
            .ok();
        }
    }

    /// Generate an error or a warning that is printed to the
    /// writer given in the `new` constructor. Most of the time
    /// this will be stderr.
    pub fn emit(&self, level: MessageLevel, kind: MaybeSpanned<'_, &dyn Display>) {
        self.increment_level_count(level);
        let mut writer = self.writer.borrow_mut();
        let msg = Message { level, kind };

        // `ok()` surpresses io error
        msg.write(&mut **writer).ok();
    }

    #[allow(dead_code)]
    pub fn warning<'a, 'b, T: Printable<'a, 'b> + ?Sized>(&self, kind: &'b T) {
        self.emit(MessageLevel::Warning, kind.as_maybe_spanned())
    }

    #[allow(dead_code)]
    pub fn error<'a, 'b, T: Printable<'a, 'b> + ?Sized>(&self, kind: &'b T) {
        self.emit(MessageLevel::Error, kind.as_maybe_spanned())
    }

    #[allow(dead_code)]
    pub fn info<'a, 'b, T: Printable<'a, 'b> + ?Sized>(&self, kind: &'b T) {
        self.emit(MessageLevel::Info, kind.as_maybe_spanned())
    }

    fn increment_level_count(&self, level: MessageLevel) {
        let mut message_count = self.message_count.borrow_mut();
        let counter = message_count.entry(level).or_insert(0);
        *counter += 1;
    }
}

#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum MessageLevel {
    Error,
    Warning,
    Info,
    Allow,
}

impl MessageLevel {
    fn color(self) -> Option<Color> {
        // Don't be confused by the return type.
        // `None` means default color in the colorterm
        // crate!
        match self {
            MessageLevel::Error => Some(Color::Red),
            MessageLevel::Warning => Some(Color::Yellow),
            MessageLevel::Info => Some(Color::Cyan),
            MessageLevel::Allow => None,
        }
    }

    fn name(&self) -> &str {
        match self {
            MessageLevel::Error => "error",
            MessageLevel::Warning => "warning",
            MessageLevel::Info => "info",
            MessageLevel::Allow => "allow",
        }
    }

    pub fn from_string(level: &str) -> Option<Self> {
        match level {
            "allow" => Some(MessageLevel::Allow),
            "info" => Some(MessageLevel::Info),
            "warning" => Some(MessageLevel::Warning),
            "error" => Some(MessageLevel::Error),
            _ => None,
        }
    }
}

pub struct Message<'file, 'msg> {
    pub level: MessageLevel,
    pub kind: MaybeSpanned<'file, &'msg dyn Display>,
}

impl<'file, 'msg> Message<'file, 'msg> {
    pub fn write(&self, writer: &mut dyn WriteColor) -> Result<(), Error> {
        match &self.kind {
            MaybeSpanned::WithoutSpan(_) => {
                self.write_description(writer)?;
            }

            MaybeSpanned::WithSpan(spanned) => {
                self.write_description(writer)?;
                self.write_code(writer, &spanned.span)?;
            }
        }

        writeln!(writer)?;
        Ok(())
    }

    fn write_description(&self, writer: &mut dyn WriteColor) -> Result<(), Error> {
        let mut output = ColorOutput::new(writer);
        output.set_color(self.level.color());
        output.set_bold(true);
        write!(output.writer(), "{}: ", self.level.name())?;

        output.set_color(None);
        writeln!(output.writer(), "{}", *self.kind)?;

        Ok(())
    }

    fn write_code(&self, writer: &mut dyn WriteColor, error: &Span<'_>) -> Result<(), Error> {
        let mut output = ColorOutput::new(writer);
        let num_fmt = LineNumberFormatter::new(error);

        num_fmt.spaces(output.writer())?;
        writeln!(output.writer())?;

        for (line_number, line) in error.lines().numbered() {
            let line_fmt = LineFormatter::new(&line);

            num_fmt.number(output.writer(), line_number)?;
            line_fmt.render(output.writer())?;
            // currently, the span will always exist since we take the line from the error
            // but future versions may print a line below and above for context that
            // is not part of the error
            if let Some(faulty_part_of_line) = Span::intersect(error, &line) {
                // TODO: implement this without the following 3 assumptions:
                // - start_pos - end_pos >= 0, guranteed by data structure invariant of Span
                // - start_term_pos - end_term_pos >= 0, guranteed by monotony of columns (a
                //   Position.char() can only be rendered to 0 or more terminal characters)
                // - unwrap(.): both positions are guranteed to exist in the line since we just
                //   got them from the faulty line, which is a subset of the whole error line
                let (start_term_pos, end_term_pos) =
                    line_fmt.actual_columns(&faulty_part_of_line).unwrap();

                let term_width = end_term_pos - start_term_pos;

                num_fmt.spaces(output.writer())?;

                {
                    let mut output = ColorOutput::new(output.writer());
                    output.set_color(self.level.color());
                    output.set_bold(true);
                    writeln!(
                        output.writer(),
                        "{spaces}{underline}",
                        spaces = " ".repeat(start_term_pos),
                        underline = "^".repeat(term_width)
                    )?;
                }
            }
        }
        Ok(())
    }
}

/// Helper that prints a range of numbers with the correct
/// amount of padding
struct LineNumberFormatter {
    width: usize,
}

impl LineNumberFormatter {
    pub fn new(span: &Span<'_>) -> Self {
        Self {
            width: span.end_position().line_number().to_string().len(),
        }
    }

    pub fn spaces(&self, writer: &mut dyn WriteColor) -> Result<(), Error> {
        let mut output = ColorOutput::new(writer);
        output.set_color(HIGHLIGHT_COLOR);
        output.set_bold(true);
        write!(output.writer(), " {} | ", " ".repeat(self.width))?;
        Ok(())
    }

    pub fn number(&self, writer: &mut dyn WriteColor, line_number: usize) -> Result<(), Error> {
        let mut output = ColorOutput::new(writer);
        output.set_color(HIGHLIGHT_COLOR);
        output.set_bold(true);
        let padded_number = pad_left(&line_number.to_string(), self.width);
        write!(output.writer(), " {} | ", padded_number)?;
        Ok(())
    }
}

pub fn pad_left(s: &str, pad: usize) -> String {
    pad_left_with_char(s, pad, ' ')
}

pub fn pad_left_with_char(s: &str, pad: usize, chr: char) -> String {
    format!(
        "{padding}{string}",
        padding = chr
            .to_string()
            .repeat(pad.checked_sub(s.len()).unwrap_or(0)),
        string = s
    )
}

/// Writes a user-supplied input line in a safe manner by replacing
/// control-characters with escape sequences.
struct LineFormatter<'span, 'file> {
    line: &'span Span<'file>,
}

impl<'span, 'file> LineFormatter<'span, 'file> {
    fn new(line: &'span Span<'file>) -> Self {
        Self { line }
    }

    fn render(&self, writer: &mut dyn WriteColor) -> Result<(), Error> {
        let mut output = ColorOutput::new(writer);

        // TODO: implement an iterator
        let chars = self.line.start_position().iter();

        for position in chars {
            let (text, color) = self.render_char(position.chr());
            output.set_color(color);
            write!(output.writer(), "{}", text)?;

            if position == self.line.end_position() {
                break;
            }
        }

        writeln!(output.writer())?;

        Ok(())
    }

    /// Map terminal columns to `Position` columns. Returns a inclusive
    /// lower bound, and an exclusive upper bound.
    ///
    /// Each printed character does not actually take up monospace grid cell.
    /// For example a TAB character may be represented by 4 spaces. This
    /// function will return the actual number of 'monospace grid cells'
    /// rendered before the given
    /// position.
    ///
    /// Returns `None` if the column is out of bounds.
    fn actual_columns(&self, span: &Span<'_>) -> Option<(usize, usize)> {
        let lower = self.len_printed_before(span.start_position().column());
        let upper = self.len_printed_before(span.end_position().column());

        match (lower, upper) {
            (Some(lower), Some(upper)) => {
                let last_char_width = self.render_char(span.end_position().chr()).0.len();
                Some((lower, upper + last_char_width))
            }
            _ => None,
        }
    }

    fn len_printed_before(&self, col: usize) -> Option<usize> {
        // TODO: get rid of this nonsense
        // NOTE: it would actually be nice to condition the Position on the Line
        // instead of AsciiFile. Thinking of this, we could actually just do
        // `AsciiFile::new((span.as_str().as_bytes()))`. Meaning AsciiFile is
        // not a file, but a View
        // that restricts the
        // linked lists in Positions and Spans to a subset of the file.
        // TODO: implement an iterator on span, or
        // span.to_view().iter()/.to_ascii_file().iter() this method is
        // inherintly unsafe
        // because we do not have
        // a way to restrict
        // positions in a type safe manner.
        if self.line.len() < col {
            return None;
        }

        let chars = self.line.start_position().iter();

        let mut actual_column = 0;

        for position in chars {
            if position.column() == col {
                break;
            }

            actual_column += self.render_char(position.chr()).0.len();
        }

        Some(actual_column)
    }

    fn render_char(&self, chr: char) -> (String, Option<Color>) {
        match chr {
            '\t' => (" ".repeat(TAB_WIDTH), None),
            '\r' | '\n' => ("".to_string(), None),
            chr if chr.is_control() => (
                format!("{{{}}}", u8_to_printable_representation(chr as u8)),
                HIGHLIGHT_COLOR,
            ),
            _ => (chr.to_string(), None),
        }
    }
}

#[cfg(test)]
#[allow(clippy::print_stdout, clippy::use_debug)]
mod tests {
    use super::*;

    #[test]
    fn test_pad_left() {
        let tests = vec![("a", "    a"), ("", "          "), ("a", "a"), ("", "")];

        for (input, expected) in tests {
            println!("Testing: {:?} => {:?}", input, expected);
            assert_eq!(expected, pad_left(input, expected.len()));
        }

        // not enough padding does not truncate string
        assert_eq!("a", pad_left("a", 0));
    }
}