docs: add some examples (#47)

This commit is contained in:
Dimitri Merejkowsky 2022-07-22 16:58:50 +02:00 committed by GitHub
parent 6d32700b95
commit 901fe3fd7b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 89 additions and 0 deletions

47
examples/custom-errors.rs Normal file
View File

@ -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<KdlDocument, MyError> {
let doc = input.parse::<KdlDocument>();
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.
}

42
examples/insert-node.rs Normal file
View File

@ -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(())
}