pub trait Ast<'fmt>: Sized {
type Error;
// Required method
fn from_expr(expr: &'fmt str) -> Result<Self, Self::Error>;
}Expand description
A typed representation of an expression which does not interpret the contents.
Often, you can use a provided implementation.
The role of an Ast is to perform as much validation as possible, without any knowledge of the
Manifest which may later use it. The correct balance here depends, of course, on the
particular use-case.
§Example
A HashMap uses &str as its Ast implementation.
An &str is not aware at all of the contents of an expression, except that it should interpret it as
a string. In contrast, if we are aware that the keys must come from a specific list, we can
check that this is the case when the template is compiled.
use mufmt::{Ast, BorrowedTemplate};
/// The permitted colours
enum Color {
Red,
Green,
Blue,
}
struct InvalidColor(pub String);
/// An `Ast` implementation which requires a string matching one of the colors.
impl Ast<'_> for Color {
type Error = InvalidColor;
fn from_expr(expr: &str) -> Result<Self, Self::Error> {
// expressions are whitespace trimmed, so we don't need to handle this here
match expr {
"red" => Ok(Self::Red),
"green" => Ok(Self::Green),
"blue" => Ok(Self::Blue),
s => Err(InvalidColor(s.to_owned())),
}
}
}
assert!(BorrowedTemplate::<Color>::compile("My favourite colors are {blue} and { green }!").is_ok());
assert!(BorrowedTemplate::<Color>::compile("The sky is very {orange}!").is_err());Required Associated Types§
Required Methods§
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.