From c0be718bbc48e409ec37b372d2fe562e00cd7244 Mon Sep 17 00:00:00 2001 From: NotAFile Date: Tue, 5 Apr 2022 14:52:56 +0200 Subject: [PATCH] parse struct initialization --- src/frontend.rs | 1 + src/parser/expression.rs | 37 ++++++++++++++++++++++++++++++++++++- 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/src/frontend.rs b/src/frontend.rs index e7ee3d7..b99604a 100644 --- a/src/frontend.rs +++ b/src/frontend.rs @@ -223,6 +223,7 @@ impl Context { todo!("expression blocks not representable in typed ir yet") } }, + Expression::StructInit(_) => todo!("structure initialization"), }; Ok(t_expr) } diff --git a/src/parser/expression.rs b/src/parser/expression.rs index 3c02a9f..cf5be53 100644 --- a/src/parser/expression.rs +++ b/src/parser/expression.rs @@ -6,7 +6,7 @@ use nom::{ branch::alt, combinator::{map, opt}, multi::separated_list0, - sequence::{delimited, tuple}, + sequence::{delimited, separated_pair, tuple}, }; #[derive(Debug, Clone)] @@ -27,6 +27,12 @@ pub struct Call<'a> { pub args: Vec>, } +#[derive(Debug, Clone)] +pub struct StructInit<'a> { + pub name: Span<'a>, + pub args: Vec<(Token<'a>, Expression<'a>)>, +} + #[derive(Debug, Clone)] pub enum BinOpKind { And, @@ -60,6 +66,7 @@ pub enum Expression<'a> { UnOp(Box>), BinOp(Box>), Call(Box>), + StructInit(Box>), BlockExpr(Box>), } @@ -67,6 +74,9 @@ pub enum Expression<'a> { fn atom(input: TokenSpan) -> IResult { alt(( map(call_item, |call| Expression::Call(Box::new(call))), + map(struct_init_item, |sinit| { + Expression::StructInit(Box::new(sinit)) + }), map(token(tk::Ident), |it| { Expression::Path(it.span().fragment()) }), @@ -146,6 +156,26 @@ pub fn call_item(input: TokenSpan) -> IResult { )(input) } +pub fn struct_init_item(input: TokenSpan) -> IResult { + map( + tuple(( + token(tk::Ident), + delimited( + token(tk::LBrace), + separated_list0( + token(tk::Comma), + separated_pair(token(tk::Ident), token(tk::Colon), expression), + ), + token(tk::RBrace), + ), + )), + |(name, args)| StructInit { + name: name.span(), + args, + }, + )(input) +} + pub fn expression(input: TokenSpan) -> IResult { alt(( bitop, @@ -200,4 +230,9 @@ mod test { fn test_call() { fullexpr(TokenSpan::new(&tok("a()"))).unwrap(); } + + #[test] + fn test_struct_init() { + fullexpr(TokenSpan::new(&tok("a{}"))).unwrap(); + } }