summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMartin Fischer <martin@push-f.com>2023-09-28 10:14:21 +0200
committerMartin Fischer <martin@push-f.com>2023-09-28 11:00:01 +0200
commit70b92eda9a38c2f0e093c0f74cafb6398f97b58e (patch)
tree9b8d020445cc974749362ba73fdc30e5e432bfdf
parent3a3b40e1eb715ec97dc873e31c726c2f3dd8dcdf (diff)
docs: add errors example
-rw-r--r--examples/errors.rs38
1 files changed, 38 insertions, 0 deletions
diff --git a/examples/errors.rs b/examples/errors.rs
new file mode 100644
index 0000000..5603b9c
--- /dev/null
+++ b/examples/errors.rs
@@ -0,0 +1,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();
+}