ast: Allow type specifier in let statement

This commit is contained in:
John 2024-02-26 15:49:55 -06:00
parent 490d320633
commit ffa313eea8
4 changed files with 15 additions and 9 deletions

View File

@ -241,6 +241,7 @@ pub enum StmtKind {
pub struct Let { pub struct Let {
pub mutable: Mutability, pub mutable: Mutability,
pub name: Identifier, pub name: Identifier,
pub ty: Option<Box<Ty>>,
pub init: Option<Box<Expr>>, pub init: Option<Box<Expr>>,
} }

View File

@ -252,8 +252,11 @@ mod display {
} }
impl Display for Let { impl Display for Let {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let Self { mutable, name, init } = self; let Self { mutable, name, ty, init } = self;
write!(f, "let {mutable}{name}")?; write!(f, "let {mutable}{name}")?;
if let Some(value) = ty {
write!(f, ": {value}")?;
}
if let Some(value) = init { if let Some(value) = init {
write!(f, " = {value}")?; write!(f, " = {value}")?;
} }

View File

@ -398,13 +398,9 @@ pub mod interpret {
} }
impl Interpret for Let { impl Interpret for Let {
fn interpret(&self, env: &mut Environment) -> IResult<ConValue> { fn interpret(&self, env: &mut Environment) -> IResult<ConValue> {
let Let { mutable: _, name: Identifier(name), init } = self; let Let { mutable: _, name: Identifier(name), ty: _, init } = self;
if let Some(init) = init { let init = init.as_ref().map(|i| i.interpret(env)).transpose()?;
let init = init.interpret(env)?; env.insert(name, init);
env.insert(name, Some(init));
} else {
env.insert(name, None);
}
Ok(ConValue::Empty) Ok(ConValue::Empty)
} }
} }

View File

@ -785,7 +785,13 @@ impl<'t> Parser<'t> {
Ok(Let { Ok(Let {
mutable: self.mutability()?, mutable: self.mutability()?,
name: self.identifier()?, name: self.identifier()?,
init: if Type::Eq == self.peek_type(Parsing::Let)? { ty: if Ok(Type::Colon) == self.peek_type(Parsing::Let) {
self.consume_peeked();
Some(self.ty()?.into())
} else {
None
},
init: if Ok(Type::Eq) == self.peek_type(Parsing::Let) {
self.consume_peeked(); self.consume_peeked();
Some(self.expr()?.into()) Some(self.expr()?.into())
} else { } else {