From c163224fb77086d7c99206441e5c66570858dafc Mon Sep 17 00:00:00 2001 From: Alex Bethel Date: Sat, 6 Aug 2022 19:42:55 -0500 Subject: [PATCH] More literals --- axc/src/parser.rs | 49 ++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 44 insertions(+), 5 deletions(-) diff --git a/axc/src/parser.rs b/axc/src/parser.rs index 5673c42..8fc0b23 100644 --- a/axc/src/parser.rs +++ b/axc/src/parser.rs @@ -3,8 +3,8 @@ use std::{error::Error, fmt::Display}; use chumsky::{ - prelude::{choice, end, just, one_of, todo, Simple}, - text::{ident, keyword, whitespace}, + prelude::{choice, end, just, none_of, one_of, todo, Simple}, + text::{ident, int, keyword, whitespace}, Parser, }; @@ -437,10 +437,49 @@ fn parse_binary<'a>( } fn parse_literal(_m: &ParserMeta) -> impl Parser> + Clone { - // TODO: add all the literals. - chumsky::text::int(10) + let string_char = none_of("\"\\").or(just('\\').ignore_then(choice(( + just('n').to('\n'), + just('t').to('\t'), + just('r').to('\r'), + just('0').to('\x00'), + just('\'').to('\''), + just('\"').to('\"'), + just('x').ignore_then( + one_of("0123456789abcdefABCDEF") + .repeated() + .exactly(2) + .collect::() + .map(|s| u8::from_str_radix(&s, 16).unwrap().try_into().unwrap()), + ), + just('u').ignore_then( + one_of("0123456789abcdefABCDEF") + .repeated() + .collect::() + .map(|s| u32::from_str_radix(&s, 16).unwrap().try_into().unwrap()), + ), + )))); + + let int = int(10) .then_ignore(whitespace()) - .map(|s: String| Expr::Literal(Literal::Integer(s.parse().unwrap()))) + .map(|s: String| s.parse().unwrap()) + .map(Literal::Integer); + + let string = string_char + .clone() + .repeated() + .collect() + .delimited_by(just('\"'), just('\"')) + .map(Literal::String); + + let float = one_of("0123456789") + .repeated() + .collect::() + .then_ignore(just('.')) + .then(one_of("0123456789").repeated().collect::()) + .map(|(l, r)| (l + "." + &r).parse().unwrap()) + .map(Literal::Float); + + choice((int, float, string)).map(Expr::Literal) } fn parse_type(_m: &ParserMeta) -> impl Parser> {