SHARE
TWEET

Untitled

a guest Jun 19th, 2019 56 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. use std::fmt::{Display, Formatter, Result as FmtResult};
  2.  
  3. trait MyError {
  4.     fn descr(&self) -> String;
  5. }
  6.  
  7. type TokenIdx = u32;
  8.  
  9. struct LexicalError {
  10.     before: TokenIdx,
  11.     after: Option<TokenIdx>,
  12.     message: String,
  13.     hint: Option<String>,
  14. }
  15.  
  16. impl MyError for LexicalError {
  17.     fn descr(&self) -> String {
  18.         format!(
  19.             "Lexical error: {}\n  before: {}{}{}",
  20.             self.message,
  21.             self.before,
  22.             self.after
  23.                 .map_or("".to_owned(), |a| format!("\n  after: {}", a)),
  24.             self.hint
  25.                 .as_ref()
  26.                 .map_or("".to_owned(), |h| format!("\n  hint: {}", h))
  27.         )
  28.     }
  29. }
  30.  
  31. impl Display for MyError {
  32.     fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
  33.         writeln!(fmt, "{}", self.descr())
  34.     }
  35. }
  36.  
  37. impl Display for LexicalError {
  38.     fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
  39.         writeln!(fmt, "a LexicalError")
  40.     }
  41. }
  42.  
  43. fn main() {
  44.     let e = LexicalError {
  45.         before: 5,
  46.         after: None,
  47.         message: "Invalid character".to_owned(),
  48.         hint: Some("Try ASCII char sequence instead (ΓΌ -> ue)".to_owned()),
  49.     };
  50.  
  51.     println!("{}", &e as &MyError);
  52.     println!("{}", e);
  53. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top