plum

#treesitter#compiler#wasm

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

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


47f787c — Peter John 2026-11-13T22:03:17+05:30
children blocks: a call or a construction takes its last argument as a trailing block, `Overlay(w: Arena.W, h: Arena.H) {` + one item a line + `}`, whose items are a list literal's (a value, `..xs`, `if c then x`, `if c then ..xs`), separated by line breaks or commas; on a function or method call the block is the last argument, after the others (`Demo.sum(1) { 2, 3 }` is `Demo.sum(1, [2, 3])`), and on a construction it is the value of the type's last field, which must be a `List` (`Overlay`'s and `Group`'s `children`) and can't also be given by name; `Type() { .. }` is a construction; why braces and not an indented block: `Overlay(..)` + an indented block can't be told from a call followed by an indented statement or a continuation line without making every call's line end significant, while `{` after a call's `)` was unused, and the scanner settles the one clash, a `{ x }` grouping that starts the next statement: the block's `{` is a new external token, `_block_open`, given only when the `{` is on the line of the call's `)` (spaces and tabs between), so `p := P(x: 1)` + a line `{ a }.b()` is still two statements; a list literal may break its items over lines without commas too (`fun view(self) -> List<View> = [` + one item a line + `]`), which is how a view's whole body reads as one block; a `{ .. }` as a whole body was not taken because `{ x }` is a grouping, so a one-item block and a grouping would be the same text; grammar: `children_block` (an optional `block` field on `fn_call`, `class_call` and a method `attribute`), `list_literal` and `children_block` share `_list_items`, whose separator is `,`, the scanner's `_newline` or both (inside the brackets the scanner already gives `_newline` only where it is asked for, so an item ends with its line; a long item breaks inside its brackets); parser: the block is lowered by `parseListLiteral` (core/list_items.rs, unchanged), appended as a positional argument to a call, and on a construction written as a field named `{block}` that core/children_block.rs (`nameBlockFields`, first in the front end, before field defaults are filled) renames to the type's last field, with errors at the call for a last field that is not a `List` ("it is the value of the last field, `n`, which is a `Int`, not a `List`"), one also given by name, and a type with no named fields; checker: an inline `if`'s branch of a narrower covariant type than the one expected is upcast to it (`if c then Cons(head: dot, tail: sqs) else sqs` in a `List<Shape>` slot), which fixes a list literal whose `if` item is followed by plain items of another implementer (`[if c then Dot(..), Sq(..)]` as a `List<Shape>` was "inline if branches: type mismatch"); formatter: a list literal or a block written across lines keeps one item a line (`[`/`{` then an indent, `]`/`}` on its own line), one written on a line stays on it, `{}` stays empty; tests: tests/syntax/children_blocks.plum (constructions with and without other fields, all defaults, empty and one-line blocks, nesting, each item form, plain elements, calls and methods taking the block last, item order, a list literal on lines, covariant children, a spread construction, a grouping on the next line) in all three modes, checker diagnostics for the three errors and for a `{` on the next line, a formatter test, a corpus case; docs: language.md (items on lines, blocks)
compiler/checker/src/infer.rs CHANGED
@@ -513,8 +513,19 @@ pub(crate) fn inferExprInner(
513
513
  let ct = inferExpr(&t.condition, env, ctx)?;
514
514
  unify(&PlumType::TBool, &ct, ctx).map_err(|e| blame(&t.condition, format!("inline if condition: {}", e)))?;
515
515
  let tenv = bindCondEnv(&t.condition, env, ctx)?;
516
- let tt = inferExprWith(&t.then, &tenv, ctx, expected)?;
516
+ let mut tt = inferExprWith(&t.then, &tenv, ctx, expected)?;
517
- let et = inferExprWith(&t.else_, env, ctx, expected)?;
517
+ let mut et = inferExprWith(&t.else_, env, ctx, expected)?;
518
+ // A branch of a narrower covariant type than the one expected is upcast to it
519
+ // (`if c then Cons(head: dot, tail: sqs) else sqs` where a `List<Shape>` is
520
+ // expected).
521
+ if let Some(exp) = expected {
522
+ if tryUpcast(exp, &tt, &t.then) {
523
+ tt = exp.clone();
524
+ }
525
+ if tryUpcast(exp, &et, &t.else_) {
526
+ et = exp.clone();
527
+ }
528
+ }
518
529
  // A branch that is `crash "msg"` gives no value: the `if` has the other branch's type.
519
530
  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(_))));
520
531
  match (crashes(&t.then), crashes(&t.else_)) {
compiler/checker/tests/checker/diagnostic_tests.rs CHANGED
@@ -355,3 +355,24 @@ fn fieldDefaultsThatConstructEachOtherAreAnError() {
355
355
  assert_eq!(es.len(), 1, "{es:?}");
356
356
  assert!(es[0].message.contains("field defaults that construct each other: A -> B -> A"), "{es:?}");
357
357
  }
358
+
359
+ /// A construction's block is the value of its type's last field, which must be a `List` and
360
+ /// not also be given by name.
361
+ #[test]
362
+ fn aBlockNeedsALastListField() {
363
+ let es = frontErrors("struct P(x: Int, n: Int)\n\nprimitive Main[App] =\n fun main() -> Int = P(x: 1) {\n 2\n }.x\n");
364
+ assert_eq!(es.len(), 1, "{es:?}");
365
+ assert_eq!((es[0].file.as_str(), es[0].line, es[0].column), ("main.plum", 4, 23), "{es:?}");
366
+ assert!(es[0].message.contains("the last field, `n`, which is a `Int`, not a `List`"), "{es:?}");
367
+ let es = frontErrors("struct P(x: Int, xs: List<Int>)\n\nprimitive Main[App] =\n fun main() -> Int = P(x: 1, xs: [1]) { 2 }.x\n");
368
+ assert!(es[0].message.contains("gives field 'xs' twice: by name and as its block"), "{es:?}");
369
+ let es = frontErrors("primitive Main[App] =\n fun main() -> Int = Unknown(x: 1) { 2 }.x\n");
370
+ assert!(es[0].message.contains("a block follows `Unknown(..)`, which has no named fields"), "{es:?}");
371
+ }
372
+
373
+ /// The block's `{` is on the line of the call's `)`: on the next line it is a grouping.
374
+ #[test]
375
+ fn aBlockOpensOnTheCallsLine() {
376
+ let es = errors("struct P(x: Int, xs: List<Int>)\n\nprimitive Main[App] =\n fun main() -> Int =\n p := P(x: 1)\n { 2 }\n");
377
+ assert!(es.iter().any(|e| e.message.contains("missing field 'xs'")), "{es:?}");
378
+ }
compiler/core/src/children_block.rs ADDED
@@ -0,0 +1,97 @@
1
+ //! A call's trailing block: `Overlay(w: Arena.W, h: Arena.H) {` + one item a line + `}`.
2
+ //!
3
+ //! The block is a list literal (the same items: a value, `..xs`, `if c then x`; separated by
4
+ //! line breaks or commas), lowered by the parser like one. It is the call's last argument:
5
+ //! after the others on a function or method call (`xs.each(1) { .. }` is `xs.each(1, [..])`),
6
+ //! and on a construction the value of the type's last field, which must be a `List`
7
+ //! (`Overlay`'s `children`). The parser cannot see the type's fields, so it writes the block
8
+ //! as a field named [`BLOCK_FIELD`]; [`nameBlockFields`] gives it the last field's name,
9
+ //! before field defaults are filled.
10
+
11
+ use std::collections::HashMap;
12
+
13
+ use crate::ast::*;
14
+ use crate::diag::{DiagKind, Diagnostic};
15
+ use crate::forms::{mapExprs, mapExprsIn};
16
+
17
+ /// The name the parser gives a construction's block until [`nameBlockFields`] names it.
18
+ pub const BLOCK_FIELD: &str = "{block}";
19
+
20
+ /// Names each construction's block after the last field of its type; see the module doc.
21
+ /// Errors: a type with no named fields, a last field that is not a `List`, or a last field
22
+ /// also given by name.
23
+ pub fn nameBlockFields(source: &mut Source) -> Vec<Diagnostic> {
24
+ let mut last: HashMap<String, (String, Type)> = HashMap::new();
25
+ for item in &source.items {
26
+ if let Item::Enum(e) = item {
27
+ for v in &e.variants {
28
+ if let (Some(n), Some(t)) = (v.field_names.last(), v.fields.last()) {
29
+ last.insert(v.name.clone(), (n.clone(), t.clone()));
30
+ }
31
+ }
32
+ }
33
+ }
34
+ let mut errors: Vec<Diagnostic> = Vec::new();
35
+ for item in &mut source.items {
36
+ match item {
37
+ Item::Fn(f) => {
38
+ let file = f.file.clone();
39
+ let mut name = |e: &mut Expr| nameBlock(e, &last, &file, &mut errors);
40
+ for p in &mut f.params {
41
+ if let Some(d) = &mut p.default {
42
+ mapExprsIn(d, &mut name);
43
+ }
44
+ }
45
+ mapExprs(&mut f.body, &mut name);
46
+ }
47
+ Item::Const(c) => mapExprsIn(&mut c.value, &mut |e| nameBlock(e, &last, "", &mut errors)),
48
+ Item::Trait(t) => {
49
+ for m in &mut t.methods {
50
+ for p in &mut m.sig.params {
51
+ if let Some(d) = &mut p.default {
52
+ mapExprsIn(d, &mut |e| nameBlock(e, &last, "", &mut errors));
53
+ }
54
+ }
55
+ }
56
+ }
57
+ Item::Enum(en) => {
58
+ let file = en.file.clone();
59
+ for v in &mut en.variants {
60
+ for d in v.field_defaults.iter_mut().flatten() {
61
+ mapExprsIn(d, &mut |e| nameBlock(e, &last, &file, &mut errors));
62
+ }
63
+ }
64
+ }
65
+ }
66
+ }
67
+ errors
68
+ }
69
+
70
+ fn nameBlock(e: &mut Expr, last: &HashMap<String, (String, Type)>, file: &str, errors: &mut Vec<Diagnostic>) {
71
+ let span = e.span;
72
+ let ExprKind::ClassCall(c) = &mut e.kind else { return };
73
+ let Some(at) = c.fields.iter().position(|f| f.name == BLOCK_FIELD) else { return };
74
+ let ty = &c.type_name;
75
+ let message = match last.get(ty) {
76
+ None => format!("a block follows `{ty}(..)`, which has no named fields: a construction's block is the value of its last field, a `List`"),
77
+ Some((field, t)) if t.name != "List" => {
78
+ format!("a block follows `{ty}(..)`: it is the value of the last field, `{field}`, which is a `{}`, not a `List`", show(t))
79
+ }
80
+ Some((field, _)) if c.fields.iter().any(|f| &f.name == field) => {
81
+ format!("`{ty}(..)` gives field '{field}' twice: by name and as its block")
82
+ }
83
+ Some((field, _)) => {
84
+ c.fields[at].name = field.clone();
85
+ return;
86
+ }
87
+ };
88
+ errors.push(Diagnostic::new(DiagKind::Type, file.to_string(), span.startLine, span.startColumn, message));
89
+ }
90
+
91
+ fn show(t: &Type) -> String {
92
+ if t.generics.is_empty() {
93
+ t.name.clone()
94
+ } else {
95
+ format!("{}<{}>", t.name, t.generics.iter().map(show).collect::<Vec<_>>().join(", "))
96
+ }
97
+ }
compiler/core/src/lib.rs CHANGED
@@ -5,6 +5,7 @@
5
5
  pub mod ast;
6
6
  pub mod binders;
7
7
  pub mod blocks;
8
+ pub mod children_block;
8
9
  pub mod builtin_usage;
9
10
  pub mod closure_escape;
10
11
  pub mod closure_spec;
compiler/core/src/lower.rs CHANGED
@@ -30,6 +30,10 @@ pub fn frontEndDiag(source: &mut Source) -> Result<(), Vec<Diagnostic>> {
30
30
  if !nativeErrors.is_empty() {
31
31
  return Err(nativeErrors);
32
32
  }
33
+ let blockFieldErrors = crate::children_block::nameBlockFields(source);
34
+ if !blockFieldErrors.is_empty() {
35
+ return Err(blockFieldErrors);
36
+ }
33
37
  let defaultErrors = crate::field_defaults::fillFieldDefaults(source);
34
38
  if !defaultErrors.is_empty() {
35
39
  return Err(defaultErrors);
compiler/core/src/parser.rs CHANGED
@@ -1372,14 +1372,44 @@ impl<'a> AstParser<'a> {
1372
1372
  column: pos.column + 1,
1373
1373
  }))
1374
1374
  }
1375
+ "fn_call" => {
1375
- "fn_call" => Expr::FnCall(self.parseFnCall(node)),
1376
+ let mut call = self.parseFnCall(node);
1377
+ match self.trailingBlock(node) {
1378
+ None => Expr::FnCall(call),
1379
+ // `Group() { .. }`: a construction, whose block is its last field.
1380
+ Some(block) if call.name.starts_with(|c: char| c.is_ascii_uppercase()) => {
1381
+ if !call.args.is_empty() {
1382
+ self.removed(node, "a block follows a construction with named fields: `Type(a: x) { .. }`");
1383
+ }
1384
+ Expr::ClassCall(ClassCall {
1385
+ type_name: call.name,
1386
+ fields: vec![FieldArg { name: crate::children_block::BLOCK_FIELD.to_string(), value: block }],
1387
+ generics: call.type_args,
1388
+ spread: None,
1389
+ unique: false,
1390
+ reuse: None,
1391
+ reboxed: vec![],
1392
+ })
1393
+ }
1394
+ Some(block) => {
1395
+ call.args.push(Arg::Positional(block));
1396
+ Expr::FnCall(call)
1397
+ }
1398
+ }
1399
+ }
1376
1400
  "builtin_call" => self.parseBuiltinCall(node),
1377
1401
  // Anywhere but as a function's whole body (`parseFn` takes that one).
1378
1402
  "native" => {
1379
1403
  self.removed(node, "`@native` is only valid as a function's whole body (`fun f(..) = @native`): it says the compiler supplies the body");
1380
1404
  Expr::Int(0)
1381
1405
  }
1406
+ "class_call" => {
1382
- "class_call" => Expr::ClassCall(self.parseClassCall(node)),
1407
+ let mut call = self.parseClassCall(node);
1408
+ if let Some(block) = self.trailingBlock(node) {
1409
+ call.fields.push(FieldArg { name: crate::children_block::BLOCK_FIELD.to_string(), value: block });
1410
+ }
1411
+ Expr::ClassCall(call)
1412
+ }
1383
1413
  "list_literal" => self.parseListLiteral(node),
1384
1414
  "parenthesized_expression" => {
1385
1415
  // parenthesized_expression: "{" expression "}" — grouping only, no AST node
@@ -1577,10 +1607,11 @@ impl<'a> AstParser<'a> {
1577
1607
  let attr = match node.child_by_field_name("arguments") {
1578
1608
  Some(args_node) => {
1579
1609
  let mut acursor = args_node.walk();
1580
- let args = args_node
1610
+ let mut args: Vec<Arg> = args_node
1581
1611
  .named_children(&mut acursor)
1582
1612
  .map(|n| self.parseArg(n))
1583
1613
  .collect();
1614
+ args.extend(self.trailingBlock(node).map(Arg::Positional));
1584
1615
  AttrKind::Method(FnCall {
1585
1616
  name: member,
1586
1617
  args,
@@ -1602,7 +1633,14 @@ impl<'a> AstParser<'a> {
1602
1633
  Expr::Attribute(Box::new(AttributeExpr { object, attr }))
1603
1634
  }
1604
1635
 
1636
+ /// A call's trailing block (`children_block`, `{` + items + `}`), as the list it builds; see
1637
+ /// `children_block`.
1638
+ fn trailingBlock(&self, node: Node) -> Option<Expr> {
1639
+ node.child_by_field_name("block").map(|b| self.parseListLiteral(b))
1640
+ }
1641
+
1605
1642
  /// list_literal: "[" (expression | pair_argument | spread_argument | list_if),* "]"
1643
+ /// (items separated by commas or line breaks)
1606
1644
  ///
1607
1645
  /// Pure sugar: `[a, b]` is `Cons(head: a, tail: Cons(head: b, tail: Nil))`
1608
1646
  /// (std's `List`), `[]` is `Nil`, spreads and `if` items are lowered by `list_items`, and `[k => v, ..]` is
compiler/core/tests/core/formatter_test.rs CHANGED
@@ -369,3 +369,14 @@ fn fieldDefaultsFormatIdempotently() {
369
369
  let twice = formatSource(&once).expect("second pass");
370
370
  assert_eq!(once, twice);
371
371
  }
372
+
373
+ /// A call's block and a list literal written across lines keep one item a line (their items
374
+ /// may be separated by line breaks alone); written on one line they stay on it.
375
+ #[test]
376
+ fn blocksAndListLinesFormat() {
377
+ let input = "primitive Main =\n fun view(self) -> List<View> = [\n Box(x: 0.0)\n ..self.mines,\n if self.over then Overlay(w: 1.0, h: 2.0) {\n Label(text: \"a\")\n Label(text: \"b\")\n }\n ]\n\n fun one() -> List<Int> = [1, 2, ..xs]\n\n fun two() -> Panel = Panel(w: 1){ 1, 2 }\n\n fun three() -> Panel = Panel() {}\n";
378
+ let once = formatSource(input).expect("first pass");
379
+ let expected = "primitive Main =\n fun view(self) -> List<View> = [\n Box(x: 0.0)\n ..self.mines,\n if self.over then Overlay(w: 1.0, h: 2.0) {\n Label(text: \"a\")\n Label(text: \"b\")\n }\n ]\n\n fun one() -> List<Int> = [1, 2, ..xs]\n\n fun two() -> Panel = Panel(w: 1) { 1, 2 }\n\n fun three() -> Panel = Panel() {}\n";
380
+ assert_eq!(once, expected);
381
+ assertFormatsUnchanged(expected);
382
+ }
compiler/tooling/tree-sitter-plum/grammar.js CHANGED
@@ -73,6 +73,9 @@ module.exports = grammar({
73
73
  // Listed so that the scanner can see whether a comparison may go here. It never
74
74
  // returns this one: the `<` operator is lexed as usual.
75
75
  '<',
76
+ // The `{` of a call's trailing block (`Overlay(w: 1.0, h: 1.0) {`): only on the line of
77
+ // the call's `)`, so a `{ x }` grouping that starts the next line stays one.
78
+ $._block_open,
76
79
  ],
77
80
  // Conflict arises at the empty-argument-list state (e.g. `Foo()`): the parser cannot
78
81
  // distinguish fn_argument_list from class_argument_list until it sees content or ')'.
@@ -683,6 +686,7 @@ module.exports = grammar({
683
686
  optional(seq(
684
687
  optional(field("generics", $.type_arguments)),
685
688
  field("arguments", $.fn_argument_list),
689
+ optional(field("block", $.children_block)),
686
690
  )),
687
691
  ),
688
692
  ),
@@ -718,6 +722,7 @@ module.exports = grammar({
718
722
  "arguments",
719
723
  $.fn_argument_list,
720
724
  ),
725
+ optional(field("block", $.children_block)),
721
726
  )),
722
727
 
723
728
  // `Box<Int>` before a `.`: `Box<Int>.make()`. A static call takes no type arguments
@@ -746,15 +751,23 @@ module.exports = grammar({
746
751
  // List literal: `[1, 2, 3]`, `[]`, `["a" => 1]` (pair elements). Only at
747
752
  // expression start. An item may be a spread (`..xs`: every element of a list,
748
753
  // or the value of an `Option`) or a `list_if` (`if c then x`: added only when
754
+ // `c` holds). Items are separated by commas or by line breaks (one item a line).
755
+ list_literal: ($) => seq("[", optional($._newline), optional($._list_items), "]"),
756
+
757
+ // A call's trailing block, `Overlay(w: 1.0, h: 1.0) {` + items + `}`: a list literal
758
+ // (the same items and separators) that is the call's last argument, or the value of
759
+ // the constructed type's last field. Its `{` is on the line of the call's `)`.
749
- // `c` holds).
760
+ children_block: ($) =>
761
+ seq(alias($._block_open, "{"), optional($._newline), optional($._list_items), "}"),
762
+
750
- list_literal: ($) =>
763
+ _list_items: ($) =>
751
764
  seq(
752
- "[",
753
- optional(commaSep1(choice($.expression, $.pair_argument, $.spread_argument, $.list_if))),
765
+ sep1(choice($.expression, $.pair_argument, $.spread_argument, $.list_if), $._item_separator),
754
- optional(","),
766
+ optional($._item_separator),
755
- "]",
756
767
  ),
757
768
 
769
+ _item_separator: ($) => choice(",", $._newline, seq(",", $._newline)),
770
+
758
771
  // `if c then x` in a list literal: `x` is an item only when `c` holds. With an
759
772
  // `else` it is an `inline_if_expression`, one item either way.
760
773
  list_if: ($) =>
@@ -780,6 +793,7 @@ module.exports = grammar({
780
793
  "arguments",
781
794
  $.class_argument_list,
782
795
  ),
796
+ optional(field("block", $.children_block)),
783
797
  )),
784
798
 
785
799
  class_argument_list: ($) =>
compiler/tooling/tree-sitter-plum/queries/plum/format.scm CHANGED
@@ -422,3 +422,33 @@
422
422
  "mut" @append_space
423
423
 
424
424
  (fn "export" @append_space)
425
+
426
+ ; ============================================================
427
+ ; List literals and call blocks — written across lines, one item a line between
428
+ ; the brackets (items may be separated by line breaks alone, so they must stay
429
+ ; on their own lines); written on one line, they stay on it.
430
+ ; ============================================================
431
+
432
+ (list_literal
433
+ "[" @append_empty_softline @append_indent_start)
434
+
435
+ (list_literal
436
+ "]" @prepend_empty_softline @prepend_indent_end)
437
+
438
+ (list_literal
439
+ (_) . (_) @prepend_spaced_softline)
440
+
441
+ (children_block
442
+ "{" @prepend_space @append_indent_start)
443
+
444
+ (children_block
445
+ "}" @prepend_indent_end)
446
+
447
+ (children_block
448
+ "{" @append_spaced_softline . (_))
449
+
450
+ (children_block
451
+ (_) . "}" @prepend_spaced_softline)
452
+
453
+ (children_block
454
+ (_) . (_) @prepend_spaced_softline)
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/src/scanner.c CHANGED
@@ -21,6 +21,7 @@ enum TokenType {
21
21
  ARM_BREAK,
22
22
  TARGS_OPEN,
23
23
  LESS_THAN,
24
+ BLOCK_OPEN,
24
25
  };
25
26
 
26
27
  static inline bool is_ident_start(int32_t c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_'; }
@@ -297,6 +298,20 @@ bool tree_sitter_plum_external_scanner_scan(void *payload, TSLexer *lexer, const
297
298
  }
298
299
  }
299
300
 
301
+ // A call's trailing block opens with a `{` on the line of the call's `)`: spaces and
302
+ // tabs only between them. A `{` on a later line is a grouping (or the next statement).
303
+ if (valid_symbols[BLOCK_OPEN] && !error_recovery_mode) {
304
+ while (lexer->lookahead == ' ' || lexer->lookahead == '\t') {
305
+ skip(lexer);
306
+ }
307
+ if (lexer->lookahead == '{') {
308
+ advance(lexer);
309
+ lexer->mark_end(lexer);
310
+ lexer->result_symbol = BLOCK_OPEN;
311
+ return true;
312
+ }
313
+ }
314
+
300
315
  lexer->mark_end(lexer);
301
316
 
302
317
  bool found_end_of_line = false;
compiler/tooling/tree-sitter-plum/test/corpus/list_literal.txt CHANGED
@@ -145,3 +145,120 @@ primitive Main =
145
145
  (expression
146
146
  (primary_expression
147
147
  (var_identifier)))))))))))
148
+
149
+ ==================
150
+ call blocks and list items on lines
151
+ ==================
152
+
153
+ primitive Main =
154
+ fun f(c: Bool) -> Panel = Panel(w: 1) {
155
+ Dot(r: 1)
156
+ ..xs
157
+ if c then g(2) { 3, 4 }
158
+ }
159
+
160
+ fun h() -> List<Int> = [
161
+ 1
162
+ 2,
163
+ 3
164
+ ]
165
+
166
+ fun k() =
167
+ p := Panel()
168
+ { a }.b()
169
+
170
+ ---
171
+
172
+ (source
173
+ (primitive
174
+ (type_identifier)
175
+ (fn
176
+ (fn_identifier)
177
+ (param
178
+ (var_identifier)
179
+ (type
180
+ (type_identifier)))
181
+ (type
182
+ (type_identifier))
183
+ (expression
184
+ (primary_expression
185
+ (class_call
186
+ (type_identifier)
187
+ (class_argument_list
188
+ (field_argument
189
+ (var_identifier)
190
+ (expression
191
+ (primary_expression
192
+ (integer)))))
193
+ (children_block
194
+ (expression
195
+ (primary_expression
196
+ (class_call
197
+ (type_identifier)
198
+ (class_argument_list
199
+ (field_argument
200
+ (var_identifier)
201
+ (expression
202
+ (primary_expression
203
+ (integer))))))))
204
+ (spread_argument
205
+ (expression
206
+ (primary_expression
207
+ (var_identifier))))
208
+ (list_if
209
+ (expression
210
+ (primary_expression
211
+ (var_identifier)))
212
+ (expression
213
+ (primary_expression
214
+ (fn_call
215
+ (var_identifier)
216
+ (fn_argument_list
217
+ (expression
218
+ (primary_expression
219
+ (integer))))
220
+ (children_block
221
+ (expression
222
+ (primary_expression
223
+ (integer)))
224
+ (expression
225
+ (primary_expression
226
+ (integer)))))))))))))
227
+ (fn
228
+ (fn_identifier)
229
+ (type
230
+ (type_identifier)
231
+ (type
232
+ (type_identifier)))
233
+ (expression
234
+ (primary_expression
235
+ (list_literal
236
+ (expression
237
+ (primary_expression
238
+ (integer)))
239
+ (expression
240
+ (primary_expression
241
+ (integer)))
242
+ (expression
243
+ (primary_expression
244
+ (integer)))))))
245
+ (fn
246
+ (fn_identifier)
247
+ (body
248
+ (assign
249
+ (var_identifier)
250
+ (expression
251
+ (primary_expression
252
+ (class_call
253
+ (type_identifier)
254
+ (class_argument_list)))))
255
+ (expression
256
+ (primary_expression
257
+ (attribute
258
+ (primary_expression
259
+ (parenthesized_expression
260
+ (expression
261
+ (primary_expression
262
+ (var_identifier)))))
263
+ (fn_identifier)
264
+ (fn_argument_list))))))))
docs/language.md CHANGED
@@ -435,6 +435,39 @@ primitive Demo[App] =
435
435
 
436
436
  Items run left to right, as written, and the list is built once, from its last item back: a value is one new cell, a spread copies the cells of what it spreads (a spread that ends the literal is shared, not copied), and nothing is appended to a list already built. Spreads are covariant like any `List`: `..self.orbs`, a `List<Orb>`, goes into a `List<View>`.
437
437
 
438
+ **Items on lines:** a list literal written across lines may put one item on each line and leave out the commas. An item then ends with its line (break a long item inside its brackets), and commas are still allowed:
439
+
440
+ ```plum
441
+ xs := [
442
+ 1
443
+ ..rest
444
+ if big then 100
445
+ ]
446
+ ```
447
+
448
+ **Blocks:** a call or a construction can take its last argument as a block, `{` on the line of its `)`, then the items, one a line (or with commas), then `}`. The block is a list literal with the same items: values, spreads and `if` items. On a function or method call it is the last argument, after the others (`Demo.sum(1) { 2, 3 }` is `Demo.sum(1, [2, 3])`); on a construction it is the value of the type's last field, which must be a `List` (`Panel`'s `children` below) and can't also be given by name. `Type() { .. }` is a construction too:
449
+
450
+ ```plum
451
+ import std/Int
452
+ import std/Bool
453
+ import std/collections/List
454
+ import std/App
455
+
456
+ struct Panel(w: Int = 1, children: List<Int>) =
457
+ fun total(self) -> Int = self.children.fold(self.w, |n, x| n + x)
458
+
459
+ primitive Demo[App] =
460
+ fun main() -> Int =
461
+ big := true
462
+ Panel(w: 10) {
463
+ 1
464
+ 2
465
+ if big then 100
466
+ }.total() # 113
467
+ ```
468
+
469
+ A block is what a tree of views is made of: a parent's children are its block, so a view reads as the tree it draws (see [the game guide](game.md)). The `{` must be on the call's line: a `{` that starts the next line is a grouping, as before.
470
+
438
471
  An empty list `[]` needs its type where it is written: an annotation (`xs: List<Int> := []`), the parameter, field or return type it is given to, a sibling element (`[[], [1]]`), or the rest of its own statement (`xs.fold([], |acc, x| Cons(head: x, tail: acc))`). A later statement doesn't type it: `e := []` alone is an error at the `[]`.
439
472
 
440
473
  A `Map` is persistent, like a `List`: `m.with(k, v)` and `m.remove(k)` return a new map that shares most of its nodes with `m`, and `m` stays as it was. A map literal `[k => v, ..]` is `Map.empty().with(k, v)...`, so a later duplicate key wins. Keys are kept in order by their `compare` method, which `Int`, `Float`, `Str`, `Bool` and `Byte` have and a struct can define, and every walk goes in key order. See [the standard library](std.md#collections).
tests/syntax/children_blocks.plum ADDED
@@ -0,0 +1,168 @@
1
+ import std/Int
2
+ import std/Bool
3
+ import std/Str
4
+ import std/Test
5
+ import std/Option
6
+ import std/collections/List
7
+
8
+ # A call's trailing block: `Panel(w: 3) {` + one item a line + `}`. The items are a list
9
+ # literal's (a value, `..xs`, `if c then x`), separated by line breaks or commas. On a
10
+ # construction the block is the value of the type's last field, a `List`; on a function or
11
+ # method call it is the last argument. A list literal may break its items over lines without
12
+ # commas too.
13
+
14
+ trait Shape =
15
+ fun area(self) -> Int
16
+
17
+ struct Sq[Shape](k: Int) =
18
+ fun area(self) -> Int = self.k * self.k
19
+
20
+ struct Dot[Shape](r: Int) =
21
+ fun area(self) -> Int = self.r
22
+
23
+ struct Panel[Shape](w: Int = 1, label: Str = "panel", children: List<Shape>) =
24
+ fun area(self) -> Int = self.w + self.children.fold(0, |acc, c| acc + c.area())
25
+
26
+ struct Names(first: Str, rest: List<Str>)
27
+
28
+ struct Log(mut seen: List<Int>) =
29
+ fun note(self, n: Int) -> Int =
30
+ self.seen = Cons(head: n, tail: self.seen)
31
+ n
32
+
33
+ fun add(self, n: Int) =
34
+ self.seen = Cons(head: n, tail: self.seen)
35
+
36
+ fun order(self) -> List<Int> = self.seen.reverse()
37
+
38
+ fun sum(self, k: Int, xs: List<Int>) -> Int = xs.fold(k, |a, x| a + x)
39
+
40
+ primitive Blocks =
41
+ fun total(xs: List<Shape>) -> Int = xs.fold(0, |acc, x| acc + x.area())
42
+
43
+ fun count(xs: List<Int>) -> Int = xs.length()
44
+
45
+ fun scaled(by: Int, xs: List<Int>) -> List<Int> = xs.map(|x| x * by)
46
+
47
+ fun scene(sqs: List<Sq>, over: Bool, dot: Option<Dot>) -> List<Shape> = [
48
+ Dot(r: 1)
49
+ ..sqs
50
+ ..dot
51
+ if over then Panel(w: 10) {
52
+ Sq(k: 2)
53
+ Dot(r: 3)
54
+ }
55
+ ]
56
+
57
+ primitive ChildrenBlocksTest[UnitTest] =
58
+ fun construction() =
59
+ p := Panel(w: 3) {
60
+ Sq(k: 2)
61
+ Dot(r: 5)
62
+ }
63
+ assert p.children.length() == 2
64
+ assert p.area() == 3 + 4 + 5
65
+ assert p.label == "panel"
66
+
67
+ fun allDefaults() =
68
+ p := Panel() {
69
+ Dot(r: 7)
70
+ }
71
+ assert p.w == 1
72
+ assert p.area() == 8
73
+ q := Panel(label: "q") { Dot(r: 1), Dot(r: 2) }
74
+ assert q.label == "q"
75
+ assert q.area() == 4
76
+
77
+ fun emptyBlocks() =
78
+ p := Panel(w: 2) {}
79
+ assert p.children.isEmpty()
80
+ q := Panel() {
81
+ }
82
+ assert q.area() == 1
83
+
84
+ fun nested() =
85
+ p := Panel(w: 1) {
86
+ Panel(w: 10) {
87
+ Panel(w: 100) {
88
+ Sq(k: 3)
89
+ }
90
+ }
91
+ Dot(r: 1000)
92
+ }
93
+ assert p.area() == 1 + 10 + 100 + 9 + 1000
94
+
95
+ fun itemForms() =
96
+ sqs := [Sq(k: 2), Sq(k: 3)]
97
+ yes := true
98
+ no := false
99
+ o := Some(Dot(r: 4))
100
+ p := Panel(w: 0) {
101
+ ..sqs
102
+ if yes then Dot(r: 10)
103
+ if no then Dot(r: 1000)
104
+ if yes then ..sqs
105
+ ..o
106
+ if Some(d) := o then Dot(r: d.r * 100)
107
+ }
108
+ assert p.area() == 4 + 9 + 10 + 4 + 9 + 4 + 400
109
+
110
+ fun plainElements() =
111
+ n := Names(first: "a") {
112
+ "b"
113
+ "c"
114
+ }
115
+ assert n.rest == ["b", "c"]
116
+
117
+ fun callsTakeTheBlockLast() =
118
+ assert Blocks.count() {
119
+ 1
120
+ 2
121
+ 3
122
+ } == 3
123
+ assert Blocks.scaled(10) { 1, 2 } == [10, 20]
124
+ log := Log(seen: Nil)
125
+ assert log.sum(100) {
126
+ 1
127
+ 2
128
+ } == 103
129
+
130
+ fun itemsRunInOrder() =
131
+ log := Log(seen: Nil)
132
+ xs := Blocks.scaled(1) {
133
+ log.note(1)
134
+ if log.note(2) > 0 then log.note(3)
135
+ log.note(4)
136
+ }
137
+ assert xs == [1, 3, 4]
138
+ assert log.order() == [1, 2, 3, 4]
139
+
140
+ fun listLiteralLines() =
141
+ xs := [
142
+ 1
143
+ 2,
144
+ 3
145
+ ]
146
+ assert xs == [1, 2, 3]
147
+ ys := [
148
+ ..xs
149
+ if xs.length() > 2 then 4
150
+ ]
151
+ assert ys == [1, 2, 3, 4]
152
+
153
+ fun covariantChildren() =
154
+ sqs := [Sq(k: 2), Sq(k: 3)]
155
+ assert Blocks.total(Blocks.scene(sqs, false, None)) == 14
156
+ assert Blocks.total(Blocks.scene(sqs, true, Some(Dot(r: 5)))) == 14 + 5 + 10 + 4 + 3
157
+
158
+ fun spreadConstruction() =
159
+ p := Panel(w: 5) { Dot(r: 1) }
160
+ q := Panel(..p) { Dot(r: 2), Dot(r: 3) }
161
+ assert q.w == 5
162
+ assert q.area() == 10
163
+
164
+ fun groupingOnTheNextLine() =
165
+ log := Log(seen: Nil)
166
+ k := Blocks.count([1])
167
+ { log }.add(k)
168
+ assert log.order() == [1]