plum

#treesitter#compiler#wasm

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

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


b702f26 — Peter John 2026-11-10T16:07:30+05:30
Checker: clearer errors, == on Option and Result, toStr in strings
compiler/checker/src/declchecks.rs CHANGED
@@ -367,6 +367,29 @@ pub(crate) fn firstDuplicate<'a>(names: impl IntoIterator<Item = &'a str>) -> Op
367
367
  /// fields or generics. The later one would silently win (or both would be compiled).
368
368
  pub(crate) fn checkDuplicateNames(source: &ast::Source) -> Vec<CheckError> {
369
369
  let mut errors = Vec::new();
370
+ // A variant is named on its own (`Red`, not `Color.Red`), so one name is one variant.
371
+ // Two files may each have a `Red` (`plum_core::modules` keeps them apart: a file's own
372
+ // wins in it); two enums of one file can't.
373
+ let mut variantOwner: HashMap<&str, &str> = HashMap::new();
374
+ for item in &source.items {
375
+ let ast::Item::Enum(e) = item else { continue };
376
+ for v in &e.variants {
377
+ match variantOwner.get(v.name.as_str()) {
378
+ Some(first) if *first != e.name => errors.push(CheckError::at(
379
+ e.line,
380
+ e.column,
381
+ format!(
382
+ "{}: variant '{}' is also a variant of {}: a variant is written on its own (`{}`), so two types in one file can't share a variant name",
383
+ e.name, v.name, first, v.name
384
+ ),
385
+ )),
386
+ Some(_) => {}
387
+ None => {
388
+ variantOwner.insert(&v.name, &e.name);
389
+ }
390
+ }
391
+ }
392
+ }
370
393
  for item in &source.items {
371
394
  match item {
372
395
  ast::Item::Fn(f) => {
compiler/checker/src/infer.rs CHANGED
@@ -119,9 +119,22 @@ pub(crate) fn inferExprInner(
119
119
  ast::Expr { kind: ast::ExprKind::String(s), .. } => {
120
120
  // Interpolated parts are typed and recorded; an error in one is the
121
121
  // string's error (positioned at the failing node inside the part).
122
+ // An assert's report shows its operands only when they can be shown.
123
+ let report = matches!(s.parts.first(), Some(ast::StringPart::Text(m)) if m == plum_core::tests_lower::ASSERT_REPORT_MARK);
122
124
  for part in &s.parts {
123
125
  if let ast::StringPart::Interp(e) = part {
124
126
  let ity = inferExprWith(e, env, ctx, None)?;
127
+ // A part is shown by its type's `toStr` (`Int`, `Float`, `Bool` and `Str` are built in).
128
+ let shown = resolveRecorded(&ity);
129
+ let isStr = matches!(&shown, PlumType::TNamed(n) if n == ast::STR_TYPE);
130
+ if !report && !isStr && matches!(shown, PlumType::TNamed(_) | PlumType::TApp(..)) {
131
+ let owner = methodReceiverName(&shown).unwrap_or_default();
132
+ if !ctx.methods.contains_key(&(owner, "toStr".to_string())) {
133
+ return Err(blame(e, format!(
134
+ "{shown} has no method 'toStr', so it can't be put in a string: give it `fun toStr(self) -> Str`"
135
+ )));
136
+ }
137
+ }
125
138
  if let PlumType::TApp(n, targs) = ity {
126
139
  let gens = enumGenericsOf(&n, ctx);
127
140
  if gens.len() == targs.len()
@@ -140,6 +153,32 @@ pub(crate) fn inferExprInner(
140
153
  }
141
154
  Ok(types::strType())
142
155
  }
156
+ // A top-level fn named as a value (`f := id`, `apply(rawNow, 1)`) is made a closure
157
+ // by codegen, which it can't do for a host call or for a fn with no one type.
158
+ // (A parameter or a closure parameter of that name is a value like any other: an
159
+ // extern's own entry takes `io: Io` first, and a generic fn's is the only scheme.)
160
+ ast::Expr { kind: ast::ExprKind::Var(name), .. }
161
+ if env.contains_key(&format!("{}{}", GLOBAL_KEY, name))
162
+ && withCheck(|s| s.extern_fns.borrow().contains(name.as_str()))
163
+ && env.get(name).is_some_and(|s| {
164
+ matches!(&*s.body, PlumType::TFun(ps, _) if matches!(ps.first(), Some(PlumType::TNamed(n)) if n == ast::IO_TYPE))
165
+ }) =>
166
+ {
167
+ let shown = plum_core::diag::sourceName(name);
168
+ Err(blame(expr, format!(
169
+ "extern function '{shown}' can't be used as a value: it is a host call, not a Plum function; wrap it in a closure, e.g. `|io| {shown}(io)`"
170
+ )))
171
+ }
172
+ ast::Expr { kind: ast::ExprKind::Var(name), .. }
173
+ if env.contains_key(&format!("{}{}", GLOBAL_KEY, name))
174
+ && env.get(name).is_some_and(|s| !s.vars.is_empty())
175
+ && withCheck(|s| s.fn_generics.borrow().get(&(None, name.clone())).is_some_and(|g| !g.is_empty())) =>
176
+ {
177
+ let shown = plum_core::diag::sourceName(name);
178
+ Err(blame(expr, format!(
179
+ "generic function '{shown}' can't be used as a value: its type is only known where it is called; wrap it in a closure, e.g. `|x| {shown}(x)`"
180
+ )))
181
+ }
143
182
  ast::Expr { kind: ast::ExprKind::Var(name), .. } => match env.get(name) {
144
183
  Some(s) if !s.vars.is_empty() => Ok(instSig(&s.body, &BTreeMap::new())),
145
184
  _ => lookup(env, name).map_err(|e| {
@@ -408,14 +447,6 @@ pub(crate) fn inferExprInner(
408
447
  let lt = inferExpr(&c.left, env, ctx)?;
409
448
  let rt = inferExpr(&c.right, env, ctx)?;
410
449
  if matches!(c.op, ast::CmpOp::Eq | ast::CmpOp::Neq | ast::CmpOp::NotEq2) {
411
- for side in [&lt, &rt] {
412
- if optionResultSuccess(&resolveRecorded(side)).is_some() {
413
- return Err(format!(
414
- "can't compare {} with ==: use match, isSome or unwrapOr",
415
- side
416
- ));
417
- }
418
- }
419
450
  if matches!(lt, PlumType::TFun(..)) || matches!(rt, PlumType::TFun(..)) {
420
451
  return Err("can't compare functions with ==".to_string());
421
452
  }
@@ -482,6 +513,22 @@ pub(crate) fn inferExprInner(
482
513
  if let Some(e) = plum_core::compile_builtins::error(call) {
483
514
  return Err(e);
484
515
  }
516
+ // A value built-in given a type: `@sameRef(x, Int)`. A bare capitalised name is a
517
+ // value only when it is a constant or a variant.
518
+ if let Some(bare) = call.name.strip_prefix('@') {
519
+ for a in &call.args {
520
+ let ast::Expr { kind: ast::ExprKind::TypeName(n), .. } = plum_core::visit::argRef(a) else { continue };
521
+ let isValue = match ctx.enum_variants.get(n) {
522
+ // A struct's or a payload variant's name alone builds nothing.
523
+ Some(info) => info.field_types.is_empty(),
524
+ None => typeParamBinding(n).is_none() && lookup(env, n).is_ok(),
525
+ };
526
+ if !isValue {
527
+ let eg = plum_core::compile_builtins::BUILTINS.iter().find(|b| b.0 == bare).map_or("", |b| b.2);
528
+ return Err(blame(plum_core::visit::argRef(a), format!("@{bare} takes values, and {n} is a type: pass a value, e.g. {eg}")));
529
+ }
530
+ }
531
+ }
485
532
  // `Int(x)`/`Float(x)`/`Byte(x)` are builtin numeric conversions, not
486
533
  // ordinary calls — handled here so `y = Float(x)` unifies against
487
534
  // `TFloat` rather than falling through to the permissive
compiler/checker/src/program.rs CHANGED
@@ -248,6 +248,16 @@ pub(crate) fn checkSourceInner(source: &ast::Source) -> (CheckResult<()>, TypedI
248
248
  })
249
249
  .collect()
250
250
  });
251
+ withCheck(|s| {
252
+ *s.extern_fns.borrow_mut() = source
253
+ .items
254
+ .iter()
255
+ .filter_map(|i| match i {
256
+ ast::Item::Fn(f) if f.is_extern && f.type_param.is_none() => Some(f.name.clone()),
257
+ _ => None,
258
+ })
259
+ .collect()
260
+ });
251
261
  errors.extend(checkTraitDecls(source, &traits, &methods));
252
262
  errors.extend(selfOutsideTrait(source));
253
263
  // Shared fields of subtyped traits; codegen fills them in (see `addTraitParams`).
compiler/checker/src/state.rs CHANGED
@@ -96,6 +96,8 @@ pub(crate) struct CheckState {
96
96
  /// Each fn's and method's own declared generics, in order ((owner, name) -> names), for
97
97
  /// a call's explicit type arguments (`findAs[Orb](..)`).
98
98
  pub(crate) fn_generics: RefCell<HashMap<(Option<String>, String), Vec<String>>>,
99
+ /// The module-level `extern fun`s: host calls, which are called and never held as values.
100
+ pub(crate) extern_fns: RefCell<std::collections::HashSet<String>>,
99
101
  /// Method calls on a value whose type was still an inference variable when the call was
100
102
  /// typed (`xs := []` then `xs.map(|x| x.length())`), by the receiver's node id: an error
101
103
  /// if nothing ever fixed that type (`checkSourceOnce`), as codegen would see `Unit`.
compiler/checker/tests/checker/features/clear_errors.rs ADDED
@@ -0,0 +1,87 @@
1
+ //! Errors that used to be vague or come from codegen: a value with no `toStr` in a string,
2
+ //! `==` on Option and Result, a variant two enums of one file share, and an extern or
3
+ //! generic function used as a value.
4
+ use plum_checker::checkSource;
5
+
6
+ const PRE: &str = "import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Option\nimport std/Result\nimport std/collections/List\nimport std/collections/Map\n\n";
7
+
8
+ /// The errors of `PRE` + `body`, as (line, column, message); lines count from `body`'s first.
9
+ fn errors(name: &str, body: &str) -> Vec<(usize, usize, String)> {
10
+ let source = plum_test_support::load(name, &format!("{PRE}{body}")).unwrap();
11
+ let skip = PRE.lines().count();
12
+ match checkSource(&source) {
13
+ Ok(_) => vec![],
14
+ Err(es) => es.into_iter().map(|e| (e.line.saturating_sub(skip), e.column, e.message)).collect(),
15
+ }
16
+ }
17
+
18
+ fn expect(name: &str, body: &str, at: (usize, usize), text: &str) {
19
+ let es = errors(name, body);
20
+ assert!(es.iter().any(|e| (e.0, e.1) == at && e.2.contains(text)), "{name}: no {text:?} at {at:?} in {es:?}");
21
+ }
22
+
23
+ #[test]
24
+ fn a_part_with_no_to_str_is_an_error_at_the_part() {
25
+ let text = "has no method 'toStr', so it can't be put in a string";
26
+ expect("ce_nostr", "struct P(x: Int)\n\nfun f() -> Str = \"p={P(x: 1)}\"\n", (3, 22), text);
27
+ expect("ce_nostr_opt", "fun f(o: Option[Int]) -> Str =\n \"{o}\"\n", (2, 5), "Option[Int] has no method 'toStr'");
28
+ }
29
+
30
+ #[test]
31
+ fn a_part_of_any_type_with_to_str_checks() {
32
+ let body = "struct P(x: Int) =\n fun toStr(self) -> Str = \"P\"\n\nfun show[T](x: T) -> Str = \"<{x}>\"\n\n\
33
+ fun f(m: Map[Str, Int], xs: List[List[Int]], p: P) -> Str =\n \"{m} {xs} {p} {1} {1.5} {true} {show(m)}\"\n";
34
+ let es = errors("ce_tostr", body);
35
+ assert!(es.is_empty(), "{es:?}");
36
+ }
37
+
38
+ #[test]
39
+ fn options_and_results_compare_by_value() {
40
+ let body = "fun f(a: Option[Int], r: Result[Str, Int]) -> Bool =\n a == Some(1) && a != None && r == Ok(\"x\") && r != Err(2) && Some([1]) == Some([1])\n";
41
+ let es = errors("ce_eq", body);
42
+ assert!(es.is_empty(), "{es:?}");
43
+ }
44
+
45
+ #[test]
46
+ fn comparing_options_of_functions_is_an_error() {
47
+ let es = errors("ce_eq_fn", "fun f() -> Bool =\n g := |x: Int| x\n Some(g) == Some(g)\n");
48
+ assert!(es.iter().any(|e| e.2.contains("can't compare functions with ==") && e.2.contains("Option.eq")), "{es:?}");
49
+ // The two sides are still one type.
50
+ let es = errors("ce_eq_mixed", "fun f(a: Option[Int], b: Option[Str]) -> Bool =\n a == b\n");
51
+ assert!(!es.is_empty(), "{es:?}");
52
+ }
53
+
54
+ #[test]
55
+ fn a_variant_of_two_enums_in_one_file_is_an_error_at_the_second() {
56
+ let text = "B: variant 'Red' is also a variant of A";
57
+ expect("ce_variant", "enum A = Red | Green\nenum B = Red | Blue\n\nfun f(a: A) -> Int = 1\n", (2, 1), text);
58
+ expect("ce_variant_payload", "enum A =\n | Hit(x: Int)\n | Miss\n\nenum B =\n | Hit(y: Str)\n", (5, 1), "B: variant 'Hit' is also a variant of A");
59
+ // Another file's variant of that name is not a clash: the file's own is meant.
60
+ let es = errors("ce_variant_std", "enum Mine = None | Lots\n\nfun f(m: Mine) -> Int = match m\n None => 0\n Lots => 1\n\nfun g() -> Int = f(None)\n");
61
+ assert!(es.is_empty(), "{es:?}");
62
+ }
63
+
64
+ #[test]
65
+ fn an_extern_function_as_a_value_is_an_error() {
66
+ let text = "extern function 'rawNow' can't be used as a value";
67
+ let pre = "extern fun rawNow(io: Io) -> Float\n\nfun apply(f: fn(Io) -> Float, io: Io) -> Float = f(io)\n\n";
68
+ expect("ce_extern_local", &format!("{pre}fun f(io: Io) -> Float =\n g := rawNow\n g(io)\n"), (6, 8), text);
69
+ expect("ce_extern_arg", &format!("{pre}fun f(io: Io) -> Float = apply(rawNow, io)\n"), (5, 32), text);
70
+ let es = errors("ce_extern_ok", &format!("{pre}fun f(io: Io) -> Float = apply(|i| rawNow(i), io) + rawNow(io)\n"));
71
+ assert!(es.is_empty(), "{es:?}");
72
+ }
73
+
74
+ #[test]
75
+ fn a_generic_function_as_a_value_is_an_error() {
76
+ let text = "generic function 'id' can't be used as a value";
77
+ let pre = "fun id[T](x: T) -> T = x\n\nfun double(x: Int) -> Int = x * 2\n\nfun apply(f: fn(Int) -> Int, x: Int) -> Int = f(x)\n\n";
78
+ expect("ce_generic_local", &format!("{pre}fun f() -> Int =\n h := id\n h(1)\n"), (8, 8), text);
79
+ expect("ce_generic_arg", &format!("{pre}fun f() -> Int = apply(id, 1)\n"), (7, 24), text);
80
+ // A parameter and a closure parameter named like the generic function are values.
81
+ let es = errors("ce_generic_param", &format!("{pre}fun f(id: fn(Int) -> Int) -> Int = apply(id, 1) + [1].map(|id| id + 1).length()\n"));
82
+ assert!(es.is_empty(), "{es:?}");
83
+ // A plain function, a closure around the generic one, and a local of that name are values.
84
+ let ok = format!("{pre}fun f() -> Int =\n g := double\n apply(double, 1) + apply(|x| id(x), 1) + g(2)\n\nfun k() -> Int =\n id := |n: Int| n + 1\n apply(id, 1)\n");
85
+ let es = errors("ce_generic_ok", &ok);
86
+ assert!(es.is_empty(), "{es:?}");
87
+ }
compiler/checker/tests/checker/features/identity.rs CHANGED
@@ -57,6 +57,24 @@ fn the_wrong_arguments_are_rejected() {
57
57
  assert!(e.contains("Bool"), "{e}");
58
58
  }
59
59
 
60
+ /// A type where a value goes says so (it was "expected Int, found Int").
61
+ #[test]
62
+ fn a_type_given_as_a_value_is_named() {
63
+ for (params, call, ty) in [
64
+ ("x: Int", "@sameRef(x, Int)", "Int"),
65
+ ("x: Str", "@sameRef(Str, x)", "Str"),
66
+ ("x: Boxed", "@sameRef(x, Boxed)", "Boxed"),
67
+ ("t: Tree", "@sameRef(t, Tree)", "Tree"),
68
+ ] {
69
+ let e = run(&format!("fun f({params}) -> Bool = {call}\n")).unwrap_err();
70
+ assert!(e.contains(&format!("@sameRef takes values, and {ty} is a type: pass a value, e.g. @sameRef(a, b)")), "{call}: {e}");
71
+ }
72
+ let e = run("fun f() -> Int = @memLoadI32(Int)\n").unwrap_err();
73
+ assert!(e.contains("@memLoadI32 takes values, and Int is a type"), "{e}");
74
+ // A variant and a constant are values.
75
+ run("Root = Leaf\n\nfun f(t: Tree) -> Bool = @sameRef(t, Leaf) && @sameRef(t, Root)\n").unwrap();
76
+ }
77
+
60
78
  /// The old spelling is gone with std/ref.plum: `ref` is an undefined name, and a function a
61
79
  /// program calls `same` is an ordinary function.
62
80
  #[test]
compiler/checker/tests/checker/features/mod.rs CHANGED
@@ -11,3 +11,4 @@ mod review_fixes;
11
11
  mod types;
12
12
  mod variant_pattern;
13
13
  mod empty_list;
14
+ mod clear_errors;
compiler/checker/tests/checker/question_tests.rs CHANGED
@@ -77,8 +77,10 @@ fn unit_value() {
77
77
  }
78
78
 
79
79
  #[test]
80
- fn eq_on_option_errors() {
80
+ fn eq_on_option_needs_an_eq_method() {
81
+ // `==` on two Options is `Option.eq` in std (see `features::clear_errors`); this bare
82
+ // `Option` has none, so `==` is the enum's built-in identity.
81
- rejected("fun f() -> Bool = Some(1) == Some(1)", "match");
83
+ ok("fun f() -> Bool = Some(1) == Some(1)");
82
84
  }
83
85
 
84
86
  #[test]
@@ -177,7 +179,7 @@ fn plain_name_bind_on_option_errors() {
177
179
  }
178
180
 
179
181
  const NUM_BOX: &str = "\
180
- enum NumErr = Bad | Worse
182
+ enum NumErr = Wrong | Worse
181
183
 
182
184
  struct Num(n: Int) =
183
185
  fun make(n: Int) -> Result[Num, NumErr] = Ok(Num(n: n))
compiler/wasm-codegen/src/construct.rs CHANGED
@@ -174,6 +174,14 @@ pub(crate) fn compileStaticString(text: &str, body: &mut Vec<u8>, state: &mut Mo
174
174
  wrapBytesAsStr(body);
175
175
  }
176
176
 
177
+ /// Whether the interpolated `e`, of type `ty`, has a `toStr` to call: its type's own method,
178
+ /// or the instantiation of a generic type's (`Map[Str, Int].toStr`) that the checker recorded
179
+ /// for this part.
180
+ fn hasToStr(e: &ast::Expr, ty: &PlumType, ctx: &LocalCtx) -> bool {
181
+ plum_checker::nominalName(ty).is_some_and(|n| ctx.func_ids.contains_key(&format!("{}::toStr", n)))
182
+ || ctx.call_inst.get(&(ctx.unit_inst, e.id, true)).is_some_and(|id| ctx.inst_funcs.contains_key(id))
183
+ }
184
+
177
185
  /// Lowers a string literal that contains at least one `{expr}` interpolation.
178
186
  /// Every part becomes a string-pointer-valued expression (static text via
179
187
  /// `compileStaticString`; `Str`/`Int`/`Bool`/`Float` interpolated values
@@ -195,8 +203,7 @@ pub(crate) fn compileInterpolatedString(
195
203
  let renderable = |e: &ast::Expr| match inferLocalType(e, ctx) {
196
204
  PlumType::TInt | PlumType::TBool | PlumType::TFloat => true,
197
205
  PlumType::TNamed(ref n) if n == ast::STR_TYPE => true,
198
- other => plum_checker::nominalName(&other)
206
+ other => hasToStr(e, &other, ctx),
199
- .is_some_and(|n| ctx.func_ids.contains_key(&format!("{}::toStr", n))),
200
207
  };
201
208
  let all = parts.iter().all(|p| match p {
202
209
  ast::StringPart::Interp(e) => renderable(e),
@@ -257,9 +264,7 @@ pub(crate) fn compileInterpolatedString(
257
264
  recv: None,
258
265
  type_args: Vec::new(),
259
266
  };
260
- if plum_checker::nominalName(&other)
267
+ if hasToStr(expr, &other, ctx) {
261
- .is_some_and(|n| ctx.func_ids.contains_key(&format!("{}::toStr", n)))
262
- {
263
268
  compileMethodCall(expr, &to_str, &other, expr, true, body, ctx, state)?;
264
269
  } else {
265
270
  return Err(format!(
docs/language.md CHANGED
@@ -226,6 +226,8 @@ fun main() =
226
226
 
227
227
  `Shape` is the type. `Circle` and `Rect` are ways to build and match it, not types of their own, so you read a variant's fields with a pattern rather than with `.field`.
228
228
 
229
+ A variant is written on its own (`Circle(r: 1.0)`, `Red`), so two types declared in one file can't share a variant name: that is an error at the second one. Two files may each have a `Red`; in a file its own `Red` is meant.
230
+
229
231
  Enums can be recursive and generic:
230
232
 
231
233
  ```plum
@@ -327,6 +329,7 @@ Each way of handling them:
327
329
  | `x.map(f)`, `x.andThen(f)` | Transform a value that is present |
328
330
  | `r.mapErr(f)` | Change the error, usually into your own error enum |
329
331
  | `o.okOr(e)`, `r.ok()` | Convert between `Option` and `Result` |
332
+ | `a == b`, `a != b` | Compare two `Option`s or two `Result`s by their values: the payloads' own `==` |
330
333
 
331
334
  `?` is shorthand for a `match`. `x := parse(a)?` followed by the rest of the block means:
332
335
 
@@ -466,6 +469,8 @@ Add a type when the compiler can't work one out: `|b: Box| b.get()`. Passing a c
466
469
 
467
470
  `adder(1)(2)` isn't supported yet, so bind the result to a name first.
468
471
 
472
+ A top-level function's name is a value too (`apply(double, 5)`), unless it is generic or `extern`: wrap those in a closure, `|x| id(x)`.
473
+
469
474
  ## Generics
470
475
 
471
476
  Declare type parameters in `[ ]`. The name can be anything.
std/Option.plum CHANGED
@@ -9,6 +9,13 @@ enum Option[T] =
9
9
  | None
10
10
  | Some(value: T)
11
11
 
12
+ # `==` and `!=`: both `None`, or both `Some` of values that are `==`.
13
+ fun eq(self, other: Option[T]) -> Bool = match self
14
+ None => other.isNone()
15
+ Some(a) => match other
16
+ None => false
17
+ Some(b) => a == b
18
+
12
19
  fun isSome(self) -> Bool = match self
13
20
  None => false
14
21
  Some(_) => true
std/Result.plum CHANGED
@@ -9,6 +9,15 @@ enum Result[T, E] =
9
9
  | Ok(value: T)
10
10
  | Err(error: E)
11
11
 
12
+ # `==` and `!=`: both `Ok` of values that are `==`, or both `Err` of errors that are `==`.
13
+ fun eq(self, other: Result[T, E]) -> Bool = match self
14
+ Ok(a) => match other
15
+ Ok(b) => a == b
16
+ Err(_) => false
17
+ Err(a) => match other
18
+ Ok(_) => false
19
+ Err(b) => a == b
20
+
12
21
  fun isOk(self) -> Bool = match self
13
22
  Ok(_) => true
14
23
  Err(_) => false
tests/core/interpolation_join.plum CHANGED
@@ -1,6 +1,10 @@
1
1
  import std/Int
2
2
  import std/Str
3
3
  import std/Float
4
+ import std/Slice
5
+ import std/collections/List
6
+ import std/collections/Map
7
+ import std/collections/Set
4
8
 
5
9
  # An interpolation of three or more parts is built in one buffer of the summed length
6
10
  # (`strJoin`): every part lands in order, views into other strings (a `sub` with a non-zero
@@ -9,6 +13,9 @@ import std/Float
9
13
  fun describe(name: Str, n: Int, ok: Bool) -> Str =
10
14
  "{name} has {n} items, ok={ok}!"
11
15
 
16
+ # A part of a generic type calls that type's `toStr`, as `m.toStr()` does.
17
+ fun show[T](x: T) -> Str = "<{x}>"
18
+
12
19
  test "several parts join in order"
13
20
  assert describe("box", 3, true) == "box has 3 items, ok=true!"
14
21
  assert describe("", -12, false) == " has -12 items, ok=false!"
@@ -29,3 +36,13 @@ test "two parts still join"
29
36
 
30
37
  test "a float part"
31
38
  assert "x={1.5}, y={2}" == "x=1.5, y=2"
39
+
40
+ test "a part of a generic type with toStr"
41
+ m := ["a" => 1, "b" => 2]
42
+ assert "{m}" == m.toStr()
43
+ assert "{m}" == "[a => 1, b => 2]"
44
+ assert "{[1, 2]}" == "[1,2]"
45
+ assert "xs={[1, 2].toSlice()}, s={Set.fromList([3, 1])}!" == "xs=[1,2], s=[1, 3]!"
46
+ assert show(m) == "<[a => 1, b => 2]>"
47
+ assert show([["x"]]) == "<[[x]]>"
48
+ assert show(7) == "<7>"
tests/core/option_result_eq.plum ADDED
@@ -0,0 +1,35 @@
1
+ # `==` and `!=` on two Options or two Results compare their values: `Option.eq` and
2
+ # `Result.eq` in std, which use the payloads' own `==`.
3
+ import std/Int
4
+ import std/Str
5
+ import std/Float
6
+ import std/Bool
7
+ import std/Option
8
+ import std/Result
9
+ import std/collections/List
10
+
11
+ struct P(x: Int, s: Str)
12
+ struct Q(x: Int) =
13
+ fun eq(self, o: Q) -> Bool = self.x == o.x
14
+
15
+ enum E = Bad | Worse
16
+
17
+ test "option eq"
18
+ a := Some(1)
19
+ none: Option[Int] := None
20
+ assert a == Some(1) && a != Some(2) && a != none && none == None && None == none
21
+ assert Some("ab") == Some("ab") && Some("ab") != Some("b")
22
+ assert Some(Some(1)) == Some(Some(1)) && Some(Some(1)) != Some(none)
23
+ assert Some([1, 2]) == Some([1, 2]) && Some([1, 2]) != Some([1])
24
+ assert Some(Q(x: 1)) == Some(Q(x: 1)) && Some(Q(x: 1)) != Some(Q(x: 2))
25
+ assert Some(1.5) == Some(1.5) && Some(true) != Some(false)
26
+ p := P(x: 1, s: "a")
27
+ assert Some(p) == Some(p)
28
+
29
+ test "result eq"
30
+ r: Result[Int, Str] := Ok(1)
31
+ e: Result[Int, Str] := Err("x")
32
+ assert r == Ok(1) && r != Ok(2) && r != e && e == Err("x") && e != Err("y")
33
+ b: Result[Int, E] := Err(Bad)
34
+ assert b == Err(Bad) && b != Err(Worse) && b != Ok(0)
35
+ assert r.ok() == Some(1) && e.ok() == None