ReviewOS

home-lang/home

Parser: implicit-return block expression { expr } (234+ kernel sites)

#56
Closed glennmichael123 opened this 24 days ago · 0 comments
24 days ago

Problem

The parser does not accept Rust-style implicit-return block expressions where the final expression in a { ... } block is the return value. Today this fails with Expected semicolon or newline between statements:

fn read_u8(addr: u64): u8 {
    unsafe { *(addr as *const u8) }       // ← fails: no semicolon, but we mean "return this"
}

The fix with explicit return parses fine:

fn read_u8(addr: u64): u8 {
    unsafe { return *(addr as *const u8) }
}

But this means every implicit-return block fails.

Scope

Kernel-wide grep: ~234 multi-line unsafe { ... } blocks plus dozens of inline unsafe { expr } blocks. The kernel author wrote them in this style throughout the kernel/src/power/, kernel/src/arch/, and kernel/src/drivers/ trees.

Expected behavior

In a brace block (whether unsafe-prefixed or plain), if the final element is an expression (not terminated by ;/newline-with-statement-shape) and the block appears in expression position (e.g. as a function body's last statement, or as the RHS of a let), the block evaluates to that expression.

Examples:

let x = { 1 + 2 };                     // x = 3
let y = if cond { 1 } else { 2 };      // already works (if-as-expression #54)
fn f(): u32 { 5 }                      // implicit return — the body block evaluates to 5
fn g(): u32 { unsafe { *p } }          // unsafe wrapper around implicit-return block

If the final element ends with ; or is a statement-only form (return, while, etc.), the block evaluates to void as today.

Implementation hint

In parseBlockStatement (or wherever brace blocks are handled), when about to emit the closing }, inspect the last parsed item:

  • If it's an expression statement without trailing semicolon, mark the block as having a tail-expression result.
  • Codegen lowers tail-expression to a result temporary; type system uses the tail-expression type as the block type (matching if/switch arm-join behavior).

The unsafe keyword is already accepted as a no-op block prefix per spot-test — no changes needed there.

Affected (sample)

  • kernel/src/power/acpi.home (multiple unsafe { *(addr as *const T) } blocks)
  • kernel/src/arch/arm64/rpi/* (multiple)
  • And 200+ other inline-style unsafe blocks across kernel/src/

Tests

Positive:

  • let x = { 5 }; → x is u32 (or inferred), value 5
  • let x = unsafe { 5 }; → same
  • fn f(): u32 { 5 } (implicit return)
  • Nested: let y = { let z = 1; z + 1 };

Regression:

  • Statement-only blocks (e.g. { foo(); bar(); }) still parse as void-result.
  • Explicit return within block still works.

Acceptance

  1. Many kernel files that currently fail at unsafe { expr } lines now parse past them.
  2. Existing test suite green.

Sign in to comment on this issue.