Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::fmt::{Display, Formatter, Result as FmtResult};
- trait MyError {
- fn descr(&self) -> String;
- }
- type TokenIdx = u32;
- struct LexicalError {
- before: TokenIdx,
- after: Option<TokenIdx>,
- message: String,
- hint: Option<String>,
- }
- impl MyError for LexicalError {
- fn descr(&self) -> String {
- format!(
- "Lexical error: {}\n before: {}{}{}",
- self.message,
- self.before,
- self.after
- .map_or("".to_owned(), |a| format!("\n after: {}", a)),
- self.hint
- .as_ref()
- .map_or("".to_owned(), |h| format!("\n hint: {}", h))
- )
- }
- }
- impl Display for MyError {
- fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
- writeln!(fmt, "{}", self.descr())
- }
- }
- impl Display for LexicalError {
- fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
- writeln!(fmt, "a LexicalError")
- }
- }
- fn main() {
- let e = LexicalError {
- before: 5,
- after: None,
- message: "Invalid character".to_owned(),
- hint: Some("Try ASCII char sequence instead (ü -> ue)".to_owned()),
- };
- println!("{}", &e as &MyError);
- println!("{}", e);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement