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
//! Diagnostics.

use std::char;
use std::str;
use std::cmp;
use std::result;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::sync::Arc;
use unicode_width::UnicodeWidthChar;
use kailua_env::{Source, SourceSlice, Span, Pos};

use dummy_term::{stderr_or_dummy};
use term::{color, StderrTerminal};
use message::{Locale, Localize, Localized, get_message_locale};

/// The diagnostic category.
///
/// Some categories can be nested in other category like this:
///
/// ```text
/// [Error] The root message
///   [Cause] More detailed cause
///     [Cause] Even more detailed cause
///       [Note] Hints or additional spans for the innermost cause
///     [Cause] Multiple causes can exist at the same level
///   [Note] Hints or additional spans for the root message
/// ```
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum Kind {
    /// A note following other reports.
    ///
    /// Normally used when there are multiple spans need to be displayed.
    Note,

    /// An informative message.
    ///
    /// This is not generated by any default procedure and
    /// can only be issued with a flag or manual intervention.
    Info,

    /// An item following other reports, used for causes of prior warnings or errors.
    Cause,

    /// A warning indicating a possible problem which does not directly lead an error.
    Warning,

    /// An error indicating a definitive problem.
    ///
    /// The report is considered a failure from this point,
    /// but won't block the following procedure.
    Error,

    /// So severe error that the process cannot proceed (in principle).
    ///
    /// In practice this category is extremely rare and is highly discouraged.
    Fatal,
}

impl Kind {
    pub fn colors(&self) -> (/*dim*/ color::Color, /*bright*/ color::Color) {
        match *self {
            Kind::Fatal => (color::RED, color::BRIGHT_RED),
            Kind::Error => (color::RED, color::BRIGHT_RED),
            Kind::Warning => (color::YELLOW, color::BRIGHT_YELLOW),
            Kind::Cause => (color::BLUE, color::BRIGHT_BLUE),
            Kind::Info => (color::GREEN, color::BRIGHT_GREEN),
            Kind::Note => (color::CYAN, color::BRIGHT_CYAN),
        }
    }
}

/// The error type for any procedure that may have to stop after the reporting.
#[must_use]
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub struct Stop;

/// The result type for any procedure that may have to stop after the reporting.
pub type Result<T> = result::Result<T, Stop>;

/// A report receiver.
///
/// This trait is not suitable for actual reporting; consider using the `Reporter` trait instead.
/// (An additional trait is required to make this trait object-friendly.)
pub trait Report {
    fn message_locale(&self) -> Locale;
    fn add_span(&self, kind: Kind, span: Span, msg: &Localize) -> Result<()>;
}

impl<'a, R: Report + ?Sized> Report for &'a R {
    fn message_locale(&self) -> Locale { (**self).message_locale() }
    fn add_span(&self, k: Kind, s: Span, m: &Localize) -> Result<()> { (**self).add_span(k, s, m) }
}

impl<'a, R: Report + ?Sized> Report for &'a mut R {
    fn message_locale(&self) -> Locale { (**self).message_locale() }
    fn add_span(&self, k: Kind, s: Span, m: &Localize) -> Result<()> { (**self).add_span(k, s, m) }
}

impl<'a, R: Report + ?Sized> Report for Box<R> {
    fn message_locale(&self) -> Locale { (**self).message_locale() }
    fn add_span(&self, k: Kind, s: Span, m: &Localize) -> Result<()> { (**self).add_span(k, s, m) }
}

impl<'a, R: Report + ?Sized> Report for Rc<R> {
    fn message_locale(&self) -> Locale { (**self).message_locale() }
    fn add_span(&self, k: Kind, s: Span, m: &Localize) -> Result<()> { (**self).add_span(k, s, m) }
}

impl<'a, R: Report + ?Sized> Report for Arc<R> {
    fn message_locale(&self) -> Locale { (**self).message_locale() }
    fn add_span(&self, k: Kind, s: Span, m: &Localize) -> Result<()> { (**self).add_span(k, s, m) }
}

/// Extension methods for `Report`. This is what you normally want to use.
pub trait Reporter: Report + Sized {
    /// Reports a fatal error with given location and message.
    /// Additional errors can be chained and should finish with `.done()` call.
    fn fatal<Loc: Into<Span>, Msg: Localize, T>(&self, loc: Loc, msg: Msg) -> ReportMore<T> {
        info!("reporting fatal error: {:?}", msg);
        let ret = self.add_span(Kind::Fatal, loc.into(), &msg);
        let ret = ret.map(|_| panic!("Report::fatal should always return Err"));
        ReportMore::new(self, ret)
    }

    /// Reports a recoverable error with given location and message.
    /// Additional errors can be chained and should finish with `.done()` call.
    fn error<Loc: Into<Span>, Msg: Localize>(&self, loc: Loc, msg: Msg) -> ReportMore<()> {
        info!("reporting error: {:?}", msg);
        let ret = self.add_span(Kind::Error, loc.into(), &msg);
        ReportMore::new(self, ret)
    }

    /// Reports a warning with given location and message.
    /// Additional errors can be chained and should finish with `.done()` call.
    fn warn<Loc: Into<Span>, Msg: Localize>(&self, loc: Loc, msg: Msg) -> ReportMore<()> {
        info!("reporting warning: {:?}", msg);
        let ret = self.add_span(Kind::Warning, loc.into(), &msg);
        ReportMore::new(self, ret)
    }

    /// Reports an additional information with given location and message.
    /// Additional errors can be chained and should finish with `.done()` call.
    fn info<Loc: Into<Span>, Msg: Localize>(&self, loc: Loc, msg: Msg) -> ReportMore<()> {
        info!("reporting info: {:?}", msg);
        let ret = self.add_span(Kind::Info, loc.into(), &msg);
        ReportMore::new(self, ret)
    }
}

impl<T: Report> Reporter for T {}

/// A helper type for additional reports to the root message.
#[must_use]
pub struct ReportMore<'a, T> {
    report: &'a Report,
    result: Result<T>,
}

impl<'a, T> ReportMore<'a, T> {
    fn new(report: &'a Report, result: Result<T>) -> ReportMore<'a, T> {
        ReportMore { report: report, result: result }
    }

    /// Reports a cause of the root message with given location and message.
    pub fn cause<Loc: Into<Span>, Msg: Localize>(self, loc: Loc, msg: Msg) -> ReportMore<'a, T> {
        info!("reporting cause: {:?}", msg);
        let ret = self.report.add_span(Kind::Cause, loc.into(), &msg);
        ReportMore::new(self.report, if let Err(e) = ret { Err(e) } else { self.result })
    }

    /// Reports a note for the root message with given location and message.
    pub fn note<Loc: Into<Span>, Msg: Localize>(self, loc: Loc, msg: Msg) -> ReportMore<'a, T> {
        info!("reporting note: {:?}", msg);
        let ret = self.report.add_span(Kind::Note, loc.into(), &msg);
        ReportMore::new(self.report, if let Err(e) = ret { Err(e) } else { self.result })
    }

    /// Same to `note` but only reports for non-dummy spans.
    /// This is useful for reporting multiple spans where some of them can be dummy.
    pub fn note_if<Loc: Into<Span>, Msg: Localize>(self, loc: Loc, msg: Msg) -> ReportMore<'a, T> {
        let loc = loc.into();
        if loc.is_dummy() {
            self
        } else {
            info!("reporting note: {:?}", msg);
            let ret = self.report.add_span(Kind::Note, loc.into(), &msg);
            ReportMore::new(self.report, if let Err(e) = ret { Err(e) } else { self.result })
        }
    }

    /// Finishes the reporting. Should be called for any `Reporter`-initiated report.
    pub fn done(self) -> Result<T> { self.result }
}

fn strip_newline(mut s: SourceSlice) -> SourceSlice {
    match s {
        SourceSlice::U8(ref mut s) => loop {
            match s.last() {
                Some(&b'\r') | Some(&b'\n') => { *s = &s[..s.len()-1]; }
                _ => { break; }
            }
        },
        SourceSlice::U16(ref mut s) => loop {
            match s.last() {
                Some(&0x0a) | Some(&0x0d) => { *s = &s[..s.len()-1]; }
                _ => { break; }
            }
        },
    }
    s
}

/// An implementation of `Report` that reports to stderr, optionally colored.
///
/// This will also give the correct context for the reports from given `Source`,
/// with mostly correct line and column numbers (may be inaccurate with strange encodings).
pub struct ConsoleReport {
    source: Rc<RefCell<Source>>,
    term: RefCell<Box<StderrTerminal>>,
    locale: Locale,
}

impl ConsoleReport {
    pub fn new(source: Rc<RefCell<Source>>) -> ConsoleReport {
        let locale = get_message_locale().unwrap_or_else(|| Locale::dummy());
        ConsoleReport::with_locale(source, locale)
    }

    pub fn with_locale(source: Rc<RefCell<Source>>, locale: Locale) -> ConsoleReport {
        ConsoleReport {
            source: source,
            term: RefCell::new(stderr_or_dummy()),
            locale: locale,
        }
    }

    // column number starts from 0
    // the final newlines are ignored and not counted towards columns
    fn calculate_column(&self, linespan: Span, pos: Pos) -> usize {
        assert!(linespan.contains_or_end(pos));
        let off = pos.to_usize() - linespan.begin().to_usize();

        let source = self.source.borrow();
        let line = strip_newline(source.slice_from_span(linespan).unwrap());

        fn seek<T, Iter, Width>(off: usize, iter: Iter, len: usize, tab: T, width: Width) -> usize
            where T: PartialEq, Iter: Iterator<Item=(usize, T)>, Width: Fn(&T) -> usize
        {
            let mut lastcol = 0;
            let mut col = 0;

            for (i, c) in iter {
                if off < i {
                    // previous start offset <= off < current start offset
                    return lastcol;
                }
                lastcol = col;
                if c == tab {
                    // assume 8-space tabs (common in terminals)
                    col = (col + 8) & !7; // 0..7->8, 8..15->16, ...
                } else {
                    col += width(&c);
                }
            }

            if off < len {
                return lastcol;
            }

            // the offset *may* exceed `len` (the entire end offset),
            // when the iterator has stripped a newline and the offset points past that newline
            col
        }

        match line {
            SourceSlice::U8(line) => {
                if let Ok(line) = str::from_utf8(line) {
                    // it is a UTF-8 string, use unicode-width
                    seek(off, line.char_indices(), line.len(), '\t',
                         |c| c.width_cjk().unwrap_or(1))
                } else {
                    // otherwise it is in the legacy encodings.
                    // fortunately for us the column width and byte width for those encodings
                    // generally agrees to each other, so we just use the byte offset
                    seek(off, line.iter().cloned().enumerate(), line.len(), b'\t', |_| 1)
                }
            }

            SourceSlice::U16(line) => {
                // we assume that the U16 lines are almost UTF-16.

                // char::decode_utf16 itself doesn't directly give an u16 offset...
                type DecodeUtf16Result = ::std::result::Result<char, char::DecodeUtf16Error>;
                struct Iter<I> { iter: I, cur: usize }
                impl<I: Iterator<Item=DecodeUtf16Result>> Iterator for Iter<I> {
                    type Item = (usize, DecodeUtf16Result);
                    fn next(&mut self) -> Option<(usize, DecodeUtf16Result)> {
                        let cur = self.cur;
                        if let Some(c) = self.iter.next() {
                            self.cur += if let Ok('\u{10000}'...'\u{10ffff}') = c { 2 } else { 1 };
                            Some((cur, c))
                        } else {
                            None
                        }
                    }
                }

                let iter = Iter { iter: char::decode_utf16(line.iter().cloned()), cur: 0 };
                seek(off, iter, line.len(), Ok('\t'),
                     |c| c.as_ref().ok().unwrap_or(&'\u{fffd}').width_cjk().unwrap_or(1))
            }
        }
    }

    // similar to calculate_column but expands tab in `line`
    fn expand_tab_in_str(&self, line: &str, next_col: &mut usize) -> Vec<u8> {
        let mut col = *next_col;
        let mut ret = String::new();
        for c in line.chars() {
            if c == '\t' {
                let newcol = (col + 8) & !7;
                for _ in col..newcol { ret.push(' '); }
                col = newcol;
            } else {
                col += c.width_cjk().unwrap_or(1);
                ret.push(c);
            }
        }
        *next_col = col;
        ret.into_bytes()
    }

    fn expand_tab_in_bytes(&self, line: &[u8], next_col: &mut usize) -> Vec<u8> {
        let mut col = *next_col;
        let mut ret = Vec::new();
        for &c in line.iter() {
            if c == b'\t' {
                let newcol = (col + 8) & !7;
                for _ in col..newcol { ret.push(b' '); }
                col = newcol;
            } else {
                col += 1;
                ret.push(c);
            }
        }
        *next_col = col;
        ret
    }
}

impl Report for ConsoleReport {
    fn message_locale(&self) -> Locale {
        self.locale
    }

    fn add_span(&self, kind: Kind, span: Span, msg: &Localize) -> Result<()> {
        let mut term = self.term.borrow_mut();
        let term = &mut *term;
        let source = self.source.borrow();

        let mut codeinfo = None;
        if let Some(f) = source.get_file(span.unit()) {
            if let Some((beginline, mut spans, endline)) = f.lines_from_span(span) {
                let beginspan = spans.next().unwrap();
                let begincol = self.calculate_column(beginspan, span.begin());
                let endspan = spans.next_back().unwrap_or(beginspan);
                let endcol = self.calculate_column(endspan, span.end());
                let _ = write!(term, "{}:{}:{}: ", f.path(), beginline + 1, begincol + 1);
                if span.begin() != span.end() {
                    let _ = write!(term, "{}:{} ", endline + 1, endcol + 1);
                }
                codeinfo = Some((beginline, begincol, beginspan, endline, endcol, endspan));
            }
        }

        let (dim, bright) = kind.colors();
        let _ = term.fg(dim);
        let _ = write!(term, "[");
        let _ = term.fg(bright);
        let _ = write!(term, "{:?}", kind);
        let _ = term.fg(dim);
        let _ = write!(term, "] ");
        let _ = term.fg(color::BRIGHT_WHITE);
        let _ = write!(term, "{}", Localized::new(msg, self.locale));
        let _ = term.reset();
        let _ = writeln!(term, "");

        // if possible, print the source code as well
        if let Some((beginline, begincol, beginspan, endline, endcol, endspan)) = codeinfo {
            fn num_digits(mut x: usize) -> usize {
                let mut d = 1;
                while x > 9 { x /= 10; d += 1; }
                d
            }

            type Term<'a> = &'a mut Box<StderrTerminal>;

            let write_newline = |term: Term| {
                let _ = writeln!(term, "");
            };

            let ndigits = num_digits(endline + 1);
            let write_lineno = |term: Term, lineno| {
                let _ = term.fg(color::BRIGHT_BLACK);
                let _ = write!(term, "{:1$} | ", lineno + 1, ndigits);
                let _ = term.reset();
            };
            let write_lineno_empty = |term: Term| {
                let _ = term.fg(color::BRIGHT_BLACK);
                let _ = write!(term, "{:1$} | ", "", ndigits);
                let _ = term.reset();
            };
            let write_lineno_omitted = |term: Term| {
                let _ = term.fg(color::BRIGHT_BLACK);
                let _ = write!(term, "{:1$} :", "", ndigits);
                let _ = term.reset();
            };

            let write_slice = |term: Term, slice: SourceSlice, begin, end| {
                macro_rules! write_marked {
                    (self.$method:ident($line:expr)) => ({
                        let line = $line;
                        let mut col = 0;
                        if begin > 0 {
                            let _ = term.write(&self.$method(&line[..begin], &mut col));
                        }
                        let _ = term.fg(bright);
                        let _ = term.write(&self.$method(&line[begin..end], &mut col));
                        let _ = term.reset();
                        if end < line.len() {
                            let _ = term.write(&self.$method(&line[end..], &mut col));
                        }
                    })
                }

                match slice {
                    SourceSlice::U8(bytes) => {
                        if let Ok(line) = str::from_utf8(bytes) {
                            write_marked!(self.expand_tab_in_str(line));
                        } else {
                            write_marked!(self.expand_tab_in_bytes(bytes));
                        }
                    }
                    SourceSlice::U16(chars) => {
                        let line = String::from_utf16_lossy(chars);
                        write_marked!(self.expand_tab_in_str(line));
                    }
                }
            };

            if beginline == endline {
                let slice = strip_newline(source.slice_from_span(beginspan).unwrap());
                let beginoff = span.begin().to_usize() - beginspan.begin().to_usize();
                let endoff = span.end().to_usize() - beginspan.begin().to_usize();

                // 123 | aaaabbbbbb     begincol = endcol
                //     |     *
                //
                // 123 | aaaaXXXXXbbb   begincol < endcol
                //     |     ^^^^^
                write_lineno(term, beginline);
                write_slice(term, slice, beginoff, endoff);
                write_newline(term);
                write_lineno_empty(term);
                let _ = term.fg(bright);
                if begincol == endcol {
                    let _ = write!(term, "{:1$}*", "", begincol);
                } else {
                    let _ = write!(term, "{:2$}{:^>3$}", "", "", begincol, endcol - begincol);
                }
                let _ = term.reset();
                write_newline(term);
            } else {
                // 123 | aaaaXXXXXXXX
                //     |     ^ from here...
                let beginslice = strip_newline(source.slice_from_span(beginspan).unwrap());
                let beginlen = beginslice.len();
                let beginoff = span.begin().to_usize() - beginspan.begin().to_usize();
                write_lineno(term, beginline);
                write_slice(term, beginslice, beginoff, beginlen);
                write_newline(term);
                write_lineno_empty(term);
                let _ = term.fg(bright);
                let _ = write!(term, "{:1$}^", "", begincol);
                let _ = term.fg(dim);
                let _ = write!(term, " from here...");
                let _ = term.reset();
                write_newline(term);

                if endline - beginline > 1 {
                    write_lineno_omitted(term);
                    write_newline(term);
                }

                // 321 | bbbbbbbbbb     endcol = 0
                //     | * ...to here
                //
                // 321 | XXXXXbbbbb     endcol > 0
                //     |     ^ to here
                let endslice = strip_newline(source.slice_from_span(endspan).unwrap());
                let endoff = span.end().to_usize() - endspan.begin().to_usize();
                write_lineno(term, endline);
                write_slice(term, endslice, 0, endoff);
                write_newline(term);
                write_lineno_empty(term);
                let _ = term.fg(bright);
                if endcol == 0 {
                    let _ = write!(term, "*");
                } else {
                    let _ = write!(term, "{:1$}^", "", endcol - 1);
                }
                let _ = term.fg(dim);
                let _ = write!(term, " ...to here");
                let _ = term.reset();
                write_newline(term);
            }
        }

        if kind == Kind::Fatal { Err(Stop) } else { Ok(()) }
    }
}

/// An implementation of `Report` that simply collects reports for later uses.
///
/// Note that the message itself is localized at the report time, so the locale is still required.
pub struct CollectedReport {
    collected: RefCell<Vec<(Kind, Span, String)>>,
    locale: Locale,
}

impl CollectedReport {
    pub fn new(locale: Locale) -> CollectedReport {
        CollectedReport { collected: RefCell::new(Vec::new()), locale: locale }
    }

    pub fn into_reports(self) -> Vec<(Kind, Span, String)> {
        self.collected.into_inner()
    }
}

impl Report for CollectedReport {
    fn message_locale(&self) -> Locale {
        self.locale
    }

    fn add_span(&self, kind: Kind, span: Span, msg: &Localize) -> Result<()> {
        let msg = Localized::new(msg, self.locale).to_string();
        self.collected.borrow_mut().push((kind, span, msg));
        if kind == Kind::Fatal { Err(Stop) } else { Ok(()) }
    }
}

/// An implementation of `Report` that panics on reports.
pub struct NoReport;

impl Report for NoReport {
    fn message_locale(&self) -> Locale {
        Locale::dummy()
    }

    fn add_span(&self, _kind: Kind, _span: Span, _msg: &Localize) -> Result<()> {
        Err(Stop)
    }
}

/// A wrapper for `Report` implementations that also tracks the most severe message category.
pub struct TrackMaxKind<R: Report> {
    report: R,
    maxkind: Cell<Option<Kind>>,
}

impl<R: Report> TrackMaxKind<R> {
    pub fn new(report: R) -> TrackMaxKind<R> {
        TrackMaxKind {
            report: report,
            maxkind: Cell::new(None),
        }
    }

    pub fn can_continue(&self) -> bool {
        self.maxkind.get() < Some(Kind::Error)
    }

    pub fn into_inner(self) -> R {
        self.report
    }
}

impl<R: Report> Report for TrackMaxKind<R> {
    fn message_locale(&self) -> Locale {
        self.report.message_locale()
    }

    fn add_span(&self, kind: Kind, span: Span, msg: &Localize) -> Result<()> {
        if let Some(maxkind) = self.maxkind.get() {
            self.maxkind.set(Some(cmp::max(maxkind, kind)));
        } else {
            self.maxkind.set(Some(kind));
        }
        self.report.add_span(kind, span, msg)
    }
}