prepare for modules

This commit is contained in:
2025-04-25 04:16:54 -04:00
parent 0ceb82445e
commit 4e7c201690
30 changed files with 369 additions and 333 deletions
+47 -8
View File
@@ -1,4 +1,7 @@
use crate::ir::{Type, UInstruction, VarInst};
use crate::{
ir::{Type, UInstruction, VarInst},
parser::{PConstStatement, PStatementLike},
};
use super::{FnLowerCtx, FnLowerable, PBlock, PStatement};
@@ -6,12 +9,48 @@ impl FnLowerable for PBlock {
type Output = VarInst;
fn lower(&self, ctx: &mut FnLowerCtx) -> Option<VarInst> {
ctx.program.push();
for statement in &self.statements {
statement.lower(ctx);
let mut last = None;
let mut statements = Vec::new();
let mut fn_nodes = Vec::new();
let mut struct_nodes = Vec::new();
// first sort statements
for s in &self.statements {
let Some(s) = s.as_ref() else {
continue;
};
match s {
PStatementLike::Statement(s) => statements.push(s),
PStatementLike::Const(pconst_statement) => match pconst_statement {
PConstStatement::Fn(f) => fn_nodes.push(f),
PConstStatement::Struct(s) => struct_nodes.push(s),
},
}
}
// then lower const things
let mut structs = Vec::new();
for s in &struct_nodes {
structs.push(s.lower_name(ctx.program));
}
for (s, id) in struct_nodes.iter().zip(structs) {
if let Some(id) = id {
s.lower(id, ctx.program, ctx.output);
}
}
let mut fns = Vec::new();
for f in &fn_nodes {
fns.push(f.lower_name(ctx.program));
}
for (f, id) in fn_nodes.iter().zip(fns) {
if let Some(id) = id {
f.lower(id, ctx.program, ctx.output)
}
}
// then lower statements
for s in statements {
last = s.lower(ctx);
}
let res = self.result.as_ref().and_then(|r| r.lower(ctx));
ctx.program.pop();
res
last
}
}
@@ -19,7 +58,7 @@ impl FnLowerable for PStatement {
type Output = VarInst;
fn lower(&self, ctx: &mut FnLowerCtx) -> Option<VarInst> {
match self {
super::PStatement::Let(def, e) => {
PStatement::Let(def, e) => {
let def = def.lower(ctx.program, ctx.output)?;
let res = e.lower(ctx);
if let Some(res) = res {
@@ -30,7 +69,7 @@ impl FnLowerable for PStatement {
}
None
}
super::PStatement::Return(e) => {
PStatement::Return(e) => {
if let Some(e) = e {
let src = e.lower(ctx)?;
ctx.push_at(UInstruction::Ret { src }, src.span);
@@ -40,7 +79,7 @@ impl FnLowerable for PStatement {
}
None
}
super::PStatement::Expr(e) => e.lower(ctx),
PStatement::Expr(e) => e.lower(ctx),
}
}
}