Skip to content

Commit 781846b

Browse files
author
Jesús Lapastora
authored
While loops (#2297)
<!-- ELLIPSIS_HIDDEN --> > [!IMPORTANT] > Add support for `while`, `break`, and `continue` statements in BAML, including type checking, validation, and tests. > > - **Behavior**: > - Add support for `while`, `break`, and `continue` statements in `codegen.rs`, `hir/mod.rs`, and `thir.rs`. > - Implement type checking for `while`, `break`, and `continue` in `thir/typecheck.rs`. > - Update parser to handle `while`, `break`, and `continue` in `parse_expr.rs` and `datamodel.pest`. > - Add validation for `while`, `break`, and `continue` in `expr_fns.rs`. > - **Tests**: > - Add tests for `while`, `break`, and `continue` in `vm.rs` and `bytecode_files/loops`. > - Add validation tests for `while`, `break`, and `continue` in `validation_files/loops`. > - **Misc**: > - Update `README.md` to reflect new loop functionality. > - Minor logging changes in `app.py`. > > <sup>This description was created by </sup>[<img alt="Ellipsis" src="https://img.shields.io/badge/Ellipsis-blue?color=175173">](https://www.ellipsis.dev?ref=BoundaryML%2Fbaml&utm_source=github&utm_medium=referral)<sup> for a27c2e7. You can [customize](https://app.ellipsis.dev/BoundaryML/settings/summaries) this summary. It will automatically update as commits are pushed.</sup> <!-- ELLIPSIS_HIDDEN -->
1 parent 2f6be15 commit 781846b

30 files changed

Lines changed: 1422 additions & 62 deletions

‎engine/baml-compiler/src/codegen.rs‎

Lines changed: 312 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,8 @@ struct HirCompiler<'g> {
189189
/// Scope stack.
190190
scopes: Vec<Scope>,
191191

192+
current_loop: Option<LoopInfo>,
193+
192194
/// Locals in scope.
193195
locals_in_scope: Vec<HashMap<String, usize>>,
194196

@@ -202,6 +204,15 @@ struct HirCompiler<'g> {
202204
objects: &'g mut Vec<Object>,
203205
}
204206

207+
#[derive(Debug)]
208+
struct LoopInfo {
209+
/// Instruction index indicating start of the loop. Used for lowering `continue`.
210+
pub start_insn: isize,
211+
/// List of jump instruction locations to be patched when loop construction is done.
212+
/// They will point to the loop exit. Used for admitting arbitrary `break`s.
213+
pub break_patch_list: Vec<usize>,
214+
}
215+
205216
impl<'g> HirCompiler<'g> {
206217
fn new(
207218
globals: &'g HashMap<String, usize>,
@@ -215,6 +226,7 @@ impl<'g> HirCompiler<'g> {
215226
llm_functions,
216227
objects,
217228
locals: HashMap::new(),
229+
current_loop: None,
218230
bytecode: Bytecode::new(),
219231
scopes: Vec::new(),
220232
current_source_line: 0,
@@ -289,7 +301,6 @@ impl<'g> HirCompiler<'g> {
289301
self.compile_expression(value);
290302
self.track_local(name);
291303
}
292-
293304
hir::Statement::Declare { name, .. } => {
294305
// For mutable references, we need to allocate space on the stack
295306
// We'll push a null/undefined value as placeholder
@@ -328,21 +339,17 @@ impl<'g> HirCompiler<'g> {
328339

329340
self.emit(Instruction::StoreVar(self.locals[name]));
330341
}
331-
332342
hir::Statement::DeclareAndAssign { name, value, .. } => {
333343
self.compile_expression(value);
334344
self.track_local(name);
335345
}
336-
337346
hir::Statement::Return { expr, .. } => {
338347
self.compile_expression(expr);
339348
self.emit(Instruction::Return);
340349
}
341-
342350
hir::Statement::Expression { expr, .. } => {
343351
self.compile_expression(expr);
344352
}
345-
346353
hir::Statement::SemicolonExpression { expr, .. } => {
347354
self.compile_expression(expr);
348355
// This could be a function call or any other random expression
@@ -354,17 +361,20 @@ impl<'g> HirCompiler<'g> {
354361
// binding) then implicitly drop the value.
355362
self.emit(Instruction::Pop(1));
356363
}
357-
358364
hir::Statement::ForLoop { .. } => {
359365
todo!()
360366
}
361-
362367
hir::Statement::While {
363368
condition, block, ..
364369
} => {
365370
// Remember where the loop starts
366371
let loop_start = self.bytecode.instructions.len() as isize;
367372

373+
let old_loop_status = self.current_loop.replace(LoopInfo {
374+
start_insn: loop_start,
375+
break_patch_list: Vec::new(),
376+
});
377+
368378
// Compile condition
369379
self.compile_expression(condition);
370380

@@ -382,11 +392,39 @@ impl<'g> HirCompiler<'g> {
382392
let offset = -(loop_end - loop_start);
383393
self.emit(Instruction::Jump(offset));
384394

385-
// Patch exit jump
386-
self.patch_jump(exit_jump);
395+
let loop_info = std::mem::replace(&mut self.current_loop, old_loop_status)
396+
.expect("should have been pushed before when grabbing old_status");
387397

398+
// patch exit jump so that it pops condition
399+
self.patch_jump(exit_jump);
388400
// Pop condition
389401
self.emit(Instruction::Pop(1));
402+
403+
// Patch breaks. Since they are executed *inside* the loop body, the condition is
404+
// alredy popped.
405+
for jump_loc in loop_info.break_patch_list {
406+
self.patch_jump(jump_loc);
407+
}
408+
}
409+
hir::Statement::Break(span) => {
410+
// NOTE: right now this will generate redundant code when using
411+
// `if condition { break }`, since `if` will generate its own jump location and we
412+
// will end up with a conditional jump and a regular jump together.
413+
let exit_jump = self.emit(Instruction::Jump(0));
414+
415+
let cur_loop = self.current_loop.as_mut().expect("`break` must have a loop wrapping it, and this should have been checked by validation");
416+
417+
cur_loop.break_patch_list.push(exit_jump);
418+
}
419+
hir::Statement::Continue(span) => {
420+
let cur_loop = self.current_loop.as_ref().expect("`continue` must have a loop wrapping it, and this should have been checked by validation");
421+
422+
// jump back to the start.
423+
let loop_start = cur_loop.start_insn;
424+
let continue_loc = self.bytecode.instructions.len() as isize;
425+
let offset = -(continue_loc - loop_start);
426+
427+
self.emit(Instruction::Jump(offset));
390428
}
391429
}
392430
}
@@ -1566,4 +1604,269 @@ mod tests {
15661604
)],
15671605
})
15681606
}
1607+
1608+
#[test]
1609+
fn while_loop_gcd() -> anyhow::Result<()> {
1610+
assert_compiles(Program {
1611+
source: r#"
1612+
fn GCD(mut a: int, mut b: int) -> int {
1613+
while (a != b) {
1614+
if a > b {
1615+
a = a - b;
1616+
} else {
1617+
b = b - a;
1618+
}
1619+
}
1620+
1621+
a
1622+
}
1623+
"#,
1624+
expected: vec![(
1625+
"GCD",
1626+
vec![
1627+
// while (a != b)
1628+
Instruction::LoadVar(1),
1629+
Instruction::LoadVar(2),
1630+
Instruction::CmpOp(CmpOp::NotEq),
1631+
Instruction::JumpIfFalse(18),
1632+
Instruction::Pop(1),
1633+
// if a > b { a = a - b; } else { b = b - a; }
1634+
Instruction::LoadVar(1),
1635+
Instruction::LoadVar(2),
1636+
Instruction::CmpOp(CmpOp::Gt),
1637+
Instruction::JumpIfFalse(7),
1638+
Instruction::Pop(1),
1639+
Instruction::LoadVar(1),
1640+
Instruction::LoadVar(2),
1641+
Instruction::BinOp(BinOp::Sub),
1642+
Instruction::StoreVar(1),
1643+
Instruction::Jump(6),
1644+
Instruction::Pop(1),
1645+
Instruction::LoadVar(2),
1646+
Instruction::LoadVar(1),
1647+
Instruction::BinOp(BinOp::Sub),
1648+
Instruction::StoreVar(2),
1649+
// jump back to loop start
1650+
Instruction::Jump(-20),
1651+
// exit loop: pop condition and return a
1652+
Instruction::Pop(1),
1653+
Instruction::LoadVar(1),
1654+
Instruction::Return,
1655+
],
1656+
)],
1657+
})
1658+
}
1659+
1660+
#[test]
1661+
fn break_factorial() -> anyhow::Result<()> {
1662+
assert_compiles(Program {
1663+
source: r#"
1664+
fn Factorial(mut limit: int) -> int {
1665+
let mut result = 1;
1666+
1667+
while true {
1668+
if limit == 0 {
1669+
break;
1670+
}
1671+
result = result * limit;
1672+
limit = limit - 1;
1673+
}
1674+
1675+
result
1676+
}
1677+
"#,
1678+
expected: vec![(
1679+
"Factorial",
1680+
vec![
1681+
// let mut result = 1;
1682+
Instruction::LoadConst(0),
1683+
// while true { ... }
1684+
Instruction::LoadConst(1),
1685+
Instruction::JumpIfFalse(19),
1686+
Instruction::Pop(1),
1687+
// if limit == 0 { break; }
1688+
Instruction::LoadVar(1),
1689+
Instruction::LoadConst(2),
1690+
Instruction::CmpOp(CmpOp::Eq),
1691+
Instruction::JumpIfFalse(4),
1692+
Instruction::Pop(1),
1693+
Instruction::Jump(13),
1694+
Instruction::Jump(2),
1695+
Instruction::Pop(1),
1696+
// result = result * limit;
1697+
Instruction::LoadVar(2),
1698+
Instruction::LoadVar(1),
1699+
Instruction::BinOp(BinOp::Mul),
1700+
Instruction::StoreVar(2),
1701+
// limit = limit - 1;
1702+
Instruction::LoadVar(1),
1703+
Instruction::LoadConst(3),
1704+
Instruction::BinOp(BinOp::Sub),
1705+
Instruction::StoreVar(1),
1706+
// loop back and exit
1707+
Instruction::Jump(-19),
1708+
Instruction::Pop(1),
1709+
// return result
1710+
Instruction::LoadVar(2),
1711+
Instruction::Return,
1712+
],
1713+
)],
1714+
})
1715+
}
1716+
1717+
#[test]
1718+
fn continue_factorial() -> anyhow::Result<()> {
1719+
assert_compiles(Program {
1720+
source: r#"
1721+
fn Factorial(mut limit: int) -> int {
1722+
let mut result = 1;
1723+
1724+
// used to make the loop break without relying on `break` implementation.
1725+
let mut should_continue = true;
1726+
while should_continue {
1727+
result = result * limit;
1728+
limit = limit - 1;
1729+
1730+
if limit != 0 {
1731+
continue;
1732+
} else {
1733+
should_continue = false;
1734+
}
1735+
}
1736+
1737+
result
1738+
}
1739+
"#,
1740+
expected: vec![(
1741+
"Factorial",
1742+
vec![
1743+
// let mut result = 1;
1744+
Instruction::LoadConst(0),
1745+
// let mut should_continue = true;
1746+
Instruction::LoadConst(1),
1747+
// while should_continue { ... }
1748+
Instruction::LoadVar(3),
1749+
Instruction::JumpIfFalse(21),
1750+
Instruction::Pop(1),
1751+
// result = result * limit;
1752+
Instruction::LoadVar(2),
1753+
Instruction::LoadVar(1),
1754+
Instruction::BinOp(BinOp::Mul),
1755+
Instruction::StoreVar(2),
1756+
// limit = limit - 1;
1757+
Instruction::LoadVar(1),
1758+
Instruction::LoadConst(2),
1759+
Instruction::BinOp(BinOp::Sub),
1760+
Instruction::StoreVar(1),
1761+
// if limit != 0 { continue; } else { should_continue = false; }
1762+
Instruction::LoadVar(1),
1763+
Instruction::LoadConst(3),
1764+
Instruction::CmpOp(CmpOp::NotEq),
1765+
Instruction::JumpIfFalse(4),
1766+
Instruction::Pop(1),
1767+
Instruction::Jump(-16),
1768+
Instruction::Jump(4),
1769+
Instruction::Pop(1),
1770+
Instruction::LoadConst(4),
1771+
Instruction::StoreVar(3),
1772+
Instruction::Jump(-21),
1773+
Instruction::Pop(1),
1774+
// return result
1775+
Instruction::LoadVar(2),
1776+
Instruction::Return,
1777+
],
1778+
)],
1779+
})
1780+
}
1781+
1782+
#[test]
1783+
fn continue_nested() -> anyhow::Result<()> {
1784+
assert_compiles(Program {
1785+
source: r#"
1786+
fn Nested() -> int {
1787+
while true {
1788+
while false {
1789+
continue;
1790+
}
1791+
if false {
1792+
continue;
1793+
}
1794+
}
1795+
5
1796+
}
1797+
"#,
1798+
expected: vec![(
1799+
"Nested",
1800+
vec![
1801+
Instruction::LoadConst(0),
1802+
Instruction::JumpIfFalse(15),
1803+
Instruction::Pop(1),
1804+
Instruction::LoadConst(1),
1805+
Instruction::JumpIfFalse(4),
1806+
Instruction::Pop(1),
1807+
Instruction::Jump(-3),
1808+
Instruction::Jump(-4),
1809+
Instruction::Pop(1),
1810+
Instruction::LoadConst(2),
1811+
Instruction::JumpIfFalse(4),
1812+
Instruction::Pop(1),
1813+
Instruction::Jump(-12),
1814+
Instruction::Jump(2),
1815+
Instruction::Pop(1),
1816+
Instruction::Jump(-15),
1817+
Instruction::Pop(1),
1818+
Instruction::LoadConst(3),
1819+
Instruction::Return,
1820+
],
1821+
)],
1822+
})
1823+
}
1824+
1825+
#[test]
1826+
fn break_nested() -> anyhow::Result<()> {
1827+
assert_compiles(Program {
1828+
source: r#"
1829+
fn Nested() -> int {
1830+
let mut a = 5;
1831+
while true {
1832+
while true {
1833+
a = a + 1;
1834+
break;
1835+
}
1836+
a = a + 1;
1837+
break;
1838+
}
1839+
a
1840+
}
1841+
"#,
1842+
expected: vec![(
1843+
"Nested",
1844+
vec![
1845+
Instruction::LoadConst(0),
1846+
Instruction::LoadConst(1),
1847+
Instruction::JumpIfFalse(18),
1848+
Instruction::Pop(1),
1849+
Instruction::LoadConst(2),
1850+
Instruction::JumpIfFalse(8),
1851+
Instruction::Pop(1),
1852+
Instruction::LoadVar(1),
1853+
Instruction::LoadConst(3),
1854+
Instruction::BinOp(BinOp::Add),
1855+
Instruction::StoreVar(1),
1856+
Instruction::Jump(3),
1857+
Instruction::Jump(-8),
1858+
Instruction::Pop(1),
1859+
Instruction::LoadVar(1),
1860+
Instruction::LoadConst(4),
1861+
Instruction::BinOp(BinOp::Add),
1862+
Instruction::StoreVar(1),
1863+
Instruction::Jump(3),
1864+
Instruction::Jump(-18),
1865+
Instruction::Pop(1),
1866+
Instruction::LoadVar(1),
1867+
Instruction::Return,
1868+
],
1869+
)],
1870+
})
1871+
}
15691872
}

0 commit comments

Comments
 (0)