plum

#treesitter#compiler#wasm

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

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


0278c12 — Peter John 2026-11-06T18:48:43+05:30
Simpler language: block if and match as values, .= and spread paths
Files changed (43) hide show
  1. compiler/checker/src/infer.rs +5 -0
  2. compiler/checker/src/matchcheck.rs +19 -1
  3. compiler/checker/src/stmt.rs +35 -0
  4. compiler/checker/tests/checker/main.rs +1 -0
  5. compiler/checker/tests/checker/syntax_tests.rs +119 -0
  6. compiler/core/src/ast.rs +7 -0
  7. compiler/core/src/blocks.rs +317 -0
  8. compiler/core/src/builtin_usage.rs +1 -0
  9. compiler/core/src/closure_escape.rs +2 -0
  10. compiler/core/src/enum_checks.rs +1 -0
  11. compiler/core/src/formatter.rs +5 -1
  12. compiler/core/src/lib.rs +2 -0
  13. compiler/core/src/lower.rs +8 -0
  14. compiler/core/src/parser.rs +112 -20
  15. compiler/core/src/purity.rs +1 -0
  16. compiler/core/src/question.rs +16 -1
  17. compiler/core/src/spread_paths.rs +207 -0
  18. compiler/core/src/uniqueness.rs +2 -0
  19. compiler/core/src/visit.rs +4 -0
  20. compiler/core/src/whistle.rs +2 -0
  21. compiler/core/tests/core/main.rs +1 -0
  22. compiler/core/tests/core/syntax_test.rs +78 -0
  23. compiler/tooling/tree-sitter-plum/grammar.js +18 -6
  24. compiler/tooling/tree-sitter-plum/queries/plum/format.scm +1 -0
  25. compiler/tooling/tree-sitter-plum/queries/plum/highlights.scm +1 -0
  26. compiler/tooling/tree-sitter-plum/src/grammar.json +0 -0
  27. compiler/tooling/tree-sitter-plum/src/node-types.json +0 -0
  28. compiler/tooling/tree-sitter-plum/src/parser.c +0 -0
  29. compiler/tooling/tree-sitter-plum/test/corpus/annotated_decl.txt +37 -36
  30. compiler/tooling/tree-sitter-plum/test/corpus/block_values.txt +449 -0
  31. compiler/tooling/tree-sitter-plum/test/corpus/closure_match_arg.txt +14 -13
  32. compiler/tooling/tree-sitter-plum/test/corpus/digit_names.txt +47 -42
  33. compiler/tooling/tree-sitter-plum/test/corpus/enum.txt +15 -14
  34. compiler/tooling/tree-sitter-plum/test/corpus/function.txt +14 -13
  35. compiler/tooling/tree-sitter-plum/test/corpus/if.txt +74 -72
  36. compiler/tooling/tree-sitter-plum/test/corpus/match.txt +145 -142
  37. compiler/tooling/tree-sitter-plum/test/corpus/single_letter.txt +28 -26
  38. compiler/tooling/vscode-plum/syntaxes/plum.tmLanguage.json +2 -1
  39. compiler/wasm-codegen/src/closures.rs +2 -0
  40. compiler/wasm-codegen/src/expr.rs +3 -0
  41. compiler/wasm-codegen/src/fnbody.rs +2 -0
  42. tests/syntax/block_values.plum +141 -0
  43. tests/syntax/update_paths.plum +59 -0
compiler/checker/src/infer.rs CHANGED
@@ -186,6 +186,11 @@ pub(crate) fn inferExprInner(
186
186
  ast::Expr { kind: ast::ExprKind::Question(_), .. } => {
187
187
  Err("'?' is not allowed here: it was not lowered (see the earlier error)".to_string())
188
188
  }
189
+ // Lifted into statements before checking (`plum_core::blocks`); one that is still here
190
+ // sits where no statement can come first.
191
+ ast::Expr { kind: ast::ExprKind::Block(_), .. } => {
192
+ Err("a block 'if' or 'match' used as a value is not allowed here".to_string())
193
+ }
189
194
  ast::Expr { kind: ast::ExprKind::Closure(cl), .. } => {
190
195
  let self_name = withCheck(|s| s.closure_self.borrow_mut().take());
191
196
  let mut closure_env = env.clone();
compiler/checker/src/matchcheck.rs CHANGED
@@ -190,7 +190,7 @@ pub(crate) fn coverRows<'a>(
190
190
 
191
191
  pub(crate) fn checkMatch(
192
192
  m: &ast::Match,
193
- env: &TypeEnv,
193
+ env: &mut TypeEnv,
194
194
  declared_ret: &PlumType,
195
195
  fn_name: &str,
196
196
  fn_pos: (usize, usize),
@@ -261,6 +261,23 @@ pub(crate) fn checkMatch(
261
261
  ),
262
262
  ));
263
263
  }
264
+ // A discarded `f()?` (`plum_core::question`): the unwrapped value must be Unit.
265
+ for (k, v) in case_env.iter().filter(|(k, _)| k.starts_with(plum_core::question::UNUSED_PREFIX)) {
266
+ let ty = resolveRecorded(&v.body);
267
+ if !matches!(ty, PlumType::TUnit | PlumType::TVar(_)) {
268
+ let callee = k[plum_core::question::UNUSED_PREFIX.len()..].rsplit_once('_').map(|x| x.0).unwrap_or("value");
269
+ let sp = m.subjects.first().map(|s| s.span).unwrap_or_default();
270
+ let (l, c) = if sp.startLine > 0 { (sp.startLine, sp.startColumn) } else { fn_pos };
271
+ errors.push(CheckError::at(
272
+ l,
273
+ c,
274
+ format!(
275
+ "fn '{}': result of '{}' is unused ({}); assign it, or discard it explicitly with '_ := ...'",
276
+ fn_name, callee, ty
277
+ ),
278
+ ));
279
+ }
280
+ }
264
281
  if let Some(guard) = &case.guard {
265
282
  match inferExpr(guard, &case_env, ctx) {
266
283
  Ok(t) => {
@@ -288,6 +305,7 @@ pub(crate) fn checkMatch(
288
305
  fn_pos,
289
306
  ctx,
290
307
  ));
308
+ crate::stmt::hoistBlockVars(&case_env, env);
291
309
  }
292
310
  errors
293
311
  }
compiler/checker/src/stmt.rs CHANGED
@@ -2,6 +2,17 @@
2
2
 
3
3
  use crate::*;
4
4
 
5
+ /// A block `if` / `match` used as a value stores its value in a `__blk` variable declared in
6
+ /// every branch (`plum_core::blocks`); that variable belongs to the code after the statement,
7
+ /// so it leaves the branch's scope. The first branch declares it, the others must agree.
8
+ pub(crate) fn hoistBlockVars(from: &TypeEnv, into: &mut TypeEnv) {
9
+ for (k, v) in from {
10
+ if k.starts_with(plum_core::blocks::BLOCK_VAR_PREFIX) && !into.contains_key(k) {
11
+ into.insert(k.clone(), v.clone());
12
+ }
13
+ }
14
+ }
15
+
5
16
  pub(crate) fn checkStmt(
6
17
  stmt: &ast::Stmt,
7
18
  env: &mut TypeEnv,
@@ -19,6 +30,21 @@ pub(crate) fn checkStmt(
19
30
  e.end_column = ec;
20
31
  }
21
32
  }
33
+ // A branch value of a block `if` / `match` used as a value (`plum_core::blocks`).
34
+ for e in errors.iter_mut() {
35
+ let marker = format!("assign '{}", plum_core::blocks::BLOCK_VAR_PREFIX);
36
+ if let Some(i) = e.message.find(&marker) {
37
+ let rest = e.message[i..].split_once("': ").map(|x| x.1.to_string()).unwrap_or_default();
38
+ let fnPart = e.message[..i].trim_end_matches(": ").to_string();
39
+ e.message = format!("{fnPart}: the branches of an 'if' or 'match' used as a value differ: {rest}");
40
+ if stmt.span.startLine > 0 {
41
+ e.line = stmt.span.startLine;
42
+ e.column = stmt.span.startColumn;
43
+ e.end_line = stmt.span.endLine;
44
+ e.end_column = stmt.span.endColumn;
45
+ }
46
+ }
47
+ }
22
48
  errors
23
49
  }
24
50
 
@@ -146,6 +172,13 @@ pub(crate) fn checkStmtInner(
146
172
  fn_pos.1,
147
173
  format!("fn '{}': assign '{}': {}", fn_name, name, msg),
148
174
  ));
175
+ } else if name.starts_with(plum_core::blocks::BLOCK_VAR_PREFIX) {
176
+ // Each branch pins what the other leaves open (`Ok(1)` /
177
+ // `Err(Bad)`); bind both ways so every branch builds the
178
+ // one joined instantiation (as an inline `if` does).
179
+ let mut binds = Binds::new();
180
+ bindMatch(&existing, &t, &mut binds);
181
+ bindMatch(&t, &existing, &mut binds);
149
182
  } else if matches!(existing, PlumType::TVar(_)) {
150
183
  // `unify` never narrows a `TVar` itself —
151
184
  // once a concrete type is available, record
@@ -330,6 +363,7 @@ pub(crate) fn checkStmtInner(
330
363
  fn_pos,
331
364
  ctx,
332
365
  ));
366
+ hoistBlockVars(&benv, env);
333
367
  for ei in &if_.else_ifs {
334
368
  match inferExpr(&ei.condition, env, ctx) {
335
369
  Ok(t) => {
@@ -360,6 +394,7 @@ pub(crate) fn checkStmtInner(
360
394
  fn_pos,
361
395
  ctx,
362
396
  ));
397
+ hoistBlockVars(&eenv, env);
363
398
  }
364
399
  if let Some(else_block) = &if_.else_ {
365
400
  set_tail(&tail);
compiler/checker/tests/checker/main.rs CHANGED
@@ -11,3 +11,4 @@ mod fip_test;
11
11
  mod fusion_pipeline_test;
12
12
  mod inline_variants_tests;
13
13
  mod question_tests;
14
+ mod syntax_tests;
compiler/checker/tests/checker/syntax_tests.rs ADDED
@@ -0,0 +1,119 @@
1
+ #![allow(non_snake_case)]
2
+ //! Block `if` / `match` as values, `.=`, and paths in spreads: what is accepted and what is rejected.
3
+ use plum_checker::checkSource;
4
+
5
+ const DEFS: &str = "\
6
+ enum Option[T] =
7
+ | None
8
+ | Some(value: T)
9
+
10
+ enum Result[T, E] =
11
+ | Ok(value: T)
12
+ | Err(error: E)
13
+
14
+ enum Oops =
15
+ | Bad
16
+
17
+ struct Ship(x: Int, y: Int)
18
+ struct Orb(ship: Ship, tag: Int)
19
+ struct State(orb: Orb, ship: Ship, t: Int)
20
+ struct Holder[T](item: T, n: Int)
21
+ struct Cnt(v: Int) =
22
+ fun bump(self, d: Int) -> Cnt = Cnt(v: self.v + d)
23
+ struct Bag(mut n: Cnt, k: Cnt)
24
+ enum Shape =
25
+ | Round(r: Int)
26
+ | Square(side: Int)
27
+ struct Frame(shape: Shape, n: Int)
28
+ fun half(n: Int) -> Result[Int, Oops] =
29
+ if n % 2 == 0 then Ok(n / 2) else Err(Bad)
30
+ ";
31
+
32
+ fn run(body: &str) -> Result<(), Vec<String>> {
33
+ let src = format!("{DEFS}\n{body}\n");
34
+ let mut source = plum_test_support::parse(&src);
35
+ plum_core::lower::frontEndDiag(&mut source).map_err(|e| e.into_iter().map(|x| x.message).collect::<Vec<_>>())?;
36
+ checkSource(&source).map_err(|e| e.into_iter().map(|x| x.message).collect())
37
+ }
38
+
39
+ fn ok(body: &str) {
40
+ run(body).unwrap_or_else(|e| panic!("{body}\n{e:?}"));
41
+ }
42
+
43
+ fn rejected(body: &str, needle: &str) {
44
+ let r = run(body);
45
+ let msg = r.expect_err(&format!("expected rejection:\n{body}")).join(" | ");
46
+ assert!(msg.contains(needle), "{body}\nexpected {needle:?} in: {msg}");
47
+ }
48
+
49
+ #[test]
50
+ fn block_if_and_match_values_check() {
51
+ ok("fun f(a: Bool) -> Int =\n v := if a\n 1\n else\n 2\n v");
52
+ ok("fun f(o: Option[Int]) -> Int =\n w := match o\n Some(x) => x\n None => 0\n w");
53
+ ok("fun id(n: Int) -> Int = n\nfun f(a: Bool) -> Int =\n id(if a\n 1\n else\n 2)");
54
+ }
55
+
56
+ #[test]
57
+ fn block_if_without_else_is_an_error() {
58
+ rejected("fun f(a: Bool) -> Int =\n v := if a\n 1\n v", "needs an 'else'");
59
+ }
60
+
61
+ #[test]
62
+ fn block_branches_must_agree() {
63
+ rejected(
64
+ "fun f(a: Bool) -> Int =\n v := if a\n 1\n else\n 2.5\n v",
65
+ "branches of an 'if' or 'match' used as a value differ",
66
+ );
67
+ }
68
+
69
+ #[test]
70
+ fn block_in_conditional_position_is_an_error() {
71
+ rejected(
72
+ "fun f(a: Bool, b: Bool) -> Bool =\n a && { if b\n true\n else\n false }",
73
+ "conditionally evaluated",
74
+ );
75
+ }
76
+
77
+ #[test]
78
+ fn question_in_a_value_branch_returns_from_the_fn() {
79
+ ok("fun f(a: Bool, n: Int) -> Result[Int, Oops] =\n v := if a\n h := half(n)?\n h + 1\n else\n 0\n Ok(v)");
80
+ }
81
+
82
+ #[test]
83
+ fn discarded_question_with_a_value_is_an_unused_result() {
84
+ rejected("fun f(n: Int) -> Result[Int, Oops] =\n half(n)?\n Ok(n)", "result of 'half' is unused");
85
+ ok("fun f(n: Int) -> Result[Int, Oops] =\n _ := half(n)?\n Ok(n)");
86
+ }
87
+
88
+ #[test]
89
+ fn update_operator_needs_a_method_call() {
90
+ ok("fun f(b: Bag) -> Int =\n b.n .= bump(3)\n b.n.v");
91
+ }
92
+
93
+ #[test]
94
+ fn update_operator_target_must_be_mut() {
95
+ rejected("fun f(b: Bag) -> Cnt =\n b.k .= bump(3)\n b.k", "immutable");
96
+ }
97
+
98
+ #[test]
99
+ fn spread_paths_check() {
100
+ ok("fun f(s: State) -> State =\n State(..s, ship.x: 1, orb.ship.y: 2, orb.tag: 3)");
101
+ ok("fun f(s: State) -> State =\n State(..s, ship.x: 1, ship.y: 2)");
102
+ }
103
+
104
+ #[test]
105
+ fn spread_path_through_an_enum_is_an_error() {
106
+ rejected("fun f(r: Frame) -> Frame =\n Frame(..r, shape.r: 1)", "an enum (Shape)");
107
+ }
108
+
109
+ #[test]
110
+ fn spread_path_through_a_generic_parameter_is_an_error() {
111
+ rejected("fun f(h: Holder[Ship]) -> Holder[Ship] =\n Holder(..h, item.x: 1)", "not a struct");
112
+ }
113
+
114
+ #[test]
115
+ fn spread_path_needs_a_spread_and_no_double_field() {
116
+ rejected("fun f() -> Ship =\n Ship(x.a: 1, y: 2)", "needs a spread");
117
+ rejected("fun f(s: State) -> State =\n State(..s, ship: s.ship, ship.x: 1)", "both whole and by path");
118
+ rejected("fun f(s: State) -> State =\n State(..s, nope.x: 1)", "has no field");
119
+ }
compiler/core/src/ast.rs CHANGED
@@ -65,6 +65,7 @@ impl Expr {
65
65
  pub fn Var(n: String) -> Expr { Expr::new(ExprKind::Var(n)) }
66
66
  pub fn TypeName(n: String) -> Expr { Expr::new(ExprKind::TypeName(n)) }
67
67
  pub fn Closure(c: Box<Closure>) -> Expr { Expr::new(ExprKind::Closure(c)) }
68
+ pub fn Block(b: Box<Block>) -> Expr { Expr::new(ExprKind::Block(b)) }
68
69
  }
69
70
 
70
71
  #[allow(non_snake_case, non_upper_case_globals)]
@@ -114,6 +115,7 @@ fn numberExpr(e: &mut Expr, all: bool) {
114
115
  }
115
116
  match &mut e.kind {
116
117
  ExprKind::Closure(c) => numberBlock(&mut c.body, all),
118
+ ExprKind::Block(b) => numberBlock(b, all),
117
119
  ExprKind::Bind(b) => {
118
120
  numberPatterns(&mut b.case.patterns, all);
119
121
  numberBlock(&mut b.case.body, all)
@@ -221,6 +223,7 @@ fn firstNode(src: &Source, bad: &mut dyn FnMut(NodeId) -> bool) -> Option<NodeId
221
223
  }
222
224
  match &e.kind {
223
225
  ExprKind::Closure(c) => block(&c.body, bad),
226
+ ExprKind::Block(b) => block(b, bad),
224
227
  ExprKind::Bind(b) => {
225
228
  patternIds(&b.case.patterns, bad).or_else(|| block(&b.case.body, bad))
226
229
  }
@@ -864,6 +867,10 @@ pub enum ExprKind {
864
867
  TypeName(String),
865
868
  /// `|params| body`
866
869
  Closure(Box<Closure>),
870
+ /// A block `if` / `match` used as a value (`v := if a` + indented branches): a block whose
871
+ /// only statement is that `if` / `match` (or, after a lowering, any statements); its last
872
+ /// statement gives the value. It runs inline, in the enclosing fn's scope.
873
+ Block(Box<Block>),
867
874
  }
868
875
 
869
876
  #[derive(Debug, Clone, PartialEq)]
compiler/core/src/blocks.rs ADDED
@@ -0,0 +1,317 @@
1
+ //! Lowers block `if` / `match` used as values (`ExprKind::Block`) before checking.
2
+ //!
3
+ //! `v := if a` + indented branches becomes the statement `if a` whose branches end in
4
+ //! `__blkN = <value>` (a synthetic first assignment: the checker declares `__blkN` for the code
5
+ //! after the `if`, see `hoistedVars` in the checker), followed by `v := __blkN`. So no
6
+ //! `ExprKind::Block` is left for the fusion passes, the closure specialiser, TRMC or codegen.
7
+ //!
8
+ //! * Several blocks in one statement are lifted in evaluation order; an earlier operand that is
9
+ //! not trivial is bound to a temporary first, so the order is kept (same rule as `question.rs`).
10
+ //! * A block in a conditionally evaluated position (the right side of `&&` / `||`, a branch of an
11
+ //! inline `if`, an `else if` condition, a `when` guard, a loop condition) is an error: bind it
12
+ //! to a local first.
13
+ //! * Every branch must end in a value; an `if` used as a value needs an `else`.
14
+ //! * A `?` in a branch follows `question.rs`: the lifted `if` is followed by the rest of the
15
+ //! block, so it is a non-tail branch and its failure arm returns from the fn.
16
+ use crate::ast::*;
17
+ use crate::diag::{DiagKind, Diagnostic};
18
+ use crate::visit::*;
19
+
20
+ /// Prefix of the variables that carry a block's value (the checker hoists them out of branches).
21
+ pub const BLOCK_VAR_PREFIX: &str = "__blk";
22
+
23
+ const MOVE: &str = "bind it to a local first";
24
+
25
+ struct Pass {
26
+ file: String,
27
+ fresh: usize,
28
+ errors: Vec<Diagnostic>,
29
+ }
30
+
31
+ fn hasBlock(e: &Expr) -> bool {
32
+ matches!(e.kind, ExprKind::Block(_)) || childRefs(e).into_iter().any(hasBlock)
33
+ }
34
+
35
+ fn firstBlock(e: &Expr) -> Option<Span> {
36
+ if matches!(e.kind, ExprKind::Block(_)) {
37
+ return Some(e.span);
38
+ }
39
+ childRefs(e).into_iter().find_map(firstBlock)
40
+ }
41
+
42
+ fn isTrivial(e: &Expr) -> bool {
43
+ match &e.kind {
44
+ ExprKind::Int(_)
45
+ | ExprKind::Float(_)
46
+ | ExprKind::BoolLit(_)
47
+ | ExprKind::Self_
48
+ | ExprKind::Var(_)
49
+ | ExprKind::TypeName(_)
50
+ | ExprKind::Closure(_) => true,
51
+ ExprKind::String(s) => s.parts.iter().all(|p| matches!(p, StringPart::Text(_))),
52
+ _ => false,
53
+ }
54
+ }
55
+
56
+ fn stmt(kind: StmtKind, span: Span) -> Stmt {
57
+ Stmt { id: NodeId(0), span, kind }
58
+ }
59
+
60
+ fn declare(name: String, value: Expr, span: Span) -> Stmt {
61
+ stmt(
62
+ StmtKind::Assign(Assign {
63
+ targets: vec![AssignTarget::Var(name)],
64
+ values: vec![value],
65
+ declare: true,
66
+ ty: None,
67
+ isSynthetic: false,
68
+ }),
69
+ span,
70
+ )
71
+ }
72
+
73
+ impl Pass {
74
+ fn error(&mut self, span: Span, msg: String) {
75
+ self.errors.push(Diagnostic::new(DiagKind::Type, self.file.clone(), span.startLine, span.startColumn, msg));
76
+ }
77
+
78
+ fn freshName(&mut self, base: &str) -> String {
79
+ self.fresh += 1;
80
+ format!("__{}{}", base, self.fresh)
81
+ }
82
+
83
+ /// Lowers the closure bodies under `e` (not into blocks: those are lowered when lifted).
84
+ fn closures(&mut self, e: &mut Expr) {
85
+ if let ExprKind::Closure(c) = &mut e.kind {
86
+ let body = std::mem::replace(&mut c.body, Block { stmts: vec![] });
87
+ c.body = self.lowerBlock(body);
88
+ }
89
+ for c in childExprs(e) {
90
+ self.closures(c);
91
+ }
92
+ }
93
+
94
+ fn extract(&mut self, e: &mut Expr, pre: &mut Vec<Stmt>) {
95
+ if !hasBlock(e) {
96
+ self.closures(e);
97
+ return;
98
+ }
99
+ if let ExprKind::Block(_) = &e.kind {
100
+ let span = e.span;
101
+ let ExprKind::Block(blk) = std::mem::replace(&mut e.kind, ExprKind::Self_) else { unreachable!() };
102
+ let inner = self.lowerBlock(*blk);
103
+ let name = self.freshName(&BLOCK_VAR_PREFIX[2..]);
104
+ pre.extend(self.leaves(inner.stmts, &name, span));
105
+ e.kind = ExprKind::Var(name);
106
+ return;
107
+ }
108
+ let condFrom = match &e.kind {
109
+ ExprKind::Bool(_) | ExprKind::InlineIf(_) | ExprKind::Bind(_) => 1,
110
+ _ => usize::MAX,
111
+ };
112
+ self.extractSeq(childExprs(e), condFrom, pre);
113
+ }
114
+
115
+ /// `items` are evaluated in order; those from `condFrom` on only conditionally.
116
+ fn extractSeq(&mut self, items: Vec<&mut Expr>, condFrom: usize, pre: &mut Vec<Stmt>) {
117
+ let mut last = None;
118
+ for (j, it) in items.iter().enumerate() {
119
+ if hasBlock(it) {
120
+ if j >= condFrom {
121
+ let span = firstBlock(it).unwrap_or(it.span);
122
+ self.error(span, format!("a block 'if' or 'match' in a conditionally evaluated expression is not allowed: {MOVE}"));
123
+ } else {
124
+ last = Some(j);
125
+ }
126
+ }
127
+ }
128
+ let Some(last) = last else {
129
+ for it in items {
130
+ self.closures(it);
131
+ }
132
+ return;
133
+ };
134
+ for (j, it) in items.into_iter().enumerate() {
135
+ if j > last {
136
+ self.closures(it);
137
+ continue;
138
+ }
139
+ if j >= condFrom {
140
+ self.closures(it);
141
+ continue;
142
+ }
143
+ self.extract(it, pre);
144
+ if j < last && !isTrivial(it) {
145
+ let tmp = self.freshName("t");
146
+ let span = it.span;
147
+ let taken = std::mem::replace(it, Expr::Var(tmp.clone()));
148
+ it.span = span;
149
+ pre.push(declare(tmp, taken, span));
150
+ }
151
+ }
152
+ }
153
+
154
+ fn lowerBlock(&mut self, b: Block) -> Block {
155
+ let mut out = Vec::new();
156
+ for mut s in b.stmts {
157
+ for blk in stmtBlocks(&mut s) {
158
+ let body = std::mem::replace(blk, Block { stmts: vec![] });
159
+ *blk = self.lowerBlock(body);
160
+ }
161
+ let condFrom = match &s.kind {
162
+ StmtKind::While(_) => 0,
163
+ StmtKind::If(_) => 1,
164
+ StmtKind::Match(m) => m.subjects.len(),
165
+ _ => usize::MAX,
166
+ };
167
+ let mut pre = Vec::new();
168
+ self.extractSeq(stmtExprs(&mut s), condFrom, &mut pre);
169
+ out.extend(pre);
170
+ out.push(s);
171
+ }
172
+ Block { stmts: out }
173
+ }
174
+
175
+ /// `stmts` with the value of the last statement stored in `name`.
176
+ fn leaves(&mut self, mut stmts: Vec<Stmt>, name: &str, at: Span) -> Vec<Stmt> {
177
+ let Some(last) = stmts.pop() else {
178
+ self.error(at, "a block used as a value needs a value on its last line".to_string());
179
+ return stmts;
180
+ };
181
+ let Stmt { id, span, kind } = last;
182
+ let kind = match kind {
183
+ StmtKind::Expr(e, ..) => StmtKind::Assign(Assign {
184
+ targets: vec![AssignTarget::Var(name.to_string())],
185
+ values: vec![e],
186
+ declare: false,
187
+ ty: None,
188
+ isSynthetic: true,
189
+ }),
190
+ StmtKind::If(mut i) => {
191
+ if i.else_.is_none() {
192
+ self.error(span, "an 'if' used as a value needs an 'else'".to_string());
193
+ }
194
+ for blk in std::iter::once(&mut i.body)
195
+ .chain(i.else_ifs.iter_mut().map(|e| &mut e.body))
196
+ .chain(i.else_.iter_mut())
197
+ {
198
+ let body = std::mem::take(&mut blk.stmts);
199
+ blk.stmts = self.leaves(body, name, span);
200
+ }
201
+ StmtKind::If(i)
202
+ }
203
+ StmtKind::Match(mut m) => {
204
+ for c in &mut m.cases {
205
+ let body = std::mem::take(&mut c.body.stmts);
206
+ c.body.stmts = self.leaves(body, name, span);
207
+ }
208
+ StmtKind::Match(m)
209
+ }
210
+ k @ (StmtKind::Return(_) | StmtKind::Crash(_) | StmtKind::Todo | StmtKind::Break | StmtKind::Continue) => k,
211
+ other => {
212
+ self.error(span, "the last line of a block used as a value must be a value, an 'if' or a 'match'".to_string());
213
+ other
214
+ }
215
+ };
216
+ stmts.push(Stmt { id, span, kind });
217
+ stmts
218
+ }
219
+ }
220
+
221
+ fn blockHasBlock(b: &Block) -> bool {
222
+ b.stmts.iter().any(stmtHasBlock)
223
+ }
224
+
225
+ fn stmtHasBlock(s: &Stmt) -> bool {
226
+ stmtExprRefs(s).into_iter().any(hasBlock) || stmtBlockRefs(s).into_iter().any(blockHasBlock)
227
+ }
228
+
229
+ /// Does some closure body under `e` hold a block value?
230
+ fn closureHasBlock(e: &Expr) -> bool {
231
+ let mut any = false;
232
+ walkRef(e, &mut |x| {
233
+ if let ExprKind::Closure(c) = &x.kind {
234
+ any |= blockHasBlock(&c.body);
235
+ }
236
+ });
237
+ any
238
+ }
239
+
240
+ fn blockClosureHasBlock(b: &Block) -> bool {
241
+ let mut any = false;
242
+ walkBlockRef(b, &mut |x| {
243
+ if let ExprKind::Closure(c) = &x.kind {
244
+ any |= blockHasBlock(&c.body);
245
+ }
246
+ });
247
+ any
248
+ }
249
+
250
+ /// Lowers every block `if` / `match` value of the program. Returns the errors.
251
+ pub fn lowerBlockValues(source: &mut Source) -> Vec<Diagnostic> {
252
+ let mut errors = Vec::new();
253
+ let mut fresh = 0;
254
+ let file = source.file.clone();
255
+ for item in source.items.iter_mut() {
256
+ match item {
257
+ Item::Fn(f) => {
258
+ let probe = match &f.body {
259
+ FnBody::Block(b) => blockHasBlock(b) || blockClosureHasBlock(b),
260
+ FnBody::Expr(e) => hasBlock(e) || closureHasBlock(e),
261
+ FnBody::Extern => false,
262
+ };
263
+ if !probe {
264
+ continue;
265
+ }
266
+ let mut pass = Pass { file: f.file.clone(), fresh, errors: vec![] };
267
+ let block = match &mut f.body {
268
+ FnBody::Block(b) => std::mem::replace(b, Block { stmts: vec![] }),
269
+ FnBody::Expr(e) => {
270
+ let span = e.span;
271
+ let (line, column) = (span.startLine, span.startColumn);
272
+ let e = std::mem::replace(e, Expr::Self_);
273
+ Block { stmts: vec![stmt(StmtKind::Expr(e, line, column), span)] }
274
+ }
275
+ FnBody::Extern => continue,
276
+ };
277
+ let saved = block.clone();
278
+ let out = pass.lowerBlock(block);
279
+ fresh = pass.fresh;
280
+ if pass.errors.is_empty() {
281
+ f.body = FnBody::Block(out);
282
+ } else {
283
+ errors.append(&mut pass.errors);
284
+ f.body = FnBody::Block(saved);
285
+ }
286
+ }
287
+ Item::Test(t) => {
288
+ if blockHasBlock(&t.body) || blockClosureHasBlock(&t.body) {
289
+ let mut pass = Pass { file: t.file.clone(), fresh, errors: vec![] };
290
+ let body = std::mem::replace(&mut t.body, Block { stmts: vec![] });
291
+ let saved = body.clone();
292
+ let out = pass.lowerBlock(body);
293
+ fresh = pass.fresh;
294
+ if pass.errors.is_empty() {
295
+ t.body = out;
296
+ } else {
297
+ errors.append(&mut pass.errors);
298
+ t.body = saved;
299
+ }
300
+ }
301
+ }
302
+ Item::Const(c) => {
303
+ if let Some(span) = firstBlock(&c.value) {
304
+ errors.push(Diagnostic::new(
305
+ DiagKind::Type,
306
+ file.clone(),
307
+ span.startLine,
308
+ span.startColumn,
309
+ "a block 'if' or 'match' is not allowed in a constant: use an inline 'if a then b else c'",
310
+ ));
311
+ }
312
+ }
313
+ Item::Enum(_) => {}
314
+ }
315
+ }
316
+ errors
317
+ }
compiler/core/src/builtin_usage.rs CHANGED
@@ -279,6 +279,7 @@ fn walkExpr(expr: &Expr, names: &mut Acc) {
279
279
  }
280
280
  }
281
281
  ExprKind::Closure(c) => walkStmts(&c.body.stmts, names),
282
+ ExprKind::Block(b) => walkStmts(&b.stmts, names),
282
283
  }
283
284
  }
284
285
 
compiler/core/src/closure_escape.rs CHANGED
@@ -230,6 +230,8 @@ impl<'a> Cx<'a> {
230
230
  StringPart::Text(_) => false,
231
231
  }),
232
232
  ExprKind::Closure(c) => self.block(&c.body, true),
233
+ // Runs inline: whatever it does with the parameter happens in the fn itself.
234
+ ExprKind::Block(b) => self.block(b, cl),
233
235
  ExprKind::Int(_)
234
236
  | ExprKind::Float(_)
235
237
  | ExprKind::BoolLit(_)
compiler/core/src/enum_checks.rs CHANGED
@@ -341,6 +341,7 @@ impl TypeWalk<'_> {
341
341
  }
342
342
  }
343
343
  ExprKind::Closure(c) => self.stmts(&c.body.stmts),
344
+ ExprKind::Block(b) => self.stmts(&b.stmts),
344
345
  ExprKind::Int(_)
345
346
  | ExprKind::Float(_)
346
347
  | ExprKind::Self_
compiler/core/src/formatter.rs CHANGED
@@ -124,7 +124,11 @@ pub fn inlineSingleStatementCaseBodies(source: &str) -> String {
124
124
  if let Some(body) = node.child_by_field_name("body") {
125
125
  if body.kind() == "body" && body.named_child_count() == 1 {
126
126
  if let Some(inner) = body.named_child(0) {
127
+ // A block `if` / `match` is an `expression` too, but stays on its own lines.
128
+ let blockForm = inner
129
+ .named_child(0)
130
+ .is_some_and(|c| c.kind() == "if" || c.kind() == "match");
127
- if inner.kind() == "expression" {
131
+ if inner.kind() == "expression" && !blockForm {
128
132
  gaps.push((body.start_byte(), inner.start_byte()));
129
133
  }
130
134
  }
compiler/core/src/lib.rs CHANGED
@@ -3,6 +3,7 @@
3
3
  #![allow(non_snake_case)]
4
4
 
5
5
  pub mod ast;
6
+ pub mod blocks;
6
7
  pub mod builtin_usage;
7
8
  pub mod closure_escape;
8
9
  pub mod closure_spec;
@@ -27,6 +28,7 @@ pub mod rename;
27
28
  pub mod reuse;
28
29
  pub mod session;
29
30
  pub mod simplify;
31
+ pub mod spread_paths;
30
32
  pub mod tail;
31
33
  pub mod tests_lower;
32
34
  pub mod trmc;
compiler/core/src/lower.rs CHANGED
@@ -25,6 +25,14 @@ pub fn perFileDiag(source: &mut Source) -> Result<(), Vec<Diagnostic>> {
25
25
  /// errors.
26
26
  pub fn frontEndDiag(source: &mut Source) -> Result<(), Vec<Diagnostic>> {
27
27
  crate::session::begin();
28
+ let pathErrors = crate::spread_paths::lowerSpreadPaths(source);
29
+ if !pathErrors.is_empty() {
30
+ return Err(pathErrors);
31
+ }
32
+ let blockErrors = crate::blocks::lowerBlockValues(source);
33
+ if !blockErrors.is_empty() {
34
+ return Err(blockErrors);
35
+ }
28
36
  let questionErrors = crate::question::lowerQuestions(source);
29
37
  if !questionErrors.is_empty() {
30
38
  return Err(questionErrors);
compiler/core/src/parser.rs CHANGED
@@ -453,12 +453,14 @@ impl<'a> AstParser<'a> {
453
453
  "body" => Some(FnBody::Block(self.parseBlock(*last))),
454
454
  // `fun f(..) = match x` + indented arms: same AST as the
455
455
  // indented `=\n match x` form.
456
- "match" => Some(FnBody::Block(Block {
457
- stmts: vec![Stmt::Match(self.parseMatch(*last))],
458
- })),
459
456
  _ => {
460
457
  let unwrapped = self.unwrapExprNode(*last);
458
+ match unwrapped.kind() {
459
+ // `fun f(..) = match x` + indented arms (or a block `if`): same AST
460
+ // as the indented `=\n match x` form.
461
+ "match" | "if" => Some(FnBody::Block(self.inlineBody(unwrapped))),
461
- Some(FnBody::Expr(self.parseExpression(unwrapped)))
462
+ _ => Some(FnBody::Expr(self.parseExpression(unwrapped))),
463
+ }
462
464
  }
463
465
  }
464
466
  })
@@ -651,6 +653,8 @@ impl<'a> AstParser<'a> {
651
653
  let mut s = Stmt::ForLoop(self.parseForLoop(u));
652
654
  s.span = self.spanOf(u);
653
655
  stmts.push(s);
656
+ } else if u.kind() == "assign" && self.isUpdate(u) {
657
+ stmts.extend(self.parseUpdate(u));
654
658
  } else if let Some(s) = self.parseStmt(n) {
655
659
  stmts.push(s);
656
660
  }
@@ -658,6 +662,81 @@ impl<'a> AstParser<'a> {
658
662
  Block { stmts }
659
663
  }
660
664
 
665
+ fn isUpdate(&self, assign: Node) -> bool {
666
+ assign.child_by_field_name("op").is_some_and(|n| self.text(n) == ".=")
667
+ }
668
+
669
+ /// `obj.f .= m(args)` is `obj.f = obj.f.m(args)`. A receiver that is more than a name or a
670
+ /// field path is bound to a temporary first, so it is evaluated once.
671
+ fn parseUpdate(&self, node: Node) -> Vec<Stmt> {
672
+ fn plain(e: &Expr) -> bool {
673
+ match &e.kind {
674
+ ExprKind::Var(_) | ExprKind::Self_ => true,
675
+ ExprKind::Attribute(a) => matches!(a.attr, AttrKind::Field(_)) && plain(&a.object),
676
+ _ => false,
677
+ }
678
+ }
679
+ fn graft(rhs: Expr, recv: Expr) -> Option<Expr> {
680
+ let Expr { id, span, kind } = rhs;
681
+ match kind {
682
+ ExprKind::FnCall(call) => Some(Expr {
683
+ id,
684
+ span,
685
+ kind: ExprKind::Attribute(Box::new(AttributeExpr { object: recv, attr: AttrKind::Method(call) })),
686
+ }),
687
+ ExprKind::Attribute(a) => {
688
+ let AttributeExpr { object, attr } = *a;
689
+ let object = graft(object, recv)?;
690
+ Some(Expr { id, span, kind: ExprKind::Attribute(Box::new(AttributeExpr { object, attr })) })
691
+ }
692
+ _ => None,
693
+ }
694
+ }
695
+ let span = self.spanOf(node);
696
+ let named = self.namedChildren(node);
697
+ let (Some(target), Some(value)) = (named.first(), named.last()) else { return vec![] };
698
+ let AssignTarget::Field(obj, member) = self.parseAssignTarget(*target) else { return vec![] };
699
+ let rhs = self.parseExpression(self.unwrapExprNode(*value));
700
+ let mut out = Vec::new();
701
+ let mut obj = *obj;
702
+ if !plain(&obj) {
703
+ let tmp = format!("__up{}_{}", span.startLine, span.startColumn);
704
+ let mut s = Stmt::Assign(Assign {
705
+ targets: vec![AssignTarget::Var(tmp.clone())],
706
+ values: vec![obj.clone()],
707
+ declare: true,
708
+ ty: None,
709
+ isSynthetic: false,
710
+ });
711
+ s.span = span;
712
+ out.push(s);
713
+ obj = Expr::Var(tmp);
714
+ obj.span = span;
715
+ }
716
+ let mut read = Expr::Attribute(Box::new(AttributeExpr { object: obj.clone(), attr: AttrKind::Field(member.clone()) }));
717
+ read.span = self.spanOf(*target);
718
+ let Some(updated) = graft(rhs, read) else {
719
+ self.malformed.borrow_mut().push(crate::diag::Diagnostic::new(
720
+ crate::diag::DiagKind::Parse,
721
+ "",
722
+ span.startLine,
723
+ span.startColumn,
724
+ format!("'.=' needs a method call on the right, like `{member} .= push(x)`"),
725
+ ));
726
+ return out;
727
+ };
728
+ let mut s = Stmt::Assign(Assign {
729
+ targets: vec![AssignTarget::Field(Box::new(obj), member)],
730
+ values: vec![updated],
731
+ declare: false,
732
+ ty: None,
733
+ isSynthetic: false,
734
+ });
735
+ s.span = span;
736
+ out.push(s);
737
+ out
738
+ }
739
+
661
740
  fn parseStmt(&self, node: Node) -> Option<Stmt> {
662
741
  let node = self.unwrapExprNode(node);
663
742
  let mut stmt = self.parseStmtKind(node)?;
@@ -904,14 +983,7 @@ impl<'a> AstParser<'a> {
904
983
  self.parseBlock(n)
905
984
  } else {
906
985
  let unwrapped = self.unwrapExprNode(n);
907
- let pos = unwrapped.start_position();
908
- Block {
909
- stmts: vec![Stmt::Expr(
910
- self.parseExpression(unwrapped),
986
+ self.inlineBody(unwrapped)
911
- pos.row + 1,
912
- pos.column + 1,
913
- )],
914
- }
915
987
  }
916
988
  })
917
989
  .unwrap_or(Block { stmts: vec![] });
@@ -967,8 +1039,29 @@ impl<'a> AstParser<'a> {
967
1039
  e
968
1040
  }
969
1041
 
1042
+ /// A block `if` / `match` in expression position: a block holding just that statement.
1043
+ fn parseBlockValue(&self, node: Node) -> Expr {
1044
+ let mut stmt = match node.kind() {
1045
+ "if" => Stmt::If(self.parseIf(node)),
1046
+ _ => Stmt::Match(self.parseMatch(node)),
1047
+ };
1048
+ stmt.span = self.spanOf(node);
1049
+ Expr::Block(Box::new(Block { stmts: vec![stmt] }))
1050
+ }
1051
+
1052
+ /// The one-statement block of an inline body (`=> e`, `|x| e`): a block `if` / `match`
1053
+ /// there is the statement itself.
1054
+ fn inlineBody(&self, unwrapped: Node) -> Block {
1055
+ let pos = unwrapped.start_position();
1056
+ match self.parseExpression(unwrapped) {
1057
+ Expr { kind: ExprKind::Block(b), .. } => *b,
1058
+ e => Block { stmts: vec![Stmt::Expr(e, pos.row + 1, pos.column + 1)] },
1059
+ }
1060
+ }
1061
+
970
1062
  fn parseExpressionKind(&self, node: Node) -> Expr {
971
1063
  match node.kind() {
1064
+ "if" | "match" => self.parseBlockValue(node),
972
1065
  "comparison_operator" => self.parseCompare(node),
973
1066
  "not_operator" => {
974
1067
  let arg = node
@@ -1056,15 +1149,12 @@ impl<'a> AstParser<'a> {
1056
1149
  Some(block_node) => self.parseBlock(block_node),
1057
1150
  None => match node.child_by_field_name("body") {
1058
1151
  Some(expr_node) => {
1152
+ // A block `if` / `match` here is the closure's value, so it stays an
1153
+ // expression (`blocks.rs` lifts it); as a bare statement the checker
1154
+ // would type the closure `Unit`.
1059
1155
  let unwrapped = self.unwrapExprNode(expr_node);
1060
1156
  let pos = unwrapped.start_position();
1061
- Block {
1062
- stmts: vec![Stmt::Expr(
1063
- self.parseExpression(unwrapped),
1157
+ Block { stmts: vec![Stmt::Expr(self.parseExpression(unwrapped), pos.row + 1, pos.column + 1)] }
1064
- pos.row + 1,
1065
- pos.column + 1,
1066
- )],
1067
- }
1068
1158
  }
1069
1159
  None => Block { stmts: vec![] },
1070
1160
  },
@@ -1488,9 +1578,11 @@ impl<'a> AstParser<'a> {
1488
1578
  None
1489
1579
  }
1490
1580
  _ => {
1581
+ // `ship.x: v` (a path, only with a spread): the dots stay in the name
1582
+ // until `spread_paths` lowers it.
1491
1583
  let name = n
1492
1584
  .child_by_field_name("name")
1493
- .map(|nn| self.text(nn))
1585
+ .map(|nn| self.text(nn).split_whitespace().collect::<String>())
1494
1586
  .unwrap_or_default();
1495
1587
  let vn = n
1496
1588
  .child_by_field_name("value")
compiler/core/src/purity.rs CHANGED
@@ -536,6 +536,7 @@ impl<'a> Walker<'a> {
536
536
  }
537
537
  }
538
538
  ExprKind::Closure(c) => self.block(&c.body),
539
+ ExprKind::Block(b) => self.block(b),
539
540
  ExprKind::Int(_)
540
541
  | ExprKind::Float(_)
541
542
  | ExprKind::BoolLit(_)
compiler/core/src/question.rs CHANGED
@@ -48,6 +48,10 @@ struct Pass {
48
48
  errors: Vec<Diagnostic>,
49
49
  }
50
50
 
51
+ /// Binder of a discarded `f()?` statement: `__unused_<callee>_<n>`. The checker reports it when
52
+ /// the unwrapped value is not Unit.
53
+ pub const UNUSED_PREFIX: &str = "__unused_";
54
+
51
55
  const MOVE: &str = "move it into a function";
52
56
 
53
57
  fn hasQ(e: &Expr) -> bool {
@@ -208,7 +212,18 @@ impl Pass {
208
212
  let span = e.span;
209
213
  let ExprKind::Question(mut inner) = std::mem::replace(&mut e.kind, ExprKind::Self_) else { unreachable!() };
210
214
  self.extract(&mut inner, &mut pre);
215
+ // The unwrapped value is dropped. The binder name tells the checker to
216
+ // report a non-Unit value as an unused result (`UNUSED_PREFIX`).
217
+ let callee = match &inner.kind {
218
+ ExprKind::FnCall(c) => c.name.clone(),
219
+ ExprKind::Attribute(a) => match &a.attr {
220
+ AttrKind::Method(c) => c.name.clone(),
221
+ AttrKind::Field(f) => f.clone(),
222
+ },
223
+ _ => "value".to_string(),
224
+ };
225
+ let binder = self.freshName(&format!("{}{}_", &UNUSED_PREFIX[2..], callee));
211
- pre.push(Pre::Unwrap { pat: CasePattern::Wildcard, operand: *inner, span });
226
+ pre.push(Pre::Unwrap { pat: CasePattern::Name(binder), operand: *inner, span });
212
227
  return (pre, None);
213
228
  }
214
229
  _ => {}
compiler/core/src/spread_paths.rs ADDED
@@ -0,0 +1,207 @@
1
+ //! Lowers paths in spreads before checking: `State(..s, ship.x: 1.0)` becomes
2
+ //! `State(..s, ship: Ship(..__pa1, x: 1.0))` with `__pa1 := s.ship` bound first (a spread source
3
+ //! has to be a plain variable), as a block value that `blocks.rs` lifts into statements.
4
+ //!
5
+ //! * Paths go through struct fields only: the field's declared type must be a struct of the
6
+ //! program. An enum, a generic parameter or a primitive on the path is an error.
7
+ //! * Paths sharing a prefix build one value: `S(..s, a.x: 1, a.y: 2)` updates `a` once.
8
+ //! * A path needs a spread (`ship.x: 1.0` alone has no value to take the other fields from), and
9
+ //! a field can't be given both whole and by path.
10
+ use crate::ast::*;
11
+ use crate::diag::{DiagKind, Diagnostic};
12
+ use crate::visit::*;
13
+ use std::collections::{HashMap, HashSet};
14
+
15
+ struct Structs {
16
+ /// struct name -> (field name, declared type name)
17
+ fields: HashMap<String, Vec<(String, String)>>,
18
+ enums: HashSet<String>,
19
+ }
20
+
21
+ struct Pass<'a> {
22
+ structs: &'a Structs,
23
+ fresh: usize,
24
+ }
25
+
26
+ fn bare(e: &Expr) -> bool {
27
+ matches!(e.kind, ExprKind::Var(_) | ExprKind::Self_)
28
+ }
29
+
30
+ fn field(object: Expr, name: &str) -> Expr {
31
+ Expr::Attribute(Box::new(AttributeExpr { object, attr: AttrKind::Field(name.to_string()) }))
32
+ }
33
+
34
+ fn declare(name: &str, value: Expr, span: Span) -> Stmt {
35
+ Stmt {
36
+ id: NodeId(0),
37
+ span,
38
+ kind: StmtKind::Assign(Assign {
39
+ targets: vec![AssignTarget::Var(name.to_string())],
40
+ values: vec![value],
41
+ declare: true,
42
+ ty: None,
43
+ isSynthetic: false,
44
+ }),
45
+ }
46
+ }
47
+
48
+ impl Pass<'_> {
49
+ fn fresh(&mut self, base: &str) -> String {
50
+ self.fresh += 1;
51
+ format!("__{}{}", base, self.fresh)
52
+ }
53
+
54
+ /// `ty(..base, fields)` where some field names are paths.
55
+ fn update(
56
+ &mut self,
57
+ ty: &str,
58
+ base: Expr,
59
+ fields: Vec<FieldArg>,
60
+ generics: Vec<Type>,
61
+ temps: &mut Vec<Stmt>,
62
+ span: Span,
63
+ ) -> Result<ClassCall, String> {
64
+ let Some(declared) = self.structs.fields.get(ty) else {
65
+ return Err(if self.structs.enums.contains(ty) {
66
+ format!("'{ty}' is an enum: a path in a spread goes through struct fields only")
67
+ } else {
68
+ format!("'{ty}' is not a struct: a path in a spread goes through struct fields only")
69
+ });
70
+ };
71
+ let declared = declared.clone();
72
+ let wholes: HashSet<String> = fields.iter().filter(|f| !f.name.contains('.')).map(|f| f.name.clone()).collect();
73
+ let mut groups: HashMap<String, Vec<FieldArg>> = HashMap::new();
74
+ for f in &fields {
75
+ if let Some((head, rest)) = f.name.split_once('.') {
76
+ if wholes.contains(head) {
77
+ return Err(format!("'{head}' is given both whole and by path ('{}')", f.name));
78
+ }
79
+ groups.entry(head.to_string()).or_default().push(FieldArg { name: rest.to_string(), value: f.value.clone() });
80
+ }
81
+ }
82
+ let mut out = Vec::new();
83
+ let mut done: HashSet<String> = HashSet::new();
84
+ for f in fields {
85
+ let Some((head, _)) = f.name.split_once('.') else {
86
+ out.push(f);
87
+ continue;
88
+ };
89
+ if !done.insert(head.to_string()) {
90
+ continue;
91
+ }
92
+ let subs = groups.remove(head).unwrap_or_default();
93
+ let Some((_, fty)) = declared.iter().find(|(n, _)| n == head) else {
94
+ return Err(format!("'{ty}' has no field '{head}'"));
95
+ };
96
+ if !self.structs.fields.contains_key(fty) {
97
+ let what = if self.structs.enums.contains(fty) {
98
+ format!("an enum ({fty})")
99
+ } else {
100
+ format!("{fty}, not a struct")
101
+ };
102
+ return Err(format!("field '{head}' of '{ty}' is {what}: a path in a spread goes through struct fields only"));
103
+ }
104
+ let tmp = self.fresh("pa");
105
+ temps.push(declare(&tmp, field(copyExpr(&base), head), span));
106
+ let mut tmpVar = Expr::Var(tmp);
107
+ tmpVar.span = span;
108
+ let inner = self.update(fty, tmpVar, subs, vec![], temps, span)?;
109
+ let mut value = Expr::ClassCall(inner);
110
+ value.span = f.value.span;
111
+ out.push(FieldArg { name: head.to_string(), value });
112
+ }
113
+ Ok(ClassCall { type_name: ty.to_string(), fields: out, generics, spread: Some(Box::new(base)), unique: false, reuse: None })
114
+ }
115
+
116
+ fn rewrite(&mut self, e: &mut Expr, errors: &mut Vec<(Span, String)>) {
117
+ let ExprKind::ClassCall(c) = &mut e.kind else { return };
118
+ if !c.fields.iter().any(|f| f.name.contains('.')) {
119
+ return;
120
+ }
121
+ let span = e.span;
122
+ let saved = c.clone();
123
+ let Some(spread) = c.spread.take() else {
124
+ let path = c.fields.iter().find(|f| f.name.contains('.')).map(|f| f.name.clone()).unwrap_or_default();
125
+ errors.push((span, format!("the path '{path}' needs a spread: {}(..value, {path}: ..)", c.type_name)));
126
+ return;
127
+ };
128
+ let mut temps = Vec::new();
129
+ let mut base = *spread;
130
+ if !bare(&base) {
131
+ let tmp = self.fresh("sp");
132
+ let taken = std::mem::replace(&mut base, Expr::Var(tmp.clone()));
133
+ base.span = taken.span;
134
+ temps.push(declare(&tmp, taken, span));
135
+ }
136
+ let fields = std::mem::take(&mut c.fields);
137
+ let generics = std::mem::take(&mut c.generics);
138
+ let ty = c.type_name.clone();
139
+ match self.update(&ty, base, fields, generics, &mut temps, span) {
140
+ Ok(call) => {
141
+ let mut value = Expr::ClassCall(call);
142
+ value.span = span;
143
+ if temps.is_empty() {
144
+ value.id = e.id;
145
+ *e = value;
146
+ } else {
147
+ temps.push(Stmt { id: NodeId(0), span, kind: StmtKind::Expr(value, span.startLine, span.startColumn) });
148
+ let id = e.id;
149
+ *e = Expr::Block(Box::new(Block { stmts: temps }));
150
+ e.id = id;
151
+ e.span = span;
152
+ }
153
+ }
154
+ Err(msg) => {
155
+ // Leave the call as written: the errors are all the caller reads.
156
+ e.kind = ExprKind::ClassCall(saved);
157
+ errors.push((span, msg));
158
+ }
159
+ }
160
+ }
161
+ }
162
+
163
+ /// Lowers every path in a spread of the program. Returns the errors.
164
+ pub fn lowerSpreadPaths(source: &mut Source) -> Vec<Diagnostic> {
165
+ let mut structs = Structs { fields: HashMap::new(), enums: HashSet::new() };
166
+ for item in &source.items {
167
+ if let Item::Enum(e) = item {
168
+ match (&e.kind, e.variants.as_slice()) {
169
+ (TypeKind::Struct(_), [v]) => {
170
+ let fields = v.field_names.iter().cloned().zip(v.fields.iter().map(|t| t.name.clone())).collect();
171
+ structs.fields.insert(e.name.clone(), fields);
172
+ }
173
+ _ => {
174
+ structs.enums.insert(e.name.clone());
175
+ }
176
+ }
177
+ }
178
+ }
179
+ let mut pass = Pass { structs: &structs, fresh: 0 };
180
+ let mut raw: Vec<(String, Span, String)> = Vec::new();
181
+ let file = source.file.clone();
182
+ for item in source.items.iter_mut() {
183
+ let (name, mut errs) = (
184
+ match item {
185
+ Item::Fn(f) => f.file.clone(),
186
+ Item::Test(t) => t.file.clone(),
187
+ _ => file.clone(),
188
+ },
189
+ Vec::new(),
190
+ );
191
+ let mut visit = |e: &mut Expr| {
192
+ pass.rewrite(e, &mut errs);
193
+ };
194
+ match item {
195
+ Item::Fn(f) => match &mut f.body {
196
+ FnBody::Block(b) => visitBlock(b, &mut visit),
197
+ FnBody::Expr(e) => visitExpr(e, &mut visit),
198
+ FnBody::Extern => {}
199
+ },
200
+ Item::Test(t) => visitBlock(&mut t.body, &mut visit),
201
+ Item::Const(c) => visitExpr(&mut c.value, &mut visit),
202
+ Item::Enum(_) => {}
203
+ }
204
+ raw.extend(errs.into_iter().map(|(s, m)| (name.clone(), s, m)));
205
+ }
206
+ raw.into_iter().map(|(f, s, m)| Diagnostic::new(DiagKind::Type, f, s.startLine, s.startColumn, m)).collect()
207
+ }
compiler/core/src/uniqueness.rs CHANGED
@@ -201,6 +201,7 @@ pub(crate) fn walkExpr<'a>(e: &'a Expr, f: Visit<'a, '_>) {
201
201
  }
202
202
  }
203
203
  ExprKind::Closure(c) => walkBlock(&c.body, f),
204
+ ExprKind::Block(b) => walkBlock(b, f),
204
205
  ExprKind::Int(_)
205
206
  | ExprKind::Float(_)
206
207
  | ExprKind::BoolLit(_)
@@ -329,6 +330,7 @@ pub(crate) fn mutExpr(e: &mut Expr, f: &mut dyn FnMut(&mut Expr)) {
329
330
  }
330
331
  }
331
332
  ExprKind::Closure(c) => mutBlock(&mut c.body, f),
333
+ ExprKind::Block(b) => mutBlock(b, f),
332
334
  ExprKind::Int(_)
333
335
  | ExprKind::Float(_)
334
336
  | ExprKind::BoolLit(_)
compiler/core/src/visit.rs CHANGED
@@ -21,6 +21,7 @@ pub fn visitExpr(e: &mut Expr, f: &mut dyn FnMut(&mut Expr)) {
21
21
  }
22
22
  match &mut e.kind {
23
23
  ExprKind::Closure(c) => visitBlock(&mut c.body, f),
24
+ ExprKind::Block(b) => visitBlock(b, f),
24
25
  _ => {}
25
26
  }
26
27
  f(e);
@@ -71,6 +72,7 @@ pub fn childExprs(e: &mut Expr) -> Vec<&mut Expr> {
71
72
  })
72
73
  .collect(),
73
74
  ExprKind::Closure(_)
75
+ | ExprKind::Block(_)
74
76
  | ExprKind::Int(_)
75
77
  | ExprKind::Float(_)
76
78
  | ExprKind::BoolLit(_)
@@ -170,6 +172,7 @@ pub fn childRefs(e: &Expr) -> Vec<&Expr> {
170
172
  })
171
173
  .collect(),
172
174
  ExprKind::Closure(_)
175
+ | ExprKind::Block(_)
173
176
  | ExprKind::Int(_)
174
177
  | ExprKind::Float(_)
175
178
  | ExprKind::BoolLit(_)
@@ -247,6 +250,7 @@ pub fn anyExpr(e: &Expr, pred: &mut dyn FnMut(&Expr) -> bool) -> bool {
247
250
  }
248
251
  match &e.kind {
249
252
  ExprKind::Closure(c) => anyBlock(&c.body, pred),
253
+ ExprKind::Block(b) => anyBlock(b, pred),
250
254
  _ => false,
251
255
  }
252
256
  }
compiler/core/src/whistle.rs CHANGED
@@ -87,6 +87,8 @@ fn view(e: &Expr) -> View<'_> {
87
87
  ExprKind::Float(x) => Node(format!("float:{}", x.to_bits()), vec![]),
88
88
  ExprKind::BoolLit(b) => Node(format!("boollit:{b}"), vec![]),
89
89
  ExprKind::TypeName(n) => Node(format!("type:{n}"), vec![]),
90
+ // Opaque: never matched against another expression.
91
+ ExprKind::Block(b) => Node(format!("block/{}", b.stmts.len()), vec![]),
90
92
  ExprKind::Closure(c) => match c.body.stmts.as_slice() {
91
93
  [Stmt { kind: StmtKind::Expr(e, _, _), .. }] | [Stmt { kind: StmtKind::Return(Some(e)), .. }] => {
92
94
  Node(format!("closure/{}", c.params.len()), vec![e])
compiler/core/tests/core/main.rs CHANGED
@@ -16,6 +16,7 @@ mod match_body_parse_test;
16
16
  mod parser_test;
17
17
  mod purity_test;
18
18
  mod question_parse_test;
19
+ mod syntax_test;
19
20
  mod record_init_parse_test;
20
21
  mod record_init_test;
21
22
  mod rename_test;
compiler/core/tests/core/syntax_test.rs ADDED
@@ -0,0 +1,78 @@
1
+ #![allow(non_snake_case)]
2
+ //! `.=` and block `if` / `match` values at the parser: the shape they lower to, and the errors.
3
+ use plum_core::ast::*;
4
+ use plum_core::loadAndMergeDiag;
5
+ use std::fs;
6
+ use tempfile::TempDir;
7
+
8
+ fn parse(src: &str) -> Source {
9
+ plum_test_support::parse(src)
10
+ }
11
+
12
+ fn body(src: &str, name: &str) -> Vec<Stmt> {
13
+ let s = parse(src);
14
+ for item in s.items {
15
+ if let Item::Fn(f) = item {
16
+ if f.name == name {
17
+ if let FnBody::Block(b) = f.body {
18
+ return b.stmts;
19
+ }
20
+ }
21
+ }
22
+ }
23
+ panic!("no fn {name}");
24
+ }
25
+
26
+ #[test]
27
+ fn update_operator_is_a_field_assignment_of_a_method_call() {
28
+ let stmts = body("struct Cnt(v: Unit)\nstruct Bag(mut n: Cnt)\nfun f(b: Bag, u: Unit) -> Unit =\n b.n .= bump(u)\n u\n", "f");
29
+ let StmtKind::Assign(a) = &stmts[0].kind else { panic!("expected an assignment, got {:?}", stmts[0].kind) };
30
+ assert!(!a.declare);
31
+ let [AssignTarget::Field(obj, field)] = a.targets.as_slice() else { panic!("expected a field target") };
32
+ assert!(matches!(obj.kind, ExprKind::Var(ref v) if v == "b"));
33
+ assert_eq!(field, "n");
34
+ let ExprKind::Attribute(at) = &a.values[0].kind else { panic!("expected a method call") };
35
+ let AttrKind::Method(call) = &at.attr else { panic!("expected a method call") };
36
+ assert_eq!(call.name, "bump");
37
+ // the receiver is the field read `b.n`
38
+ let ExprKind::Attribute(recv) = &at.object.kind else { panic!("receiver should be b.n") };
39
+ assert!(matches!(&recv.attr, AttrKind::Field(f) if f == "n"));
40
+ }
41
+
42
+ #[test]
43
+ fn update_operator_binds_a_computed_receiver_once() {
44
+ let stmts = body("struct Cnt(v: Unit)\nstruct Bag(mut n: Cnt)\nfun mk(u: Unit) -> Bag = Bag(n: Cnt(v: u))\nfun f(u: Unit) -> Unit =\n mk(u).n .= bump(u)\n u\n", "f");
45
+ // `__up..L_C := mk(u)` then `__up.n = __up.n.bump(u)`
46
+ let StmtKind::Assign(first) = &stmts[0].kind else { panic!("expected a temporary") };
47
+ assert!(first.declare);
48
+ let [AssignTarget::Var(tmp)] = first.targets.as_slice() else { panic!() };
49
+ assert!(tmp.starts_with("__up"));
50
+ let StmtKind::Assign(second) = &stmts[1].kind else { panic!("expected the update") };
51
+ let [AssignTarget::Field(obj, _)] = second.targets.as_slice() else { panic!() };
52
+ assert!(matches!(&obj.kind, ExprKind::Var(v) if v == tmp));
53
+ }
54
+
55
+ #[test]
56
+ fn block_if_in_an_expression_slot_parses_to_a_block_value() {
57
+ let stmts = body("fun f(a: Bool) -> Unit =\n v := if a\n a\n else\n a\n v\n", "f");
58
+ // the `if` comes first, then `v := __blkN`
59
+ assert!(matches!(stmts[0].kind, StmtKind::If(_)));
60
+ let StmtKind::Assign(a) = &stmts[1].kind else { panic!() };
61
+ // lowered before checking: the value is a variable holding the branches' result
62
+ assert!(matches!(&a.values[0].kind, ExprKind::Var(n) if n.starts_with("__blk")), "{:?}", a.values[0].kind);
63
+ }
64
+
65
+ #[test]
66
+ fn update_operator_without_a_method_call_is_a_parse_error() {
67
+ let dir = TempDir::new().unwrap();
68
+ let lib = dir.path().join("libs");
69
+ fs::create_dir_all(&lib).unwrap();
70
+ let entry = lib.join("main.plum");
71
+ fs::write(
72
+ &entry,
73
+ "module fixtures\n\nstruct Cnt(v: Unit)\nstruct Bag(mut n: Cnt)\n\nfun f(b: Bag, c: Cnt) -> Unit =\n b.n .= c\n",
74
+ )
75
+ .unwrap();
76
+ let errs = loadAndMergeDiag(&entry, &lib).expect_err("a bare value after .= is rejected");
77
+ assert!(errs.iter().any(|e| e.message.contains("'.=' needs a method call")), "{errs:?}");
78
+ }
compiler/tooling/tree-sitter-plum/grammar.js CHANGED
@@ -71,6 +71,7 @@ module.exports = grammar({
71
71
  [$.fn_argument_list, $.class_argument_list],
72
72
  [$.bind_pattern, $.primary_expression],
73
73
  [$.bind_class_pattern, $.fn_argument_list, $.class_argument_list],
74
+ [$.field_path, $.primary_expression],
74
75
  ],
75
76
  rules: {
76
77
  source: ($) =>
@@ -247,7 +248,7 @@ module.exports = grammar({
247
248
  // emitting a `param` — see `parse_fn`.
248
249
  field("params", seq("(", optional(commaSep1(choice($.self, $.param))), ")")),
249
250
  field("returns", optional(seq("->", choice($.type, $.fn_value_type)))),
250
- optional(field("body", seq("=", choice($.expression, $.body, $.match)))),
251
+ optional(field("body", seq("=", choice($.expression, $.body)))),
251
252
  )
252
253
  ),
253
254
 
@@ -267,8 +268,6 @@ module.exports = grammar({
267
268
  $.assert,
268
269
  $.for,
269
270
  $.while,
270
- $.if,
271
- $.match,
272
271
  $.return,
273
272
  $.todo,
274
273
  $.crash,
@@ -311,6 +310,12 @@ module.exports = grammar({
311
310
  ),
312
311
  ),
313
312
  ),
313
+ // `self.items .= push(x)`: `self.items = self.items.push(x)`.
314
+ seq(
315
+ $.field_target,
316
+ field("op", ".="),
317
+ $.expression,
318
+ ),
314
319
  // `self.f: Type = value` (typed field assignment).
315
320
  seq(
316
321
  $.field_target,
@@ -332,13 +337,13 @@ module.exports = grammar({
332
337
  crash: ($) => prec.right(2, seq("crash", $.expression)),
333
338
 
334
339
  if: ($) =>
335
- seq(
340
+ prec.right(seq(
336
341
  "if",
337
342
  field("condition", choice($.expression, $.bind_condition)),
338
343
  field("body", $.body),
339
344
  repeat(field("alternative", $.else_if)),
340
345
  optional(field("otherwise", $.else)),
341
- ),
346
+ )),
342
347
  // `Pattern := expr[, cond]*` as an `if`/`else if`/`while` condition.
343
348
  bind_condition: ($) =>
344
349
  seq(
@@ -468,6 +473,10 @@ module.exports = grammar({
468
473
  $.closure,
469
474
  $.primary_expression,
470
475
  $.inline_if_expression,
476
+ // Block `if` / `match`: a statement when it stands alone, a value anywhere an
477
+ // expression goes (`v := if a` + indented branches).
478
+ $.if,
479
+ $.match,
471
480
  ),
472
481
 
473
482
  primary_expression: ($) =>
@@ -679,7 +688,10 @@ module.exports = grammar({
679
688
  ),
680
689
 
681
690
  field_argument: ($) =>
682
- seq(field("name", $.var_identifier), ":", field("value", $.expression)),
691
+ seq(field("name", choice($.var_identifier, $.field_path)), ":", field("value", $.expression)),
692
+
693
+ // `ship.x: 1.0` in a spread: updates a field of a nested struct.
694
+ field_path: ($) => seq($.var_identifier, repeat1(seq(".", $.var_identifier))),
683
695
 
684
696
  // Gleam-style functional-update entry: `Point(..p, x: 10)` — fields not
685
697
  // named after it are read from `p` instead of being required. Only ever
compiler/tooling/tree-sitter-plum/queries/plum/format.scm CHANGED
@@ -76,6 +76,7 @@
76
76
  [
77
77
  "="
78
78
  ":="
79
+ ".="
79
80
  ] @prepend_space @append_space
80
81
 
81
82
  "->" @prepend_space @append_space
compiler/tooling/tree-sitter-plum/queries/plum/highlights.scm CHANGED
@@ -58,6 +58,7 @@
58
58
  [
59
59
  "="
60
60
  ":="
61
+ ".="
61
62
  "!="
62
63
  "=="
63
64
  "*"
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/annotated_decl.txt CHANGED
@@ -115,30 +115,31 @@ fun main() =
115
115
  (fn
116
116
  (fn_identifier)
117
117
  (body
118
+ (expression
118
- (match
119
+ (match
119
- (expression
120
- (primary_expression
121
- (var_identifier)))
122
- (case
123
- (case_pattern
124
- (class_pattern
125
- (type_identifier)
126
- (case_pattern
127
- (dotted_name
128
- (var_identifier)))))
129
- (expression
130
- (primary_expression
131
- (var_identifier))))
132
- (case
133
- (case_pattern
134
- (class_pattern
135
- (type_identifier)
136
- (case_pattern
137
- (dotted_name
138
- (var_identifier)))))
139
120
  (expression
140
121
  (primary_expression
122
+ (var_identifier)))
123
+ (case
124
+ (case_pattern
125
+ (class_pattern
126
+ (type_identifier)
127
+ (case_pattern
128
+ (dotted_name
141
- (var_identifier)))))
129
+ (var_identifier)))))
130
+ (expression
131
+ (primary_expression
132
+ (var_identifier))))
133
+ (case
134
+ (case_pattern
135
+ (class_pattern
136
+ (type_identifier)
137
+ (case_pattern
138
+ (dotted_name
139
+ (var_identifier)))))
140
+ (expression
141
+ (primary_expression
142
+ (var_identifier))))))
142
143
  (expression
143
144
  (primary_expression
144
145
  (fn_call
@@ -149,19 +150,19 @@ fun main() =
149
150
  (expression
150
151
  (primary_expression
151
152
  (float))))))))
153
+ (expression
152
- (if
154
+ (if
153
- (bind_condition
155
+ (bind_condition
154
- (bind_pattern
156
+ (bind_pattern
155
- (var_identifier))
157
+ (var_identifier))
156
- (expression
157
- (primary_expression
158
- (var_identifier))))
159
- (body
160
- (assign
161
- (var_identifier)
162
- (type
163
- (type_identifier))
164
158
  (expression
165
159
  (primary_expression
160
+ (var_identifier))))
161
+ (body
162
+ (assign
163
+ (var_identifier)
164
+ (type
165
+ (type_identifier))
166
+ (expression
167
+ (primary_expression
166
- (var_identifier)))))))))
168
+ (var_identifier))))))))))
167
-
compiler/tooling/tree-sitter-plum/test/corpus/block_values.txt ADDED
@@ -0,0 +1,449 @@
1
+ ================================================================================
2
+ block if as a value
3
+ ================================================================================
4
+
5
+ fun f(a: Bool) -> Int =
6
+ v := if a
7
+ 1
8
+ else
9
+ 2
10
+ v
11
+
12
+ --------------------------------------------------------------------------------
13
+
14
+ (source
15
+ (fn
16
+ (fn_identifier)
17
+ (param
18
+ (var_identifier)
19
+ (type
20
+ (type_identifier)))
21
+ (type
22
+ (type_identifier))
23
+ (body
24
+ (assign
25
+ (var_identifier)
26
+ (expression
27
+ (if
28
+ (expression
29
+ (primary_expression
30
+ (var_identifier)))
31
+ (body
32
+ (expression
33
+ (primary_expression
34
+ (integer))))
35
+ (else
36
+ (body
37
+ (expression
38
+ (primary_expression
39
+ (integer))))))))
40
+ (expression
41
+ (primary_expression
42
+ (var_identifier))))))
43
+
44
+ ================================================================================
45
+ block match as a value
46
+ ================================================================================
47
+
48
+ fun f(o: Option[Int]) -> Int =
49
+ w := match o
50
+ Some(x) => x
51
+ None => 0
52
+ w
53
+
54
+ --------------------------------------------------------------------------------
55
+
56
+ (source
57
+ (fn
58
+ (fn_identifier)
59
+ (param
60
+ (var_identifier)
61
+ (type
62
+ (type_identifier)
63
+ (type
64
+ (type_identifier))))
65
+ (type
66
+ (type_identifier))
67
+ (body
68
+ (assign
69
+ (var_identifier)
70
+ (expression
71
+ (match
72
+ (expression
73
+ (primary_expression
74
+ (var_identifier)))
75
+ (case
76
+ (case_pattern
77
+ (class_pattern
78
+ (type_identifier)
79
+ (case_pattern
80
+ (dotted_name
81
+ (var_identifier)))))
82
+ (expression
83
+ (primary_expression
84
+ (var_identifier))))
85
+ (case
86
+ (case_pattern
87
+ (type_identifier))
88
+ (expression
89
+ (primary_expression
90
+ (integer)))))))
91
+ (expression
92
+ (primary_expression
93
+ (var_identifier))))))
94
+
95
+ ================================================================================
96
+ block if and match as call arguments
97
+ ================================================================================
98
+
99
+ fun f(a: Bool) -> Int =
100
+ g(if a
101
+ 1
102
+ else
103
+ 2)
104
+ h(1, match a
105
+ true => 1
106
+ false => 2)
107
+
108
+ --------------------------------------------------------------------------------
109
+
110
+ (source
111
+ (fn
112
+ (fn_identifier)
113
+ (param
114
+ (var_identifier)
115
+ (type
116
+ (type_identifier)))
117
+ (type
118
+ (type_identifier))
119
+ (body
120
+ (expression
121
+ (primary_expression
122
+ (fn_call
123
+ (var_identifier)
124
+ (fn_argument_list
125
+ (expression
126
+ (if
127
+ (expression
128
+ (primary_expression
129
+ (var_identifier)))
130
+ (body
131
+ (expression
132
+ (primary_expression
133
+ (integer))))
134
+ (else
135
+ (body
136
+ (expression
137
+ (primary_expression
138
+ (integer)))))))))))
139
+ (expression
140
+ (primary_expression
141
+ (fn_call
142
+ (var_identifier)
143
+ (fn_argument_list
144
+ (expression
145
+ (primary_expression
146
+ (integer)))
147
+ (expression
148
+ (match
149
+ (expression
150
+ (primary_expression
151
+ (var_identifier)))
152
+ (case
153
+ (case_pattern
154
+ (true))
155
+ (expression
156
+ (primary_expression
157
+ (integer))))
158
+ (case
159
+ (case_pattern
160
+ (false))
161
+ (expression
162
+ (primary_expression
163
+ (integer)))))))))))))
164
+
165
+ ================================================================================
166
+ block if with several statements and else if
167
+ ================================================================================
168
+
169
+ fun f(n: Int) -> Int =
170
+ v := if n < 0
171
+ t := 5
172
+ t * 2
173
+ else if n == 0
174
+ 0
175
+ else
176
+ 3
177
+ v
178
+
179
+ --------------------------------------------------------------------------------
180
+
181
+ (source
182
+ (fn
183
+ (fn_identifier)
184
+ (param
185
+ (var_identifier)
186
+ (type
187
+ (type_identifier)))
188
+ (type
189
+ (type_identifier))
190
+ (body
191
+ (assign
192
+ (var_identifier)
193
+ (expression
194
+ (if
195
+ (expression
196
+ (comparison_operator
197
+ (primary_expression
198
+ (var_identifier))
199
+ (primary_expression
200
+ (integer))))
201
+ (body
202
+ (assign
203
+ (var_identifier)
204
+ (expression
205
+ (primary_expression
206
+ (integer))))
207
+ (expression
208
+ (primary_expression
209
+ (binary_operator
210
+ (primary_expression
211
+ (var_identifier))
212
+ (primary_expression
213
+ (integer))))))
214
+ (else_if
215
+ (expression
216
+ (comparison_operator
217
+ (primary_expression
218
+ (var_identifier))
219
+ (primary_expression
220
+ (integer))))
221
+ (body
222
+ (expression
223
+ (primary_expression
224
+ (integer)))))
225
+ (else
226
+ (body
227
+ (expression
228
+ (primary_expression
229
+ (integer))))))))
230
+ (expression
231
+ (primary_expression
232
+ (var_identifier))))))
233
+
234
+ ================================================================================
235
+ block if as a closure body and a match arm
236
+ ================================================================================
237
+
238
+ fun f(xs: List[Int], o: Option[Int]) -> Int =
239
+ xs.map(|x| if x > 2
240
+ x
241
+ else
242
+ 0)
243
+ match o
244
+ Some(x) => if x > 1
245
+ x
246
+ else
247
+ 0
248
+ None => 0
249
+
250
+ --------------------------------------------------------------------------------
251
+
252
+ (source
253
+ (fn
254
+ (fn_identifier)
255
+ (param
256
+ (var_identifier)
257
+ (type
258
+ (type_identifier)
259
+ (type
260
+ (type_identifier))))
261
+ (param
262
+ (var_identifier)
263
+ (type
264
+ (type_identifier)
265
+ (type
266
+ (type_identifier))))
267
+ (type
268
+ (type_identifier))
269
+ (body
270
+ (expression
271
+ (primary_expression
272
+ (attribute
273
+ (primary_expression
274
+ (var_identifier))
275
+ (fn_identifier)
276
+ (fn_argument_list
277
+ (expression
278
+ (closure
279
+ (var_identifier)
280
+ (expression
281
+ (if
282
+ (expression
283
+ (comparison_operator
284
+ (primary_expression
285
+ (var_identifier))
286
+ (primary_expression
287
+ (integer))))
288
+ (body
289
+ (expression
290
+ (primary_expression
291
+ (var_identifier))))
292
+ (else
293
+ (body
294
+ (expression
295
+ (primary_expression
296
+ (integer)))))))))))))
297
+ (expression
298
+ (match
299
+ (expression
300
+ (primary_expression
301
+ (var_identifier)))
302
+ (case
303
+ (case_pattern
304
+ (class_pattern
305
+ (type_identifier)
306
+ (case_pattern
307
+ (dotted_name
308
+ (var_identifier)))))
309
+ (expression
310
+ (if
311
+ (expression
312
+ (comparison_operator
313
+ (primary_expression
314
+ (var_identifier))
315
+ (primary_expression
316
+ (integer))))
317
+ (body
318
+ (expression
319
+ (primary_expression
320
+ (var_identifier))))
321
+ (else
322
+ (body
323
+ (expression
324
+ (primary_expression
325
+ (integer))))))))
326
+ (case
327
+ (case_pattern
328
+ (type_identifier))
329
+ (expression
330
+ (primary_expression
331
+ (integer)))))))))
332
+
333
+ ================================================================================
334
+ update operator
335
+ ================================================================================
336
+
337
+ fun f(b: Bag, x: Int) -> Int =
338
+ b.items .= push(x)
339
+ a.b().c .= push(1).push(2)
340
+
341
+ --------------------------------------------------------------------------------
342
+
343
+ (source
344
+ (fn
345
+ (fn_identifier)
346
+ (param
347
+ (var_identifier)
348
+ (type
349
+ (type_identifier)))
350
+ (param
351
+ (var_identifier)
352
+ (type
353
+ (type_identifier)))
354
+ (type
355
+ (type_identifier))
356
+ (body
357
+ (assign
358
+ (field_target
359
+ (primary_expression
360
+ (var_identifier))
361
+ (fn_identifier))
362
+ (expression
363
+ (primary_expression
364
+ (fn_call
365
+ (var_identifier)
366
+ (fn_argument_list
367
+ (expression
368
+ (primary_expression
369
+ (var_identifier))))))))
370
+ (assign
371
+ (field_target
372
+ (primary_expression
373
+ (attribute
374
+ (primary_expression
375
+ (var_identifier))
376
+ (fn_identifier)
377
+ (fn_argument_list)))
378
+ (fn_identifier))
379
+ (expression
380
+ (primary_expression
381
+ (attribute
382
+ (primary_expression
383
+ (fn_call
384
+ (var_identifier)
385
+ (fn_argument_list
386
+ (expression
387
+ (primary_expression
388
+ (integer))))))
389
+ (fn_identifier)
390
+ (fn_argument_list
391
+ (expression
392
+ (primary_expression
393
+ (integer)))))))))))
394
+
395
+ ================================================================================
396
+ paths in a spread
397
+ ================================================================================
398
+
399
+ fun f(s: State) -> State =
400
+ State(..s, ship.x: 1.0, ship.y: 2.0, orb.ship.tag: 3, t: 4)
401
+
402
+ --------------------------------------------------------------------------------
403
+
404
+ (source
405
+ (fn
406
+ (fn_identifier)
407
+ (param
408
+ (var_identifier)
409
+ (type
410
+ (type_identifier)))
411
+ (type
412
+ (type_identifier))
413
+ (body
414
+ (expression
415
+ (primary_expression
416
+ (class_call
417
+ (type_identifier)
418
+ (class_argument_list
419
+ (spread_argument
420
+ (expression
421
+ (primary_expression
422
+ (var_identifier))))
423
+ (field_argument
424
+ (field_path
425
+ (var_identifier)
426
+ (var_identifier))
427
+ (expression
428
+ (primary_expression
429
+ (float))))
430
+ (field_argument
431
+ (field_path
432
+ (var_identifier)
433
+ (var_identifier))
434
+ (expression
435
+ (primary_expression
436
+ (float))))
437
+ (field_argument
438
+ (field_path
439
+ (var_identifier)
440
+ (var_identifier)
441
+ (var_identifier))
442
+ (expression
443
+ (primary_expression
444
+ (integer))))
445
+ (field_argument
446
+ (var_identifier)
447
+ (expression
448
+ (primary_expression
449
+ (integer)))))))))))
compiler/tooling/tree-sitter-plum/test/corpus/closure_match_arg.txt CHANGED
@@ -26,21 +26,22 @@ fun main() =
26
26
  (closure
27
27
  (var_identifier)
28
28
  (body
29
+ (expression
29
- (match
30
+ (match
30
- (expression
31
- (primary_expression
32
- (var_identifier)))
33
- (case
34
- (case_pattern
35
- (type_identifier))
36
31
  (expression
37
32
  (primary_expression
33
+ (var_identifier)))
34
+ (case
35
+ (case_pattern
36
+ (type_identifier))
37
+ (expression
38
+ (primary_expression
38
- (integer))))
39
+ (integer))))
39
- (case
40
+ (case
40
- (case_pattern)
41
+ (case_pattern)
41
- (expression
42
+ (expression
42
- (primary_expression
43
+ (primary_expression
43
- (integer))))))))))))))))
44
+ (integer)))))))))))))))))
44
45
 
45
46
  ================================================================================
46
47
  typed closure parameter
compiler/tooling/tree-sitter-plum/test/corpus/digit_names.txt CHANGED
@@ -88,26 +88,27 @@ fun f(w: V2) =
88
88
  (type
89
89
  (type_identifier)))
90
90
  (body
91
+ (expression
91
- (match
92
+ (match
92
- (expression
93
- (primary_expression
94
- (var_identifier)))
95
- (case
96
- (case_pattern
97
- (class_pattern
98
- (type_identifier)
99
- (case_pattern
100
- (dotted_name
101
- (var_identifier)))))
102
- (expression
103
- (primary_expression
104
- (var_identifier))))
105
- (case
106
- (case_pattern
107
- (type_identifier))
108
93
  (expression
109
94
  (primary_expression
95
+ (var_identifier)))
96
+ (case
97
+ (case_pattern
98
+ (class_pattern
99
+ (type_identifier)
100
+ (case_pattern
101
+ (dotted_name
102
+ (var_identifier)))))
103
+ (expression
104
+ (primary_expression
105
+ (var_identifier))))
106
+ (case
107
+ (case_pattern
108
+ (type_identifier))
109
+ (expression
110
+ (primary_expression
110
- (integer))))))))
111
+ (integer)))))))))
111
112
 
112
113
  ================================================================================
113
114
  digit names - pattern if
@@ -129,31 +130,33 @@ fun f(w: V2) =
129
130
  (type
130
131
  (type_identifier)))
131
132
  (body
133
+ (expression
132
- (if
134
+ (if
133
- (bind_condition
135
+ (bind_condition
134
- (bind_pattern
136
+ (bind_pattern
135
- (type_identifier))
137
+ (type_identifier))
136
- (expression
138
+ (expression
137
- (primary_expression
139
+ (primary_expression
138
- (var_identifier))))
139
- (body
140
- (expression
141
- (primary_expression
142
- (integer)))))
143
- (if
144
- (bind_condition
145
- (bind_pattern
146
- (bind_class_pattern
147
- (type_identifier)
148
- (bind_pattern
149
140
  (var_identifier))))
141
+ (body
150
- (expression
142
+ (expression
151
- (primary_expression
143
+ (primary_expression
144
+ (integer))))))
145
+ (expression
146
+ (if
147
+ (bind_condition
148
+ (bind_pattern
149
+ (bind_class_pattern
150
+ (type_identifier)
151
+ (bind_pattern
152
- (var_identifier))))
152
+ (var_identifier))))
153
+ (expression
154
+ (primary_expression
155
+ (var_identifier))))
153
- (body
156
+ (body
154
- (expression
157
+ (expression
155
- (primary_expression
158
+ (primary_expression
156
- (var_identifier))))))))
159
+ (var_identifier)))))))))
157
160
 
158
161
  ================================================================================
159
162
  digit names - qualified const access
@@ -226,3 +229,5 @@ primitive Lim =
226
229
  MAX_VALUE = 1
227
230
 
228
231
  --------------------------------------------------------------------------------
232
+
233
+
compiler/tooling/tree-sitter-plum/test/corpus/enum.txt CHANGED
@@ -100,22 +100,23 @@ enum Step =
100
100
  (type
101
101
  (type_identifier))
102
102
  (body
103
+ (expression
103
- (match
104
+ (match
104
- (expression
105
- (primary_expression
106
- (self)))
107
- (case
108
- (case_pattern
109
- (type_identifier))
110
- (expression
111
- (primary_expression
112
- (integer))))
113
- (case
114
- (case_pattern
115
- (type_identifier))
116
105
  (expression
117
106
  (primary_expression
107
+ (self)))
108
+ (case
109
+ (case_pattern
110
+ (type_identifier))
111
+ (expression
112
+ (primary_expression
113
+ (integer))))
114
+ (case
115
+ (case_pattern
116
+ (type_identifier))
117
+ (expression
118
+ (primary_expression
118
- (integer)))))))))
119
+ (integer))))))))))
119
120
 
120
121
  ================================================================================
121
122
  enum - named payload fields
compiler/tooling/tree-sitter-plum/test/corpus/function.txt CHANGED
@@ -507,21 +507,22 @@ fun f(x: Int) -> Int = match x
507
507
  (type_identifier)))
508
508
  (type
509
509
  (type_identifier))
510
+ (expression
510
- (match
511
+ (match
511
- (expression
512
- (primary_expression
513
- (var_identifier)))
514
- (case
515
- (case_pattern
516
- (integer))
517
- (expression
518
- (primary_expression
519
- (integer))))
520
- (case
521
- (case_pattern)
522
512
  (expression
523
513
  (primary_expression
514
+ (var_identifier)))
515
+ (case
516
+ (case_pattern
517
+ (integer))
518
+ (expression
519
+ (primary_expression
520
+ (integer))))
521
+ (case
522
+ (case_pattern)
523
+ (expression
524
+ (primary_expression
524
- (integer)))))))
525
+ (integer))))))))
525
526
 
526
527
  ================================================================================
527
528
  fn return type
compiler/tooling/tree-sitter-plum/test/corpus/if.txt CHANGED
@@ -21,32 +21,14 @@ fun main() =
21
21
  (fn
22
22
  (fn_identifier)
23
23
  (body
24
+ (expression
24
- (if
25
+ (if
25
- (expression
26
- (comparison_operator
27
- (primary_expression
28
- (var_identifier))
29
- (primary_expression
30
- (var_identifier))))
31
- (body
32
- (expression
33
- (primary_expression
34
- (fn_call
35
- (var_identifier)
36
- (fn_argument_list
37
- (expression
38
- (primary_expression
39
- (string
40
- (string_start)
41
- (string_content)
42
- (string_end)))))))))
43
- (else_if
44
26
  (expression
45
27
  (comparison_operator
46
28
  (primary_expression
47
29
  (var_identifier))
48
30
  (primary_expression
49
- (integer))))
31
+ (var_identifier))))
50
32
  (body
51
33
  (expression
52
34
  (primary_expression
@@ -54,58 +36,78 @@ fun main() =
54
36
  (var_identifier)
55
37
  (fn_argument_list
56
38
  (expression
57
- (comparison_operator
58
- (primary_expression
39
+ (primary_expression
40
+ (string
59
- (var_identifier))
41
+ (string_start)
60
- (primary_expression
42
+ (string_content)
61
- (integer))))))))))
43
+ (string_end)))))))))
62
- (else_if
44
+ (else_if
63
- (expression
64
- (comparison_operator
65
- (primary_expression
66
- (var_identifier))
67
- (primary_expression
68
- (integer))))
69
- (body
70
45
  (expression
46
+ (comparison_operator
71
- (primary_expression
47
+ (primary_expression
72
- (fn_call
73
- (var_identifier)
48
+ (var_identifier))
74
- (fn_argument_list
75
- (expression
76
- (comparison_operator
77
- (primary_expression
49
+ (primary_expression
78
- (var_identifier))
79
- (primary_expression
80
- (integer))))))))))
50
+ (integer))))
81
- (else
82
- (body
51
+ (body
83
- (if
84
52
  (expression
53
+ (primary_expression
54
+ (fn_call
55
+ (var_identifier)
56
+ (fn_argument_list
57
+ (expression
85
- (comparison_operator
58
+ (comparison_operator
86
- (primary_expression
59
+ (primary_expression
87
- (var_identifier))
60
+ (var_identifier))
88
- (primary_expression
89
- (integer))))
90
- (body
91
- (expression
92
- (primary_expression
93
- (fn_call
94
- (var_identifier)
95
- (fn_argument_list
96
- (expression
97
61
  (primary_expression
62
+ (integer))))))))))
63
+ (else_if
64
+ (expression
65
+ (comparison_operator
66
+ (primary_expression
98
- (var_identifier))))))))
67
+ (var_identifier))
68
+ (primary_expression
69
+ (integer))))
70
+ (body
71
+ (expression
72
+ (primary_expression
73
+ (fn_call
74
+ (var_identifier)
75
+ (fn_argument_list
76
+ (expression
77
+ (comparison_operator
78
+ (primary_expression
79
+ (var_identifier))
80
+ (primary_expression
81
+ (integer))))))))))
99
- (else
82
+ (else
100
- (body
83
+ (body
84
+ (expression
85
+ (if
101
86
  (expression
87
+ (comparison_operator
102
- (primary_expression
88
+ (primary_expression
89
+ (var_identifier))
90
+ (primary_expression
91
+ (integer))))
92
+ (body
93
+ (expression
94
+ (primary_expression
103
- (fn_call
95
+ (fn_call
104
- (var_identifier)
96
+ (var_identifier)
105
- (fn_argument_list
97
+ (fn_argument_list
106
- (expression
98
+ (expression
107
- (primary_expression
99
+ (primary_expression
100
+ (var_identifier))))))))
101
+ (else
102
+ (body
103
+ (expression
104
+ (primary_expression
105
+ (fn_call
106
+ (var_identifier)
107
+ (fn_argument_list
108
+ (expression
109
+ (primary_expression
108
- (string
110
+ (string
109
- (string_start)
111
+ (string_start)
110
- (string_content)
112
+ (string_content)
111
- (string_end)))))))))))))))))
113
+ (string_end)))))))))))))))))))
compiler/tooling/tree-sitter-plum/test/corpus/match.txt CHANGED
@@ -23,57 +23,115 @@ fun main() =
23
23
  (fn
24
24
  (fn_identifier)
25
25
  (body
26
- (match
27
- (expression
28
- (primary_expression
29
- (var_identifier)))
30
- (case
31
- (case_pattern
32
- (integer))
33
- (body
34
- (expression
35
- (primary_expression
36
- (fn_call
37
- (var_identifier)
38
- (fn_argument_list
39
- (expression
40
- (primary_expression
41
- (var_identifier)))))))))
42
- (case
43
- (case_pattern
44
- (string
45
- (string_start)
46
- (string_content)
47
- (string_end)))
48
- (body
49
- (expression
50
- (primary_expression
51
- (fn_call
52
- (var_identifier)
53
- (fn_argument_list
54
- (expression
55
- (primary_expression
56
- (var_identifier)))))))))
57
- (case
58
- (case_pattern
59
- (true))
60
- (body
61
- (expression
62
- (primary_expression
63
- (fn_call
64
- (var_identifier)
65
- (fn_argument_list
66
- (expression
67
- (primary_expression
68
- (var_identifier)))))))))
69
- (case
70
- (case_pattern
71
- (class_pattern
72
- (type_identifier)
73
- (case_pattern
74
- (dotted_name
75
- (var_identifier)))))
76
- (body
26
+ (expression
27
+ (match
28
+ (expression
29
+ (primary_expression
30
+ (var_identifier)))
31
+ (case
32
+ (case_pattern
33
+ (integer))
34
+ (body
35
+ (expression
36
+ (primary_expression
37
+ (fn_call
38
+ (var_identifier)
39
+ (fn_argument_list
40
+ (expression
41
+ (primary_expression
42
+ (var_identifier)))))))))
43
+ (case
44
+ (case_pattern
45
+ (string
46
+ (string_start)
47
+ (string_content)
48
+ (string_end)))
49
+ (body
50
+ (expression
51
+ (primary_expression
52
+ (fn_call
53
+ (var_identifier)
54
+ (fn_argument_list
55
+ (expression
56
+ (primary_expression
57
+ (var_identifier)))))))))
58
+ (case
59
+ (case_pattern
60
+ (true))
61
+ (body
62
+ (expression
63
+ (primary_expression
64
+ (fn_call
65
+ (var_identifier)
66
+ (fn_argument_list
67
+ (expression
68
+ (primary_expression
69
+ (var_identifier)))))))))
70
+ (case
71
+ (case_pattern
72
+ (class_pattern
73
+ (type_identifier)
74
+ (case_pattern
75
+ (dotted_name
76
+ (var_identifier)))))
77
+ (body
78
+ (expression
79
+ (primary_expression
80
+ (fn_call
81
+ (var_identifier)
82
+ (fn_argument_list
83
+ (expression
84
+ (primary_expression
85
+ (var_identifier)))))))))
86
+ (case
87
+ (case_pattern
88
+ (dotted_name
89
+ (var_identifier)))
90
+ (body
91
+ (expression
92
+ (primary_expression
93
+ (fn_call
94
+ (var_identifier)
95
+ (fn_argument_list
96
+ (expression
97
+ (primary_expression
98
+ (var_identifier)))))))))
99
+ (case
100
+ (case_pattern)
101
+ (body
102
+ (expression
103
+ (primary_expression
104
+ (fn_call
105
+ (var_identifier)
106
+ (fn_argument_list
107
+ (expression
108
+ (primary_expression
109
+ (var_identifier))))))))))))))
110
+
111
+ ================================================================================
112
+ match - inline case bodies
113
+ ================================================================================
114
+
115
+ fun main() =
116
+ match a
117
+ 1 => printLn(a)
118
+ 2 => printLn(b)
119
+ _ => printLn(c)
120
+
121
+ --------------------------------------------------------------------------------
122
+
123
+ (source
124
+ (fn
125
+ (fn_identifier)
126
+ (body
127
+ (expression
128
+ (match
129
+ (expression
130
+ (primary_expression
131
+ (var_identifier)))
132
+ (case
133
+ (case_pattern
134
+ (integer))
77
135
  (expression
78
136
  (primary_expression
79
137
  (fn_call
@@ -81,12 +139,10 @@ fun main() =
81
139
  (fn_argument_list
82
140
  (expression
83
141
  (primary_expression
84
- (var_identifier)))))))))
142
+ (var_identifier))))))))
85
- (case
143
+ (case
86
- (case_pattern
144
+ (case_pattern
87
- (dotted_name
88
- (var_identifier)))
145
+ (integer))
89
- (body
90
146
  (expression
91
147
  (primary_expression
92
148
  (fn_call
@@ -94,10 +150,9 @@ fun main() =
94
150
  (fn_argument_list
95
151
  (expression
96
152
  (primary_expression
97
- (var_identifier)))))))))
153
+ (var_identifier))))))))
98
- (case
154
+ (case
99
- (case_pattern)
155
+ (case_pattern)
100
- (body
101
156
  (expression
102
157
  (primary_expression
103
158
  (fn_call
@@ -107,59 +162,6 @@ fun main() =
107
162
  (primary_expression
108
163
  (var_identifier)))))))))))))
109
164
 
110
- ================================================================================
111
- match - inline case bodies
112
- ================================================================================
113
-
114
- fun main() =
115
- match a
116
- 1 => printLn(a)
117
- 2 => printLn(b)
118
- _ => printLn(c)
119
-
120
- --------------------------------------------------------------------------------
121
-
122
- (source
123
- (fn
124
- (fn_identifier)
125
- (body
126
- (match
127
- (expression
128
- (primary_expression
129
- (var_identifier)))
130
- (case
131
- (case_pattern
132
- (integer))
133
- (expression
134
- (primary_expression
135
- (fn_call
136
- (var_identifier)
137
- (fn_argument_list
138
- (expression
139
- (primary_expression
140
- (var_identifier))))))))
141
- (case
142
- (case_pattern
143
- (integer))
144
- (expression
145
- (primary_expression
146
- (fn_call
147
- (var_identifier)
148
- (fn_argument_list
149
- (expression
150
- (primary_expression
151
- (var_identifier))))))))
152
- (case
153
- (case_pattern)
154
- (expression
155
- (primary_expression
156
- (fn_call
157
- (var_identifier)
158
- (fn_argument_list
159
- (expression
160
- (primary_expression
161
- (var_identifier))))))))))))
162
-
163
165
  ================================================================================
164
166
  match - guard-clause arms, no subject
165
167
  ================================================================================
@@ -189,33 +191,34 @@ fun compare(x: Int, y: Int) -> Int =
189
191
  (type
190
192
  (type_identifier))
191
193
  (body
194
+ (expression
192
- (match
195
+ (match
193
- (guard_case
196
+ (guard_case
194
- (expression
195
- (comparison_operator
196
- (primary_expression
197
- (var_identifier))
198
- (primary_expression
199
- (var_identifier))))
200
- (body
201
- (expression
202
- (primary_expression
203
- (integer)))))
204
- (guard_case
205
- (expression
206
- (comparison_operator
207
- (primary_expression
208
- (var_identifier))
209
- (primary_expression
210
- (var_identifier))))
211
- (body
212
197
  (expression
198
+ (comparison_operator
213
- (primary_expression
199
+ (primary_expression
200
+ (var_identifier))
201
+ (primary_expression
202
+ (var_identifier))))
203
+ (body
204
+ (expression
205
+ (primary_expression
214
- (integer)))))
206
+ (integer)))))
215
- (guard_case
207
+ (guard_case
216
- (body
217
208
  (expression
209
+ (comparison_operator
218
- (primary_expression
210
+ (primary_expression
211
+ (var_identifier))
212
+ (primary_expression
213
+ (var_identifier))))
214
+ (body
215
+ (expression
216
+ (primary_expression
217
+ (integer)))))
218
+ (guard_case
219
+ (body
220
+ (expression
221
+ (primary_expression
219
- (unary_operator
222
+ (unary_operator
220
- (primary_expression
223
+ (primary_expression
221
- (integer)))))))))))
224
+ (integer))))))))))))
compiler/tooling/tree-sitter-plum/test/corpus/single_letter.txt CHANGED
@@ -28,22 +28,23 @@ fun unP(v: Two) -> Int = match v
28
28
  (type_identifier)))
29
29
  (type
30
30
  (type_identifier))
31
+ (expression
31
- (match
32
+ (match
32
- (expression
33
- (primary_expression
34
- (var_identifier)))
35
- (case
36
- (case_pattern
37
- (type_identifier))
38
- (expression
39
- (primary_expression
40
- (integer))))
41
- (case
42
- (case_pattern
43
- (type_identifier))
44
33
  (expression
45
34
  (primary_expression
35
+ (var_identifier)))
36
+ (case
37
+ (case_pattern
38
+ (type_identifier))
39
+ (expression
40
+ (primary_expression
41
+ (integer))))
42
+ (case
43
+ (case_pattern
44
+ (type_identifier))
45
+ (expression
46
+ (primary_expression
46
- (integer))))))
47
+ (integer)))))))
47
48
  (fn
48
49
  (fn_identifier)
49
50
  (param
@@ -52,20 +53,21 @@ fun unP(v: Two) -> Int = match v
52
53
  (type_identifier)))
53
54
  (type
54
55
  (type_identifier))
56
+ (expression
55
- (match
57
+ (match
56
- (expression
57
- (primary_expression
58
- (var_identifier)))
59
- (case
60
- (case_pattern
61
- (class_pattern
62
- (type_identifier)
63
- (case_pattern
64
- (dotted_name
65
- (var_identifier)))))
66
58
  (expression
67
59
  (primary_expression
60
+ (var_identifier)))
61
+ (case
62
+ (case_pattern
63
+ (class_pattern
64
+ (type_identifier)
65
+ (case_pattern
66
+ (dotted_name
67
+ (var_identifier)))))
68
+ (expression
69
+ (primary_expression
68
- (var_identifier)))))))
70
+ (var_identifier))))))))
69
71
 
70
72
  ================================================================================
71
73
  single letter - constructor call and bare tag
compiler/tooling/vscode-plum/syntaxes/plum.tmLanguage.json CHANGED
@@ -77,8 +77,9 @@
77
77
  "match": "(\\+|\\-|/|\\*|%)"
78
78
  },
79
79
  {
80
+ "comment": "`.=` updates a field with a method call: `self.items .= push(x)`",
80
81
  "name": "keyword.operator.assignment.plum",
81
- "match": ":?="
82
+ "match": "\\.=|:?="
82
83
  }
83
84
  ]
84
85
  },
compiler/wasm-codegen/src/closures.rs CHANGED
@@ -187,6 +187,8 @@ impl<'a, 't> ClosureWalker<'a, 't> {
187
187
  }
188
188
  }
189
189
  ast::Expr { kind: ast::ExprKind::Closure(cl), .. } => self.recordClosure(expr, cl),
190
+ // Lifted into statements by `plum_core::blocks` before checking.
191
+ ast::Expr { kind: ast::ExprKind::Block(_), .. } => {}
190
192
  ast::Expr { kind: ast::ExprKind::Binary(b), .. } => {
191
193
  self.walkExpr(&b.left);
192
194
  self.walkExpr(&b.right);
compiler/wasm-codegen/src/expr.rs CHANGED
@@ -47,6 +47,9 @@ pub(crate) fn compileExpr(
47
47
  state: &mut ModuleState,
48
48
  ) -> Result<(), String> {
49
49
  match expr {
50
+ ast::Expr { kind: ast::ExprKind::Block(_), .. } => {
51
+ return Err("codegen: a block 'if' or 'match' value reached codegen unlowered".to_string())
52
+ }
50
53
  ast::Expr { kind: ast::ExprKind::Bang(b), .. } => compileEnumUnwrap(expr, &b.value, false, body, ctx, state)?,
51
54
  ast::Expr { kind: ast::ExprKind::Bind(b), .. } => {
52
55
  let value_ty = inferLocalType(&b.value, ctx);
compiler/wasm-codegen/src/fnbody.rs CHANGED
@@ -258,6 +258,8 @@ impl<'a> Collector<'a> {
258
258
  // A closure literal's body has its own locals, belonging to the separate
259
259
  // closure function it compiles to — nothing to recurse into here.
260
260
  ast::Expr { kind: ast::ExprKind::Closure(_), .. } => {}
261
+ // Lifted into statements by `plum_core::blocks` before checking.
262
+ ast::Expr { kind: ast::ExprKind::Block(_), .. } => {}
261
263
  }
262
264
  }
263
265
 
tests/syntax/block_values.plum ADDED
@@ -0,0 +1,141 @@
1
+ # Block `if` / `match` as values: anywhere an expression goes.
2
+ import std/Float
3
+ import std/Option
4
+ import std/Result
5
+ import std/Int
6
+ import std/List
7
+ import std/Str
8
+
9
+ enum Oops =
10
+ | Bad
11
+
12
+ fun half(n: Int) -> Result[Int, Oops] =
13
+ if n % 2 == 0 then Ok(n / 2) else Err(Bad)
14
+
15
+ fun withQ(a: Bool, n: Int) -> Result[Int, Oops] =
16
+ v := if a
17
+ h := half(n)?
18
+ h + 100
19
+ else
20
+ 7
21
+ Ok(v + 1)
22
+
23
+ fun nested(a: Bool, b: Bool) -> Int =
24
+ v := if a
25
+ if b
26
+ 1
27
+ else
28
+ 2
29
+ else
30
+ match b
31
+ true => 3
32
+ false => 4
33
+ v
34
+
35
+ fun inClosure(xs: List[Int]) -> List[Int] =
36
+ xs.map(|x| if x > 2
37
+ x * 10
38
+ else
39
+ x)
40
+
41
+ fun two(a: Bool) -> Int =
42
+ id2(f2(), match a
43
+ true => 10
44
+ false => 20)
45
+
46
+ fun f2() -> Int = 1
47
+
48
+ fun id2(a: Int, b: Int) -> Int = a * 100 + b
49
+
50
+ fun elseif(n: Int) -> Int =
51
+ v := if n < 0
52
+ 0 - 1
53
+ else if n == 0
54
+ 0
55
+ else
56
+ 1
57
+ v
58
+
59
+ fun withDiverge(n: Int) -> Result[Int, Oops] =
60
+ v := match half(n)
61
+ Ok(x) => x
62
+ Err(e) => 0 - 5
63
+ Ok(v)
64
+
65
+ fun annotated(a: Bool) -> Float =
66
+ x: Float := if a
67
+ 1.5
68
+ else
69
+ 2.5
70
+ x
71
+
72
+ fun show(r: Result[Int, Oops]) -> Int = match r
73
+ Ok(v) => v
74
+ Err(_) => 0 - 1
75
+
76
+ fun res(a: Bool) -> Result[Int, Oops] =
77
+ v := if a
78
+ Ok(1)
79
+ else
80
+ Err(Bad)
81
+ v
82
+
83
+ fun pick(a: Bool) -> Int =
84
+ v := if a
85
+ 1
86
+ else
87
+ 2
88
+ v
89
+
90
+ fun opt(o: Option[Int]) -> Int =
91
+ w := match o
92
+ Some(x) => x
93
+ None => 0
94
+ w
95
+
96
+ fun idInt(n: Int) -> Int = n
97
+
98
+ fun arg(a: Bool) -> Int =
99
+ idInt(if a
100
+ 10
101
+ else
102
+ 20)
103
+
104
+ fun multi(a: Bool) -> Int =
105
+ v := if a
106
+ t := 5
107
+ t * 2
108
+ else
109
+ 3
110
+ v + 1
111
+
112
+ test "blocks"
113
+ assert pick(true) == 1
114
+ assert pick(false) == 2
115
+ assert opt(Some(7)) == 7
116
+ assert opt(None) == 0
117
+ assert arg(true) == 10
118
+ assert arg(false) == 20
119
+ assert multi(true) == 11
120
+ assert multi(false) == 4
121
+
122
+ test "more"
123
+ assert show(withQ(true, 4)) == 103
124
+ assert show(withQ(false, 4)) == 8
125
+ assert show(withQ(true, 3)) == 0 - 1
126
+ assert nested(true, true) == 1
127
+ assert nested(true, false) == 2
128
+ assert nested(false, true) == 3
129
+ assert nested(false, false) == 4
130
+ assert inClosure([1, 5]).at(0) == 1
131
+ assert inClosure([1, 5]).at(1) == 50
132
+ assert two(true) == 110
133
+ assert two(false) == 120
134
+ assert elseif(0 - 4) == 0 - 1
135
+ assert elseif(0) == 0
136
+ assert elseif(9) == 1
137
+ assert show(withDiverge(4)) == 2
138
+ assert show(withDiverge(3)) == 0 - 5
139
+ assert annotated(true) == 1.5
140
+ assert show(res(true)) == 1
141
+ assert show(res(false)) == 0 - 1
tests/syntax/update_paths.plum ADDED
@@ -0,0 +1,59 @@
1
+ # `.=` and paths in spreads.
2
+ import std/Array
3
+ import std/Int
4
+
5
+ struct Bag(mut items: Array[Int], mut n: Int)
6
+
7
+ struct Ship(x: Int, y: Int)
8
+ struct Orb(ship: Ship, tag: Int)
9
+ struct State(orb: Orb, ship: Ship, t: Int)
10
+
11
+ struct Counter(mut hits: Int)
12
+
13
+ fun bump(c: Counter, log: Counter) -> Counter =
14
+ log.hits = log.hits + 1
15
+ c
16
+
17
+ fun add(b: Bag, x: Int) -> Int =
18
+ b.items .= push(x)
19
+ b.n .= max(3)
20
+ b.n
21
+
22
+ fun twice(c: Counter, log: Counter) -> Int =
23
+ bump(c, log).hits .= max(5)
24
+ log.hits
25
+
26
+ fun move(s: State) -> State =
27
+ State(..s, ship.x: 10, orb.ship.y: 7, orb.tag: 2)
28
+
29
+ fun sharedPrefix(s: State) -> State =
30
+ State(..s, ship.x: 1, ship.y: 2)
31
+
32
+ fun nonVarSpread(s: State) -> State =
33
+ State(..s, ship.x: 99)
34
+
35
+ test "update"
36
+ b := Bag(items: Array[Int](), n: 0)
37
+ assert add(b, 4) == 3
38
+ assert add(b, 5) == 3
39
+ assert b.items.length() == 2
40
+ c := Counter(hits: 0)
41
+ log := Counter(hits: 0)
42
+ assert twice(c, log) == 1
43
+ assert c.hits == 5
44
+
45
+ test "paths"
46
+ s := State(orb: Orb(ship: Ship(x: 1, y: 2), tag: 3), ship: Ship(x: 4, y: 5), t: 6)
47
+ m := move(s)
48
+ assert m.ship.x == 10
49
+ assert m.ship.y == 5
50
+ assert m.orb.ship.x == 1
51
+ assert m.orb.ship.y == 7
52
+ assert m.orb.tag == 2
53
+ assert s.ship.x == 4
54
+ p := sharedPrefix(s)
55
+ assert p.ship.x == 1
56
+ assert p.ship.y == 2
57
+ assert p.t == 6
58
+ assert nonVarSpread(s).ship.x == 99
59
+ assert nonVarSpread(s).ship.y == 5