kotlin_parser/parse/expression/
literal.rs

1use crate::ast::{Expression, Literal};
2use chumsky::prelude::*;
3
4pub fn null_literal() -> impl Parser<char, Literal, Error = Simple<char>> {
5    just("null").to(Literal::Null)
6}
7
8pub fn string_literal() -> impl Parser<char, Literal, Error = Simple<char>> {
9    just('"')
10        .ignore_then(none_of('"').repeated())
11        .then_ignore(just('"'))
12        .collect::<String>()
13        .map(Literal::String)
14}
15
16pub fn char_literal() -> impl Parser<char, Literal, Error = Simple<char>> {
17    just('\'')
18        .ignore_then(none_of('\''))
19        .then_ignore(just('\''))
20        .map(Literal::Char)
21}
22
23pub fn boolean_literal() -> impl Parser<char, Literal, Error = Simple<char>> {
24    choice((
25        just("true").to(Literal::Boolean(true)),
26        just("false").to(Literal::Boolean(false)),
27    ))
28}
29
30pub fn float_literal() -> impl Parser<char, Literal, Error = Simple<char>> {
31    text::int(10)
32        .then(just('.').then(text::int(10)))
33        .map(|(int, (_, frac))| {
34            Literal::Decimal(format!("{}.{}", int, frac).parse().unwrap())
35        })
36}
37
38pub fn int_literal() -> impl Parser<char, Literal, Error = Simple<char>> {
39    text::int(10).map(|s: String| Literal::Integer(s.parse().unwrap()))
40}
41
42pub fn literal_parser() -> impl Parser<char, Literal, Error = Simple<char>> {
43    choice((
44        float_literal(),
45        int_literal(),
46        string_literal(),
47        char_literal(),
48        boolean_literal(),
49        null_literal(),
50    ))
51}
52
53#[allow(dead_code)]
54pub fn literal_expr_parser(
55) -> impl Parser<char, Expression, Error = Simple<char>> {
56    literal_parser().map(Expression::Literal)
57}
58
59#[cfg(test)]
60mod tests {
61    use super::*;
62
63    #[test]
64    fn parse_literal() {
65        assert_eq!(literal_parser().parse("123"), Ok(Literal::Integer(123)));
66
67        assert_eq!(
68            literal_parser().parse("123.456"),
69            Ok(Literal::Decimal(123.456))
70        );
71
72        assert_eq!(
73            literal_parser().parse("\"abc\""),
74            Ok(Literal::String("abc".to_string()))
75        );
76
77        assert_eq!(literal_parser().parse("'a'"), Ok(Literal::Char('a')));
78
79        assert_eq!(literal_parser().parse("true"), Ok(Literal::Boolean(true)));
80
81        assert_eq!(
82            literal_parser().parse("false"),
83            Ok(Literal::Boolean(false))
84        );
85
86        assert_eq!(literal_parser().parse("null"), Ok(Literal::Null));
87    }
88}