diff --git a/examples/custom-errors.rs b/examples/custom-errors.rs new file mode 100644 index 0000000..20fa2c0 --- /dev/null +++ b/examples/custom-errors.rs @@ -0,0 +1,47 @@ +/// Show how to build your own diagnostics, without having to use the +/// `fancy` feature or having `main()` return `miette::Result` +use kdl::KdlDocument; +use miette::Diagnostic; +use miette::SourceSpan; + +#[derive(Debug)] +pub struct MyError { + pub message: String, +} + +fn parse(input: &str) -> Result { + let doc = input.parse::(); + doc.map_err(|error| { + let source = error + .source_code() + .expect("parse errors should have source code"); + let help = error.help.unwrap_or_default(); + let span: SourceSpan = error.span; + let contents = source + .read_span(&span, 0, 0) + .expect("source should have span contents"); + // miette uses 0 based indexes, but humans prefer 1-based + let line = contents.line() + 1; + let column = contents.column() + 1; + let message = format!( + "line {}, column {}: {}\n help: {}", + line, column, error, help + ); + MyError { message } + }) +} + +fn main() { + let input = r#" + foo { + bar { + baz 1. + } + } + "#; + let err = parse(input).unwrap_err(); + eprintln!("{}", err.message); + // Output: + // line 4, column 14: Expected valid value. + // help: Floating point numbers must be base 10, and have numbers after the decimal point. +} diff --git a/examples/insert-node.rs b/examples/insert-node.rs new file mode 100644 index 0000000..fe008bf --- /dev/null +++ b/examples/insert-node.rs @@ -0,0 +1,42 @@ +// Shows how to maintain nodes sorted by value in a +// machine-generated kdl document + +use kdl::{KdlDocument, KdlIdentifier, KdlNode}; + +fn sort_by_name(x: &KdlNode, y: &KdlNode) -> std::cmp::Ordering { + x.name().value().cmp(y.name().value()) +} + +fn main() -> miette::Result<()> { + let input = r#" +words { + apple // one a day keeps the doctor away + orange +} + "#; + let mut doc: KdlDocument = input.parse()?; + + let words_section = doc.get_mut("words").expect("'words' section should exist"); + let children = words_section + .children_mut() + .as_mut() + .expect("'words' section should have children"); + let word_nodes = children.nodes_mut(); + + let identifier = KdlIdentifier::from("banana"); + let word_node = KdlNode::new(identifier); + word_nodes.push(word_node); + word_nodes.sort_by(sort_by_name); + words_section.fmt(); + + println!("{}", doc.to_string()); + + // output: + // words { + // apple // one a day keeps the doctor away + // banana + // orange + // } + + Ok(()) +}