aboutsummaryrefslogtreecommitdiff
path: root/examples/spans.rs
blob: b8d5283e0567da71a23875fe9b1f4bd2fcd2732c (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
use codespan_reporting::{
    diagnostic::{Diagnostic, Label},
    files::SimpleFiles,
    term,
    term::termcolor::{ColorChoice, StandardStream},
};
use html5tokenizer::{offset::PosTrackingReader, trace::Trace, NaiveParser, Token, TracingEmitter};

fn main() {
    let html = r#"<img src=example.jpg alt="some description">"#;
    let parser =
        NaiveParser::new_with_emitter(PosTrackingReader::new(html), TracingEmitter::default());

    let (Token::StartTag(tag), Trace::StartTag(trace)) = parser.flatten().next().unwrap() else {
        panic!()
    };

    let mut files = SimpleFiles::new();
    let file_id = files.add("file.html", html);

    let mut labels = Vec::new();

    labels.push(Label::primary(file_id, trace.name_span).with_message("tag name"));

    for attr in &tag.attributes {
        let attr_trace = &trace.attribute_traces[attr.trace_idx().unwrap()];
        labels.push(Label::primary(file_id, attr_trace.name_span()).with_message("attr name"));
        labels.push(
            Label::primary(file_id, attr_trace.value_span().unwrap()).with_message("attr value"),
        );
    }

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

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