aboutsummaryrefslogtreecommitdiff
path: root/examples/errors.rs
blob: 5603b9cf768738e00654df9e46352a502b05fbec (plain)
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
//! Annotates errors in the HTML read from stdin.
//! Try it out with e.g.:
//!
//! ```sh
//! printf "The pirate says &arrrrr;" | cargo run --example errors
//! ```

use codespan_reporting::{
    diagnostic::{Diagnostic, Label},
    files::SimpleFiles,
    term,
    term::termcolor::{ColorChoice, StandardStream},
};
use html5tokenizer::{offset::PosTrackingReader, NaiveParser, TracingEmitter};

fn main() {
    let input = std::io::read_to_string(std::io::stdin()).unwrap();
    let input_clone = input.clone();
    let mut parser =
        NaiveParser::new_with_emitter(PosTrackingReader::new(&input), TracingEmitter::default());

    let mut files = SimpleFiles::new();
    let file_id = files.add("stdin", input_clone);

    let mut labels = Vec::new();

    for _ in parser.by_ref() {}

    for (error, span) in parser.emitter_mut().drain_errors() {
        labels.push(Label::primary(file_id, span).with_message(error.code()));
    }

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

    let mut writer = StandardStream::stdout(ColorChoice::Auto);
    let config = codespan_reporting::term::Config::default();
    term::emit(&mut writer, &config, &files, &diagnostic).unwrap();
}