-
Notifications
You must be signed in to change notification settings - Fork 84
/
Copy pathnote.rs
55 lines (52 loc) · 1.69 KB
/
note.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
use crate::error::Error;
use crate::token::{Token, Tokenizer};
use std::fmt;
#[derive(PartialEq, Eq, Debug)]
pub enum NoteCommand {
Summary { title: String },
Remove { title: String },
}
#[derive(PartialEq, Eq, Debug)]
pub enum ParseError {
MissingTitle,
}
impl std::error::Error for ParseError {}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ParseError::MissingTitle => write!(f, "missing required summary title"),
}
}
}
impl NoteCommand {
pub fn parse<'a>(input: &mut Tokenizer<'a>) -> Result<Option<Self>, Error<'a>> {
let mut toks = input.clone();
if let Some(Token::Word("note")) = toks.peek_token()? {
toks.next_token()?;
let mut remove = false;
loop {
match toks.next_token()? {
Some(Token::Word(title)) if title == "remove" => {
remove = true;
continue;
}
Some(Token::Word(title)) | Some(Token::Quote(title)) => {
let command = if remove {
NoteCommand::Remove {
title: title.to_string(),
}
} else {
NoteCommand::Summary {
title: title.to_string(),
}
};
break Ok(Some(command));
}
_ => break Err(toks.error(ParseError::MissingTitle)),
};
}
} else {
Ok(None)
}
}
}