plum

#treesitter#compiler#wasm

git clone https://git.pyrossh.dev/plum

A statically typed, imperative programming language inspired by rust, python


702fc35 — Peter John 2026-11-10T12:30:56+05:30
Grammar: crash is accepted as a branch of an inline if
compiler/checker/src/infer.rs CHANGED
@@ -443,6 +443,13 @@ pub(crate) fn inferExprInner(
443
443
  let tenv = bindCondEnv(&t.condition, env, ctx)?;
444
444
  let tt = inferExprWith(&t.then, &tenv, ctx, expected)?;
445
445
  let et = inferExprWith(&t.else_, env, ctx, expected)?;
446
+ // A branch that is `crash "msg"` gives no value: the `if` has the other branch's type.
447
+ let crashes = |e: &ast::Expr| matches!(&e.kind, ast::ExprKind::Block(b) if matches!(b.stmts.last().map(|s| &s.kind), Some(ast::StmtKind::Crash(_))));
448
+ match (crashes(&t.then), crashes(&t.else_)) {
449
+ (true, false) => return Ok(et),
450
+ (false, true) => return Ok(tt),
451
+ _ => {}
452
+ }
446
453
  if let Some(j) = joinTrait(expected, &[tt.clone(), et.clone()], ctx) {
447
454
  return Ok(j);
448
455
  }
compiler/core/src/parser.rs CHANGED
@@ -1443,11 +1443,19 @@ impl<'a> AstParser<'a> {
1443
1443
 
1444
1444
  fn parseInlineIf(&self, node: Node) -> Expr {
1445
1445
  // inline_if_expression: "if" condition "then" then "else" else
1446
+ // A branch may be `crash "msg"`: a one-statement block that gives no value.
1446
1447
  let field = |name: &str| {
1447
1448
  node.child_by_field_name(name)
1449
+ .map(|n| match self.parseStmt(n).filter(|_| n.kind() == "crash") {
1450
+ Some(stmt) => {
1451
+ let mut e = Expr::Block(Box::new(Block { stmts: vec![stmt] }));
1452
+ e.span = self.spanOf(n);
1453
+ e
1454
+ }
1448
- .map(|n| {
1455
+ None => {
1449
- let u = self.unwrapExprNode(n);
1456
+ let u = self.unwrapExprNode(n);
1450
- self.parseExpression(u)
1457
+ self.parseExpression(u)
1458
+ }
1451
1459
  })
1452
1460
  .unwrap_or_else(|| self.missing(node))
1453
1461
  };
compiler/tooling/tree-sitter-plum/grammar.js CHANGED
@@ -760,6 +760,7 @@ module.exports = grammar({
760
760
  seq("..", field("value", $.expression)),
761
761
 
762
762
  // Inline `if`: `if c then a else b` (chains via `else if c2 then ...`).
763
+ // A branch may be `crash "msg"`: that path ends the program and gives no value.
763
764
  // Block `if` statements (indented bodies, no `then`) are the `if` rule.
764
765
  inline_if_expression: ($) =>
765
766
  prec.right(
@@ -768,9 +769,9 @@ module.exports = grammar({
768
769
  "if",
769
770
  field("condition", choice($.expression, $.bind_condition)),
770
771
  "then",
771
- field("then", $.expression),
772
+ field("then", choice($.expression, $.crash)),
772
773
  "else",
773
- field("else", $.expression),
774
+ field("else", choice($.expression, $.crash)),
774
775
  ),
775
776
  ),
776
777
 
compiler/tooling/tree-sitter-plum/src/grammar.json CHANGED
Binary file
compiler/tooling/tree-sitter-plum/src/node-types.json CHANGED
Binary file
compiler/tooling/tree-sitter-plum/src/parser.c CHANGED
Binary file
compiler/tooling/tree-sitter-plum/test/corpus/inline_if.txt CHANGED
@@ -137,3 +137,41 @@ fun g(n: Int) -> Int =
137
137
  (expression
138
138
  (primary_expression
139
139
  (integer))))))))
140
+
141
+ ================================================================================
142
+ inline if with a crash branch
143
+ ================================================================================
144
+
145
+ fun g(n: Int) -> Int =
146
+ if n > 0 then n else crash "neg"
147
+
148
+ --------------------------------------------------------------------------------
149
+
150
+ (source
151
+ (fn
152
+ (fn_identifier)
153
+ (param
154
+ (var_identifier)
155
+ (type
156
+ (type_identifier)))
157
+ (type
158
+ (type_identifier))
159
+ (body
160
+ (expression
161
+ (inline_if_expression
162
+ (expression
163
+ (comparison_operator
164
+ (primary_expression
165
+ (var_identifier))
166
+ (primary_expression
167
+ (integer))))
168
+ (expression
169
+ (primary_expression
170
+ (var_identifier)))
171
+ (crash
172
+ (expression
173
+ (primary_expression
174
+ (string
175
+ (string_start)
176
+ (string_content)
177
+ (string_end))))))))))
compiler/wasm-codegen/src/expr.rs CHANGED
@@ -59,7 +59,10 @@ fn compileExprNode(
59
59
  // A block `if` / `match` value: its statements run inline, the last value is the result.
60
60
  ast::Expr { kind: ast::ExprKind::Block(blk), .. } => {
61
61
  let ty = inferLocalType(expr, ctx);
62
+ if matches!(blk.stmts.last().map(|s| &s.kind), Some(ast::StmtKind::Crash(_))) {
63
+ // `if c then crash "msg" else v`: the branch traps, so no value is needed.
64
+ compileBlock(blk, body, ctx, state)?;
62
- if matches!(ty, PlumType::TUnit) {
65
+ } else if matches!(ty, PlumType::TUnit) {
63
66
  // A Unit-valued branch (a call to a Unit fn) leaves nothing on the stack: run the
64
67
  // statements, then the Unit value is the `i64` zero a Unit slot holds.
65
68
  compileBlock(blk, body, ctx, state)?;
compiler/wasm-codegen/tests/wasm_codegen/codegen_tests.rs CHANGED
@@ -2149,6 +2149,34 @@ fun main() -> Int =
2149
2149
  assert!(msgs[0].ends_with("main.plum:6:5"), "{}", msgs[0]);
2150
2150
  }
2151
2151
 
2152
+ /// `crash "msg"` as a branch of an inline `if` (once a parse error): the other branch gives
2153
+ /// the value, and the crashing one reports its message and position.
2154
+ #[test]
2155
+ fn inline_if_crash_branch() {
2156
+ let src = |arg: i64| {
2157
+ format!(
2158
+ "\
2159
+ import std/Str
2160
+ import std/Int
2161
+
2162
+ fun pos(n: Int) -> Int =
2163
+ if n > 0 then n else crash \"not positive: {{n}}\"
2164
+
2165
+ fun main() -> Int =
2166
+ pos({arg}) + 1
2167
+ "
2168
+ )
2169
+ };
2170
+ let (r, msgs) = runWithCrash("inlinecrash_ok", &src(4));
2171
+ assert_eq!(r, Ok(5));
2172
+ assert!(msgs.is_empty(), "{msgs:?}");
2173
+ let (r, msgs) = runWithCrash("inlinecrash", &src(-3));
2174
+ assert!(r.is_err());
2175
+ assert_eq!(msgs.len(), 1, "{msgs:?}");
2176
+ assert!(msgs[0].starts_with("not positive: -3 at "), "{}", msgs[0]);
2177
+ assert!(msgs[0].ends_with("main.plum:5:24"), "{}", msgs[0]);
2178
+ }
2179
+
2152
2180
  /// Master 9b8580b: wasmtime demangled a one-letter name (`g` became `__float128`), so a
2153
2181
  /// short function name is shown as `fn.g` in the name section.
2154
2182
  #[test]
tests/syntax/inline_if_crash.plum ADDED
@@ -0,0 +1,30 @@
1
+ # `crash "msg"` as a branch of an inline `if`: it was a parse error. The `if` has the type of
2
+ # its other branch; a crash can't run under `plum test`, so only the other paths are run here
3
+ # (the crashing one is `inline_if_crash_branch` in compiler/wasm-codegen's codegen_tests.rs).
4
+ import std/Int
5
+ import std/Str
6
+ import std/Option
7
+
8
+ struct P(x: Int)
9
+
10
+ fun positive(n: Int) -> Int =
11
+ if n > 0 then n else crash "not positive: {n}"
12
+
13
+ fun chained(n: Int) -> Int =
14
+ x := if n < 0 then crash "negative" else if n == 0 then crash "zero" else n
15
+ x + 1
16
+
17
+ fun boxed(n: Int) -> P =
18
+ if n < 0 then crash "negative" else P(x: n)
19
+
20
+ fun some(n: Int) -> Option[Int] =
21
+ if n < 0 then crash "negative" else Some(n)
22
+
23
+ fun never(n: Int) -> Unit =
24
+ if n < 0 then crash "negative" else crash "not negative"
25
+
26
+ test "an inline if with a crash branch has its other branch's value"
27
+ assert positive(2) == 2
28
+ assert chained(3) == 4
29
+ assert boxed(4).x == 4
30
+ assert some(5).unwrapOr(0) == 5