Block/scope parsing.

This commit is contained in:
2026-11-15 12:11:26 +01:00
parent 3002eedbdf
commit 592e476f29
2 changed files with 55 additions and 1 deletions
+13
View File
@@ -5,6 +5,7 @@ pub enum Stmt {
Let(Let), Let(Let),
Assign(Assign), Assign(Assign),
Expr(Expr), Expr(Expr),
Block(Block),
Fn(FnDef), Fn(FnDef),
} }
@@ -26,6 +27,12 @@ impl From<Expr> for Stmt {
} }
} }
impl From<Block> for Stmt {
fn from(block: Block) -> Self {
Stmt::Block(block)
}
}
impl From<FnDef> for Stmt { impl From<FnDef> for Stmt {
fn from(fn_def: FnDef) -> Self { fn from(fn_def: FnDef) -> Self {
Stmt::Fn(fn_def) Stmt::Fn(fn_def)
@@ -55,6 +62,12 @@ pub struct FnDef {
pub span: Span, pub span: Span,
} }
#[derive(Debug, PartialEq)]
pub struct Block {
pub stmts: Vec<Stmt>,
pub span: Span,
}
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
pub struct FnParam { pub struct FnParam {
pub name: Ident, pub name: Ident,
+42 -1
View File
@@ -1,7 +1,7 @@
use std::iter::Peekable; use std::iter::Peekable;
use crate::{ use crate::{
ast::{Assign, Expr, FnCall, Ident, Let, LitNumber, LitString, Stmt}, ast::{Assign, Block, Expr, FnCall, Ident, Let, LitNumber, LitString, Stmt},
lexer::Token, lexer::Token,
span::{Span, Spanned}, span::{Span, Spanned},
}; };
@@ -114,6 +114,19 @@ where
} }
.into()) .into())
} }
Some(Token::CurlyBracketL) => {
let lbrace = self.next().unwrap();
let mut stmts = Vec::new();
while self.peek() != Some(&Token::CurlyBracketR) {
stmts.push(self.parse_stmt()?);
}
let rbrace = self.next_expected(Token::CurlyBracketR)?;
Ok(Block {
stmts,
span: lbrace.span_to(&rbrace),
}
.into())
}
Some(Token::Fn) => { Some(Token::Fn) => {
unimplemented!() unimplemented!()
} }
@@ -397,6 +410,34 @@ mod tests {
pretty_assertions::assert_eq!(parser.next(), None); pretty_assertions::assert_eq!(parser.next(), None);
} }
#[test]
fn stmt_block() {
let input = "{ x = 42; }";
let lexer = Lexer::new(input);
let mut parser = Parser::new(input, lexer);
pretty_assertions::assert_eq!(
parser.parse_stmt(),
Ok(Stmt::Block(Block {
stmts: vec![Stmt::Assign(Assign {
name: Ident {
name: "x".to_string(),
span: Span::new(2, 3),
},
value: Expr::Literal(
LitNumber {
value: 42.0,
span: Span::new(6, 8)
}
.into()
),
span: Span::new(2, 9),
})],
span: Span::new(0, 11),
}))
);
pretty_assertions::assert_eq!(parser.next(), None);
}
#[test] #[test]
fn expr_numbers() { fn expr_numbers() {
let input = "500.0"; let input = "500.0";