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
56
57
58
59
60
61
62
63
64
use std::ops::Deref;
use nom::{
branch::alt,
bytes::complete::{escaped, tag},
character::complete::{none_of, one_of},
combinator::map,
sequence::delimited,
IResult,
};
use super::Parser;
#[derive(Debug, Clone)]
pub struct Literal(pub String);
impl Deref for Literal {
type Target = str;
fn deref(&self) -> &str {
&self.0
}
}
impl Parser for Literal {
fn parse(input: &str) -> IResult<&str, Literal> {
alt((
map(single_quote, |x| Literal(x.into())),
map(double_quote, |x| Literal(x.into())),
))(input)
}
}
fn single_quote(input: &str) -> IResult<&str, &str> {
let esc = escaped(none_of(r#"\'"#), '\\', one_of(r#"'"n\"#));
let esc_or_empty = alt((esc, tag("")));
let res = delimited(tag("\'"), esc_or_empty, tag("\'"))(input)?;
Ok(res)
}
fn double_quote(input: &str) -> IResult<&str, &str> {
let esc = escaped(none_of(r#"\""#), '\\', one_of(r#"'"n\"#));
let esc_or_empty = alt((esc, tag("")));
let res = delimited(tag("\""), esc_or_empty, tag("\""))(input)?;
Ok(res)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_literal() {
let input = r#""foo""#;
match super::Literal::parse(input) {
Ok((remain, lit)) => {
assert_eq!(remain, "");
assert_eq!(lit.0, "foo");
}
Err(e) => panic!("Error: {e:?}"),
}
}
}