buildlang 1.15.0

BuildLang (buildc): an effects-oriented compiler with a verified C path, shader output, experimental backends, opt-in linear types, and re-checkable accountability + scientific-runtime receipts
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
// ===============================================================================
// BUILDLANG PARSER - STATEMENT PARSING
// ===============================================================================
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2022-2026 Zain Dana Harper.
// ===============================================================================

//! Statement and block parsing.
//!
//! This module handles parsing of statements, blocks, and local bindings.

use super::{ParseError, ParseErrorKind, ParseResult, Parser};
use crate::ast::*;
use crate::lexer::{Delimiter, Keyword, TokenKind};

impl<'a> Parser<'a> {
    /// Parse a block: `{ statements... }`
    pub fn parse_block(&mut self) -> ParseResult<Block> {
        let start = self.expect(&TokenKind::OpenDelim(Delimiter::Brace))?.span;

        let mut stmts = Vec::new();

        while !self.check(&TokenKind::CloseDelim(Delimiter::Brace)) && !self.is_eof() {
            match self.parse_stmt() {
                Ok(stmt) => stmts.push(stmt),
                Err(e) => {
                    self.errors.push(e);
                    self.recover_to_stmt();
                }
            }
        }

        let end = self.expect(&TokenKind::CloseDelim(Delimiter::Brace))?.span;
        let span = start.merge(&end);

        Ok(Block {
            stmts,
            span,
            id: NodeId::DUMMY,
        })
    }

    /// Parse a statement.
    pub fn parse_stmt(&mut self) -> ParseResult<Stmt> {
        let attrs = self.parse_outer_attrs()?;
        let start = self.current_span();

        // Check for item statements
        if self.is_item_start() {
            let item = self.parse_item()?;
            let span = item.span;
            return Ok(Stmt::new(StmtKind::Item(Box::new(item)), span));
        }

        match self.current_kind().clone() {
            // =================================================================
            // LET STATEMENT
            // =================================================================
            TokenKind::Keyword(Keyword::Let) => self.parse_let_stmt(attrs),

            // =================================================================
            // SEMICOLON (empty statement)
            // =================================================================
            TokenKind::Semi => {
                self.advance();
                Ok(Stmt::new(StmtKind::Empty, start))
            }

            // =================================================================
            // EXPRESSION STATEMENT
            // =================================================================
            _ => self.parse_expr_stmt(attrs),
        }
    }

    /// Parse a let statement: `let pattern: type = expr;`
    fn parse_let_stmt(&mut self, attrs: Vec<Attribute>) -> ParseResult<Stmt> {
        let start = self.expect_keyword(Keyword::Let)?;

        let pattern = self.parse_pattern()?;

        let ty = if self.eat(&TokenKind::Colon) {
            Some(Box::new(self.parse_type()?))
        } else {
            None
        };

        let init = if self.eat(&TokenKind::Eq) {
            let value = self.parse_expr()?;

            // Check for else branch (let-else)
            let diverge = if self.eat_keyword(Keyword::Else) {
                let block = self.parse_block()?;
                let block_span = block.span;
                let expr = Expr {
                    kind: ExprKind::Block(Box::new(block)),
                    span: block_span,
                    id: NodeId::DUMMY,
                    attrs: Vec::new(),
                };
                Some(Box::new(expr))
            } else {
                None
            };

            Some(LocalInit {
                expr: Box::new(value),
                diverge,
            })
        } else {
            None
        };

        let end = self.expect(&TokenKind::Semi)?.span;
        let span = start.merge(&end);

        let local = Local {
            attrs,
            pattern,
            ty,
            init,
            span,
            id: NodeId::DUMMY,
        };

        Ok(Stmt::new(StmtKind::Local(Box::new(local)), span))
    }

    /// Parse an expression statement.
    fn parse_expr_stmt(&mut self, _attrs: Vec<Attribute>) -> ParseResult<Stmt> {
        // Statement position: a block-like leading expression (`if`, `match`,
        // `{...}`, a loop, `unsafe`/`async`/`handle`) terminates at its closing
        // brace and does not bind a trailing operator, so `if c { .. }` on one
        // line and `*ptr = v;` on the next parse as two statements.
        let expr = self.parse_stmt_expr()?;
        let start = expr.span;

        // Check if this is a block expression that doesn't need semicolon
        let needs_semi = !self.expr_is_complete(&expr);

        if self.eat(&TokenKind::Semi) {
            // Expression with semicolon - value is discarded
            let span = start.merge(&self.tokens[self.pos - 1].span);
            Ok(Stmt::new(StmtKind::Semi(Box::new(expr)), span))
        } else if needs_semi {
            // Check if we're at the end of a block
            if self.check(&TokenKind::CloseDelim(Delimiter::Brace)) {
                // Expression is the final expression of the block
                Ok(Stmt::new(StmtKind::Expr(Box::new(expr)), start))
            } else {
                // Missing semicolon: the exact fix inserts it right after
                // the expression, not at the next token.
                let after =
                    crate::lexer::Span::new(expr.span.end, expr.span.end, expr.span.source_id);
                Err(
                    ParseError::new(ParseErrorKind::ExpectedSemicolon, self.current_span())
                        .with_fix(crate::diagnostics::Fix::insert(
                            "add a `;` at the end of the statement",
                            after,
                            ";",
                            true,
                        )),
                )
            }
        } else {
            // Block expression, no semicolon needed
            Ok(Stmt::new(StmtKind::Expr(Box::new(expr)), start))
        }
    }

    /// Check if an expression is "complete" (doesn't require a semicolon).
    fn expr_is_complete(&self, expr: &Expr) -> bool {
        matches!(
            expr.kind,
            ExprKind::If { .. }
                | ExprKind::IfLet { .. }
                | ExprKind::Match { .. }
                | ExprKind::Loop { .. }
                | ExprKind::While { .. }
                | ExprKind::WhileLet { .. }
                | ExprKind::For { .. }
                | ExprKind::Block(_)
                | ExprKind::Unsafe(_)
                | ExprKind::Async { .. }
        )
    }

    /// Check if the current token starts an item.
    fn is_item_start(&self) -> bool {
        // Check for visibility first
        if self.check_keyword(Keyword::Pub) {
            return true;
        }

        // Check for outer attributes
        if self.check(&TokenKind::Pound) && !matches!(self.peek().kind, TokenKind::Not) {
            // Could be item with attributes
            return true;
        }

        match self.current_kind() {
            TokenKind::Keyword(kw) => match kw {
                // unsafe/async are only item starts when followed by fn/impl/trait/mod
                // (e.g., `unsafe fn`, `unsafe impl`). Standalone `unsafe { ... }` blocks
                // are expressions, not items.
                Keyword::Unsafe | Keyword::Async => {
                    matches!(
                        self.peek().kind,
                        TokenKind::Keyword(Keyword::Fn)
                            | TokenKind::Keyword(Keyword::Impl)
                            | TokenKind::Keyword(Keyword::Trait)
                            | TokenKind::Keyword(Keyword::Mod)
                            | TokenKind::Keyword(Keyword::Extern)
                    )
                }
                // `effect` starts an item only when followed by the effect
                // name (`effect Foo { .. }`). Used as a value (`effect.run()`,
                // or a local named `effect`), it is an expression handled by
                // the value-context-keyword path, not an item declaration.
                Keyword::Effect => {
                    matches!(self.peek().kind, TokenKind::Ident | TokenKind::RawIdent)
                }
                _ => matches!(
                    kw,
                    Keyword::Fn
                        | Keyword::Struct
                        | Keyword::Enum
                        | Keyword::Trait
                        | Keyword::Impl
                        | Keyword::Type
                        | Keyword::Const
                        | Keyword::Static
                        | Keyword::Mod
                        | Keyword::Use
                        | Keyword::Extern
                        | Keyword::Macro
                ),
            },
            _ => false,
        }
    }

    /// Parse multiple statements until end of block.
    pub fn parse_stmts(&mut self) -> ParseResult<Vec<Stmt>> {
        let mut stmts = Vec::new();

        while !self.check(&TokenKind::CloseDelim(Delimiter::Brace)) && !self.is_eof() {
            match self.parse_stmt() {
                Ok(stmt) => stmts.push(stmt),
                Err(e) => {
                    self.errors.push(e);
                    self.recover_to_stmt();
                }
            }
        }

        Ok(stmts)
    }

    /// Parse an optional block or expression.
    pub fn parse_block_or_expr(&mut self) -> ParseResult<Expr> {
        if self.check(&TokenKind::OpenDelim(Delimiter::Brace)) {
            let block = self.parse_block()?;
            let span = block.span;
            Ok(Expr::new(ExprKind::Block(Box::new(block)), span))
        } else {
            self.parse_expr()
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lexer::{Lexer, SourceFile as LexerSourceFile};

    fn parse_stmt_from_str(s: &str) -> ParseResult<Stmt> {
        let source = LexerSourceFile::new("test.bld", format!("fn test() {{ {} }}", s));
        let mut lexer = Lexer::new(&source);
        let tokens = lexer.tokenize().unwrap();
        let mut parser = Parser::new(&source, tokens);
        // Skip fn test() {
        parser.advance(); // fn
        parser.advance(); // test
        parser.advance(); // (
        parser.advance(); // )
        parser.advance(); // {
        parser.parse_stmt()
    }

    #[test]
    fn test_let_stmt() {
        // Basic let
        let result = parse_stmt_from_str("let x = 42;");
        assert!(result.is_ok());

        // Let with type
        let result = parse_stmt_from_str("let x: i32 = 42;");
        assert!(result.is_ok());

        // Let without initializer
        let result = parse_stmt_from_str("let x: i32;");
        assert!(result.is_ok());
    }

    #[test]
    fn test_expr_stmt() {
        let result = parse_stmt_from_str("x + 1;");
        assert!(result.is_ok());
    }

    /// Parse a whole function body and return the parser's collected errors.
    fn parse_fn_body_errors(body: &str) -> Vec<String> {
        let source = LexerSourceFile::new("test.bld", format!("fn test() {{ {} }}", body));
        let mut lexer = Lexer::new(&source);
        let tokens = lexer.tokenize().unwrap();
        let mut parser = Parser::new(&source, tokens);
        let _ = parser.parse();
        parser.errors().iter().map(|e| e.message()).collect()
    }

    #[test]
    fn block_like_statement_does_not_swallow_next_deref_assignment() {
        // A block-like statement (`if`, `match`, bare block, loop, `unsafe`)
        // is complete at its closing brace: a following line that begins with
        // a prefix operator (`*ptr = v`, `*acc += n`, `-x`) is a SEPARATE
        // statement, not a trailing operand of the block. Before the
        // ExprWithBlock fix the `*` bound as multiplication continuing the
        // block, and the later `=`/`+=` made the block the invalid left side
        // of an assignment ("invalid left-hand side of assignment"). Each case
        // is the shape found in the corpus (oracle/lib, nexus/diagnostics).
        let bodies = [
            "if sum > 0.0 { normalize(); }\n*run_length_probs = new_probs;",
            "if a > b { record(); }\n*self.usage.entry(k).or_insert(0) += size;",
            "match tag { A => one(), B => two() }\n*out = done;",
            "unsafe { touch(); }\n*p = q;",
            "{ let t = 1; use_it(t); }\n*p = q;",
        ];
        for body in bodies {
            let errors = parse_fn_body_errors(body);
            assert!(
                errors.is_empty(),
                "block-like statement followed by a deref-assignment should parse \
                 as two statements, got errors for {body:?}: {errors:?}"
            );
        }
    }

    #[test]
    fn assignment_with_block_like_right_side_still_binds() {
        // The fix is scoped to statement position: a block-like expression on
        // the RIGHT of `=` (value position) is unaffected and still parses as
        // the assignment's value. This guards against a fix that stopped
        // operator binding everywhere.
        let errors = parse_fn_body_errors("let x = if c { 1 } else { 2 };\nuse_it(x);");
        assert!(
            errors.is_empty(),
            "a block-like expression in value position must still parse, got: {errors:?}"
        );
    }

    #[test]
    fn effect_as_value_is_not_an_item_start() {
        // `effect` is a value-context keyword. When it names a value -- a local
        // called `effect`, a method call on one -- a statement that starts with
        // it must parse as an expression, not an effect declaration. These are
        // the corpus forms (photon/post_processing, refract/system, refract/lib,
        // wavelength/video) that reported `expected identifier, found `.`` when
        // `effect` was treated as an unconditional item start.
        let bodies = [
            "effect.execute(ctx, cmd, input, out);",
            "effect.apply(ctx);",
            "effect.process(&mut frame);",
            "let e = effect;",
        ];
        for body in bodies {
            let errors = parse_fn_body_errors(body);
            assert!(
                errors.is_empty(),
                "`effect` as a value should parse as an expression, got errors for {body:?}: {errors:?}"
            );
        }
    }

    #[test]
    fn effect_declaration_is_still_an_item_start() {
        // The value-context change above must not stop `effect <Name> { .. }`
        // from parsing as an effect declaration: `effect` followed by an
        // identifier is still an item start.
        let errors = parse_fn_body_errors("effect Logger {}");
        assert!(
            errors.is_empty(),
            "`effect Name {{}}` should still parse as an effect declaration, got: {errors:?}"
        );
    }

    #[test]
    fn if_let_block_statement_needs_no_semicolon() {
        // A non-tail `if let { ... }` is a block-expression statement, so no
        // trailing `;` is required -- the same as a plain `if { ... }`. A second
        // statement follows the first, so the first is not in tail position.
        let errors = parse_fn_body_errors(
            "if let Some(x) = opt { use_it(x); }\n\
             if let Some(y) = other { use_it(y); }\n\
             done();",
        );
        assert!(
            errors.is_empty(),
            "consecutive `if let` statements should parse without a semicolon, got: {errors:?}"
        );
    }

    #[test]
    fn plain_if_block_statement_needs_no_semicolon() {
        // Control: the plain `if` case that already worked, guarding the shared
        // `expr_is_complete` path against regression.
        let errors = parse_fn_body_errors(
            "if a { one(); }\n\
             if b { two(); }\n\
             done();",
        );
        assert!(
            errors.is_empty(),
            "consecutive `if` statements should parse, got: {errors:?}"
        );
    }

    #[test]
    fn turbofish_on_path_call_parses() {
        // `path::seg::<T>()` turbofish on a plain `::`-path (not a `.method`
        // call and not `Self::`) was rejected with `expected identifier, found
        // `<``, because the path loop ate the `::` and then demanded an ident.
        let errors = parse_fn_body_errors(
            "let n = std::mem::size_of::<i32>();\n\
             let r = rand::random::<f32>();\n\
             let v = Vec::<u8>::new();",
        );
        assert!(
            errors.is_empty(),
            "turbofish path calls should parse, got: {errors:?}"
        );
    }
}