plum
git clone https://git.pyrossh.dev/plum
A statically typed, imperative programming language inspired by rust, python
9aed011
— Peter John
2026-11-16T19:41:13+05:30
U2b: `@final` trait defaults and `@std` variants; Screen.name can't be overridden, a GoTo is made only by Cmd.goTo<S>()
- compiler/checker/src/traits.rs +43 -0
- compiler/checker/tests/checker/diagnostic_tests.rs +59 -0
- compiler/core/src/ast.rs +6 -0
- compiler/core/src/loader.rs +66 -1
- compiler/core/src/parser.rs +40 -9
- compiler/core/src/tests_lower.rs +1 -0
- compiler/core/tests/core/formatter_test.rs +8 -0
- compiler/tooling/tree-sitter-plum/grammar.js +41 -29
- compiler/tooling/tree-sitter-plum/queries/plum/format.scm +3 -0
- compiler/tooling/tree-sitter-plum/queries/plum/highlights.scm +4 -0
- compiler/tooling/tree-sitter-plum/src/grammar.json +0 -0
- compiler/tooling/tree-sitter-plum/src/node-types.json +0 -0
- compiler/tooling/tree-sitter-plum/src/parser.c +0 -0
- compiler/tooling/tree-sitter-plum/test/corpus/decl_attribute.txt +59 -0
- docs/game.md +3 -3
- docs/language.md +22 -0
- docs/std.md +1 -1
- std/game/Cmd.plum +3 -2
- std/game/Screen.plum +3 -3
- tests/std/game/Cmd.plum +4 -3
compiler/checker/src/traits.rs
CHANGED
|
@@ -17,6 +17,8 @@ pub struct TraitMethodInfo {
|
|
|
17
17
|
/// generics as `TParam`s.
|
|
18
18
|
pub sig: PlumType,
|
|
19
19
|
pub hasDefault: bool,
|
|
20
|
+
/// `@final`: no subtrait or implementer gives it a body of its own.
|
|
21
|
+
pub isFinal: bool,
|
|
20
22
|
pub hasSelf: bool,
|
|
21
23
|
/// Arguments a call must give (the params before the first with a default).
|
|
22
24
|
pub minRequired: usize,
|
|
@@ -317,6 +319,7 @@ pub fn buildTraits(source: &ast::Source) -> Traits {
|
|
|
317
319
|
name: m.sig.name.clone(),
|
|
318
320
|
sig,
|
|
319
321
|
hasDefault: m.hasDefault,
|
|
322
|
+
isFinal: m.isFinal,
|
|
320
323
|
hasSelf: m.sig.has_self,
|
|
321
324
|
minRequired: minRequired(&m.sig),
|
|
322
325
|
dyn_copy: plum_core::trait_defaults::needsDynCopy(&m.sig),
|
|
@@ -642,6 +645,14 @@ pub(crate) fn checkTraitDecls(source: &ast::Source, traits: &Traits, methods: &M
|
|
|
642
645
|
(Some(o), Some(s)) => o.sig == s && o.hasSelf == sm.hasSelf,
|
|
643
646
|
_ => false,
|
|
644
647
|
};
|
|
648
|
+
if sm.isFinal {
|
|
649
|
+
errors.push(CheckError::resolution(
|
|
650
|
+
m.sig.line,
|
|
651
|
+
m.sig.column,
|
|
652
|
+
format!("trait '{}': method '{}' is `@final` in its supertrait {}, so no trait or type gives it another body", t.name, m.sig.name, owner),
|
|
653
|
+
));
|
|
654
|
+
continue;
|
|
655
|
+
}
|
|
645
656
|
if m.hasDefault && sameSig {
|
|
646
657
|
continue;
|
|
647
658
|
}
|
|
@@ -701,6 +712,20 @@ pub(crate) fn checkTraitDecls(source: &ast::Source, traits: &Traits, methods: &M
|
|
|
701
712
|
_ => {}
|
|
702
713
|
}
|
|
703
714
|
}
|
|
715
|
+
// The methods each type wrote itself, not the copies of trait defaults.
|
|
716
|
+
let defaultsAt = plum_core::trait_defaults::defaultPositions(source);
|
|
717
|
+
let ownMethod = |ty: &str, name: &str| {
|
|
718
|
+
source.items.iter().find_map(|i| match i {
|
|
719
|
+
ast::Item::Fn(f)
|
|
720
|
+
if f.type_param.as_deref() == Some(ty)
|
|
721
|
+
&& f.name == name
|
|
722
|
+
&& !plum_core::trait_defaults::isDefaultCopy(f, &defaultsAt.0, &defaultsAt.1) =>
|
|
723
|
+
{
|
|
724
|
+
Some(f)
|
|
725
|
+
}
|
|
726
|
+
_ => None,
|
|
727
|
+
})
|
|
728
|
+
};
|
|
704
729
|
for e in types.values() {
|
|
705
730
|
if e.implements.is_empty() {
|
|
706
731
|
continue;
|
|
@@ -750,6 +775,24 @@ pub(crate) fn checkTraitDecls(source: &ast::Source, traits: &Traits, methods: &M
|
|
|
750
775
|
.unwrap_or_default();
|
|
751
776
|
// A supertrait's methods are checked under its own entry.
|
|
752
777
|
for m in t.methods.iter().filter(|m| m.from.is_none()) {
|
|
778
|
+
// `@final`: the trait's default is the type's, and writing one is an error.
|
|
779
|
+
if m.isFinal {
|
|
780
|
+
if let Some(f) = ownMethod(&e.name, &m.name) {
|
|
781
|
+
let prev = (!f.file.is_empty()).then(|| setCurrentFile(&f.file));
|
|
782
|
+
errors.push(CheckError::resolution(
|
|
783
|
+
f.line,
|
|
784
|
+
f.column,
|
|
785
|
+
format!(
|
|
786
|
+
"{}.{}: '{}' is `@final` in trait {}{via}, so a type can't write its own: remove it",
|
|
787
|
+
e.name, m.name, m.name, t.name
|
|
788
|
+
),
|
|
789
|
+
));
|
|
790
|
+
if let Some(p) = prev {
|
|
791
|
+
setCurrentFile(&p);
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
continue;
|
|
795
|
+
}
|
|
753
796
|
let Some(expected) = traits.methodSig(&entry.ty, &m.name, &selfTy) else { continue };
|
|
754
797
|
let key = (e.name.clone(), m.name.clone());
|
|
755
798
|
let Some(found) = methods.get(&key).filter(|_| declared.contains(&key)) else {
|
compiler/checker/tests/checker/diagnostic_tests.rs
CHANGED
|
@@ -476,3 +476,62 @@ fn aFieldAttributeIsAnError() {
|
|
|
476
476
|
assert!(err.contains("syntax") || err.contains("parse") || err.contains("unexpected"), "{err}");
|
|
477
477
|
}
|
|
478
478
|
|
|
479
|
+
|
|
480
|
+
/// The messages of the first errors a program meets: the front end's, else the checker's
|
|
481
|
+
/// (none when it checks).
|
|
482
|
+
fn firstErrors(src: &str) -> Vec<(usize, String)> {
|
|
483
|
+
let mut source = plum_test_support::parseRawSource(src);
|
|
484
|
+
source.stampFile("main.plum");
|
|
485
|
+
match plum_core::lower::frontEndDiag(&mut source) {
|
|
486
|
+
Err(ds) => ds.into_iter().map(|d| (d.line, d.message)).collect(),
|
|
487
|
+
Ok(()) => checkSource(&source).err().unwrap_or_default().into_iter().map(|e| (e.line, e.message)).collect(),
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
/// `@final` on a trait's default: no type writes its own (std/game's `Screen.name`), and no
|
|
492
|
+
/// subtrait gives it another default; a type that doesn't write it gets the trait's.
|
|
493
|
+
#[test]
|
|
494
|
+
fn aFinalTraitDefaultCantBeOverridden() {
|
|
495
|
+
let pre = "trait Named =\n @final fun n(self) -> Int = 1\n\n fun m(self) -> Int = 2\n\n";
|
|
496
|
+
let main = "\nprimitive Main[App] =\n fun main() -> Int = 1\n";
|
|
497
|
+
let es = firstErrors(&format!("{pre}struct S[Named](x: Int) =\n fun m(self) -> Int = 3\n\n fun n(self) -> Int = 4\n{main}"));
|
|
498
|
+
assert_eq!(es.len(), 1, "{es:?}");
|
|
499
|
+
assert_eq!(es[0], (9, "S.n: 'n' is `@final` in trait Named, so a type can't write its own: remove it".to_string()), "{es:?}");
|
|
500
|
+
let es = firstErrors(&format!("{pre}trait Sub[Named] =\n fun n(self) -> Int = 5\n\nstruct T[Sub](x: Int)\n{main}"));
|
|
501
|
+
assert!(es.iter().any(|(l, m)| *l == 7 && m == "trait 'Sub': method 'n' is `@final` in its supertrait Named, so no trait or type gives it another body"), "{es:?}");
|
|
502
|
+
let es = firstErrors(&format!("{pre}trait Sub[Named] =\n fun k(self) -> Int = 5\n\nstruct T[Sub](x: Int) =\n fun n(self) -> Int = 6\n{main}"));
|
|
503
|
+
assert!(es.iter().any(|(l, m)| *l == 10 && m.starts_with("T.n: 'n' is `@final` in trait Named (Sub extends Named)")), "{es:?}");
|
|
504
|
+
assert_eq!(firstErrors(&format!("{pre}struct S[Named](x: Int)\n{main}")), vec![]);
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/// An attribute fits what it is on: `@final` a trait's method with a default, `@std` an enum
|
|
508
|
+
/// variant; any other is an error, and none goes on another declaration.
|
|
509
|
+
#[test]
|
|
510
|
+
fn anAttributeMustFitWhatItIsOn() {
|
|
511
|
+
let main = "\nprimitive Main[App] =\n fun main() -> Int = 1\n";
|
|
512
|
+
let es = firstErrors(&format!("trait Named =\n @final fun n(self) -> Int\n{main}"));
|
|
513
|
+
assert!(es.iter().any(|(l, m)| *l == 2 && m.contains("`@final` on `n`, which has no default")), "{es:?}");
|
|
514
|
+
let es = firstErrors(&format!("trait Named =\n @std fun n(self) -> Int = 1\n{main}"));
|
|
515
|
+
assert!(es.iter().any(|(_, m)| m.contains("`@std` is not an attribute of a trait's method: the one there is is `@final`")), "{es:?}");
|
|
516
|
+
let es = firstErrors(&format!("enum E =\n | @final A\n | B\n{main}"));
|
|
517
|
+
assert!(es.iter().any(|(_, m)| m.contains("`@final` is not an attribute of an enum variant: the one there is is `@std`")), "{es:?}");
|
|
518
|
+
let err = plum_test_support::load("fn_attribute", &format!("struct P(x: Int) =\n @final fun n(self) -> Int = 1\n{main}")).err().expect("only a trait's method takes an attribute");
|
|
519
|
+
assert!(err.contains("syntax") || err.contains("parse") || err.contains("unexpected"), "{err}");
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/// `| @std GoTo(..)` (std/game/Cmd): only std builds the variant; a file outside std that
|
|
523
|
+
/// constructs one is an error at the construction, while matching one and building a
|
|
524
|
+
/// variant of its own named like it are fine.
|
|
525
|
+
#[test]
|
|
526
|
+
fn aStdVariantIsBuiltOnlyByStd() {
|
|
527
|
+
let head = "module app\nimport std/Int\nimport std/Str\nimport std/game/Cmd\nimport std/game/Screen\nimport std/App\n\nstruct Lobby[Screen](n: Int)\n\nprimitive Main[App] =\n";
|
|
528
|
+
let err = plum_test_support::load("std_variant", &format!("{head} fun main() -> Int =\n c := GoTo(screen: \"Lobby\")\n 1\n")).err().expect("GoTo is std's to build");
|
|
529
|
+
assert!(
|
|
530
|
+
err.contains("main.plum:12:10") && err.contains("`GoTo` is a `@std` variant of Cmd: only std builds one, so use the static of Cmd that makes it (any file may match it)"),
|
|
531
|
+
"{err}"
|
|
532
|
+
);
|
|
533
|
+
let matched = " fun main() -> Int = match Cmd.goTo<Lobby>()\n GoTo(screen) => screen.length()\n _ => 0\n";
|
|
534
|
+
plum_test_support::load("std_variant_match", &format!("{head}{matched}")).expect("matching a GoTo is fine");
|
|
535
|
+
let own = " fun main() -> Int = match GoTo(screen: 2)\n GoTo(screen) => screen\n\nenum Mine =\n | GoTo(screen: Int)\n";
|
|
536
|
+
plum_test_support::load("std_variant_own", &format!("{head}{own}")).expect("a variant of one's own named GoTo");
|
|
537
|
+
}
|
compiler/core/src/ast.rs
CHANGED
|
@@ -484,6 +484,9 @@ pub struct Trait {
|
|
|
484
484
|
pub struct TraitMethod {
|
|
485
485
|
pub sig: Fn,
|
|
486
486
|
pub hasDefault: bool,
|
|
487
|
+
/// `@final fun ..`: its default is every implementer's, and a type that writes its own
|
|
488
|
+
/// is an error (`plum_checker::traits::checkTraitDecls`).
|
|
489
|
+
pub isFinal: bool,
|
|
487
490
|
}
|
|
488
491
|
|
|
489
492
|
impl Trait {
|
|
@@ -624,6 +627,9 @@ pub struct EnumVariant {
|
|
|
624
627
|
/// field has one. A construction that leaves a defaulted field out gets a fresh copy of
|
|
625
628
|
/// its default (`field_defaults::fillFieldDefaults`).
|
|
626
629
|
pub field_defaults: Vec<Option<Expr>>,
|
|
630
|
+
/// `| @std GoTo(..)`: only std constructs the variant; any file may match it
|
|
631
|
+
/// (`loader::stdOnlyVariants`).
|
|
632
|
+
pub std_only: bool,
|
|
627
633
|
}
|
|
628
634
|
|
|
629
635
|
// ---------- Functions ----------
|
compiler/core/src/loader.rs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
use std::collections::{HashMap, HashSet};
|
|
2
2
|
use std::path::{Path, PathBuf};
|
|
3
3
|
|
|
4
|
-
use crate::ast::{Import, Item, PrimitiveDecl, Source, APP_TRAIT, BUILTIN_PRIMITIVES, MEMBER_SEP, UNIT_TEST_TRAIT};
|
|
4
|
+
use crate::ast::{Expr, ExprKind, FnBody, Import, Item, PrimitiveDecl, Source, APP_TRAIT, BUILTIN_PRIMITIVES, MEMBER_SEP, UNIT_TEST_TRAIT};
|
|
5
5
|
use crate::builtin_usage::usedBuiltinTypeNames;
|
|
6
6
|
use crate::diag::{DiagKind, Diagnostic};
|
|
7
7
|
use crate::parser::AstParser;
|
|
@@ -76,6 +76,7 @@ pub fn loadAndMergeWithOverridesDiag(
|
|
|
76
76
|
oneApp(&files)?;
|
|
77
77
|
importedMainsAreStatics(&mut files);
|
|
78
78
|
crate::timing::time("resolve modules", || resolveFileModules(&mut files, lib_path))?;
|
|
79
|
+
stdOnlyVariants(&files, lib_path)?;
|
|
79
80
|
crate::timing::time("merge", || -> Loaded_<()> {
|
|
80
81
|
for f in &files {
|
|
81
82
|
mergeItems(&f.path, &f.source, &mut items, &mut names, &mut prims)?;
|
|
@@ -517,6 +518,70 @@ fn nativeOnlyInStd(files: &[Loaded], lib_path: &Path) -> Loaded_<()> {
|
|
|
517
518
|
Ok(())
|
|
518
519
|
}
|
|
519
520
|
|
|
521
|
+
/// `| @std GoTo(..)`: a variant only std builds. A construction of one in a file outside std
|
|
522
|
+
/// (`GoTo(screen: "Menu")`, or the bare name) is an error at it; a pattern is not. Run once
|
|
523
|
+
/// variants have their global names, so a file's own variant named like std's is its own.
|
|
524
|
+
fn stdOnlyVariants(files: &[Loaded], lib_path: &Path) -> Loaded_<()> {
|
|
525
|
+
let mut owners: HashMap<&str, &str> = HashMap::new();
|
|
526
|
+
for f in files.iter().filter(|f| isStdFile(&f.path, lib_path)) {
|
|
527
|
+
for item in &f.source.items {
|
|
528
|
+
if let Item::Enum(e) = item {
|
|
529
|
+
for v in e.variants.iter().filter(|v| v.std_only) {
|
|
530
|
+
owners.insert(v.name.as_str(), e.name.as_str());
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
if owners.is_empty() {
|
|
536
|
+
return Ok(());
|
|
537
|
+
}
|
|
538
|
+
for f in files.iter().filter(|f| !isStdFile(&f.path, lib_path)) {
|
|
539
|
+
let mut found: Option<(usize, usize, String)> = None;
|
|
540
|
+
let mut look = |x: &Expr| {
|
|
541
|
+
let name = match &x.kind {
|
|
542
|
+
ExprKind::ClassCall(c) => c.type_name.as_str(),
|
|
543
|
+
ExprKind::TypeName(n) => n.as_str(),
|
|
544
|
+
_ => return,
|
|
545
|
+
};
|
|
546
|
+
if let (Some(owner), None) = (owners.get(name), &found) {
|
|
547
|
+
let shown = crate::modules::sourceFnName(name);
|
|
548
|
+
found = Some((
|
|
549
|
+
x.span.startLine,
|
|
550
|
+
x.span.startColumn,
|
|
551
|
+
format!("`{shown}` is a `@std` variant of {owner}: only std builds one, so use the static of {owner} that makes it (any file may match it)"),
|
|
552
|
+
));
|
|
553
|
+
}
|
|
554
|
+
};
|
|
555
|
+
for item in &f.source.items {
|
|
556
|
+
match item {
|
|
557
|
+
Item::Fn(func) => {
|
|
558
|
+
for p in &func.params {
|
|
559
|
+
if let Some(d) = &p.default {
|
|
560
|
+
crate::visit::walkRef(d, &mut look);
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
match &func.body {
|
|
564
|
+
FnBody::Expr(e) => crate::visit::walkRef(e, &mut look),
|
|
565
|
+
FnBody::Block(b) => crate::visit::walkBlockRef(b, &mut look),
|
|
566
|
+
FnBody::Extern => {}
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
Item::Const(c) => crate::visit::walkRef(&c.value, &mut look),
|
|
570
|
+
Item::Enum(e) => {
|
|
571
|
+
for d in e.variants.iter().flat_map(|v| v.field_defaults.iter().flatten()) {
|
|
572
|
+
crate::visit::walkRef(d, &mut look);
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
_ => {}
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
if let Some((line, column, message)) = found {
|
|
579
|
+
return Err(vec![Diagnostic::new(DiagKind::Type, displayPath(&f.path), line, column, message)]);
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
Ok(())
|
|
583
|
+
}
|
|
584
|
+
|
|
520
585
|
/// Gives each file's `import a/b` the name `b` for that module's functions and constants
|
|
521
586
|
/// (see `modules`), renaming the ones several files define.
|
|
522
587
|
fn resolveFileModules(files: &mut [Loaded], lib_path: &Path) -> Loaded_<()> {
|
compiler/core/src/parser.rs
CHANGED
|
@@ -367,11 +367,44 @@ impl<'a> AstParser<'a> {
|
|
|
367
367
|
defaults.push(d);
|
|
368
368
|
}
|
|
369
369
|
f.body = FnBody::Extern;
|
|
370
|
+
let isFinal = match self.declAttribute(n) {
|
|
371
|
+
Some((a, line, column)) if a == "final" && !hasDefault => {
|
|
372
|
+
self.litErrors.borrow_mut().push((
|
|
373
|
+
line,
|
|
374
|
+
column,
|
|
375
|
+
format!("`@final` on `{}`, which has no default: `@final` keeps a trait's default from being overridden, so give `{}` a body", f.name, f.name),
|
|
376
|
+
));
|
|
377
|
+
false
|
|
378
|
+
}
|
|
379
|
+
Some((a, _, _)) => a == "final",
|
|
380
|
+
None => false,
|
|
381
|
+
};
|
|
370
|
-
t.methods.push(TraitMethod { sig: f, hasDefault });
|
|
382
|
+
t.methods.push(TraitMethod { sig: f, hasDefault, isFinal });
|
|
371
383
|
}
|
|
372
384
|
(t, defaults)
|
|
373
385
|
}
|
|
374
386
|
|
|
387
|
+
/// The attribute before a declaration (`@final fun ..`, `| @std GoTo(..)`): its name and
|
|
388
|
+
/// position. An unknown name, or one that doesn't fit what it is on, is an error here.
|
|
389
|
+
fn declAttribute(&self, node: Node) -> Option<(String, usize, usize)> {
|
|
390
|
+
let a = node.child_by_field_name("attribute")?;
|
|
391
|
+
let name = a.child_by_field_name("name").map(|c| self.text(c)).unwrap_or_default();
|
|
392
|
+
let pos = a.start_position();
|
|
393
|
+
let (fits, what, one) = if node.kind() == "fn" {
|
|
394
|
+
(name == "final", "a trait's method", "`@final` (no type writes its own)")
|
|
395
|
+
} else {
|
|
396
|
+
(name == "std", "an enum variant", "`@std` (only std builds the variant)")
|
|
397
|
+
};
|
|
398
|
+
if !fits {
|
|
399
|
+
self.litErrors.borrow_mut().push((
|
|
400
|
+
pos.row + 1,
|
|
401
|
+
pos.column + 1,
|
|
402
|
+
format!("`@{name}` is not an attribute of {what}: the one there is is {one}"),
|
|
403
|
+
));
|
|
404
|
+
}
|
|
405
|
+
Some((name, pos.row + 1, pos.column + 1))
|
|
406
|
+
}
|
|
407
|
+
|
|
375
408
|
fn parseEnum(&self, node: Node) -> Enum {
|
|
376
409
|
// enum: "enum" type_identifier generics? "=" body
|
|
377
410
|
let named: Vec<Node> = self.namedChildren(node);
|
|
@@ -445,13 +478,10 @@ impl<'a> AstParser<'a> {
|
|
|
445
478
|
// | ("(" enum_named_field,* ")")? -- named payload fields
|
|
446
479
|
// named children after the name: `type` (bare positional fields) or `enum_named_field`
|
|
447
480
|
// (named fields, each wrapping its own `name`/`type`) — never mixed on one variant.
|
|
481
|
+
let std_only = node.kind() == "field" && self.declAttribute(node).is_some_and(|(a, _, _)| a == "std");
|
|
448
|
-
let
|
|
482
|
+
let named: Vec<Node> = self.namedChildren(node).into_iter().filter(|n| n.kind() != "decl_attribute").collect();
|
|
449
|
-
.named_child(0)
|
|
450
|
-
|
|
483
|
+
let name = named.first().map(|n| self.text(*n)).unwrap_or_default();
|
|
451
|
-
.unwrap_or_default();
|
|
452
|
-
let rest: Vec<Node> = (1.
|
|
484
|
+
let rest: Vec<Node> = named.into_iter().skip(1).collect();
|
|
453
|
-
.filter_map(|i| node.named_child(i as u32))
|
|
454
|
-
.collect();
|
|
455
485
|
let named_fields: Vec<Node> = rest
|
|
456
486
|
.iter()
|
|
457
487
|
.filter(|n| n.kind() == "enum_named_field")
|
|
@@ -502,6 +532,7 @@ impl<'a> AstParser<'a> {
|
|
|
502
532
|
field_names,
|
|
503
533
|
mut_fields,
|
|
504
534
|
field_defaults,
|
|
535
|
+
std_only,
|
|
505
536
|
}
|
|
506
537
|
}
|
|
507
538
|
|
|
@@ -518,7 +549,7 @@ impl<'a> AstParser<'a> {
|
|
|
518
549
|
// `<Receiver>` annotation syntax to parse.
|
|
519
550
|
let named: Vec<Node> = self.namedChildren(node);
|
|
520
551
|
|
|
521
|
-
let name =
|
|
552
|
+
let name = node.child_by_field_name("name").map(|n| self.text(n)).unwrap_or_default();
|
|
522
553
|
|
|
523
554
|
let params: Vec<Param> = named
|
|
524
555
|
.iter()
|
compiler/core/src/tests_lower.rs
CHANGED
|
@@ -48,6 +48,7 @@ fn reportStruct() -> crate::ast::Item {
|
|
|
48
48
|
field_names: vec![REPORT_FIELD.to_string()],
|
|
49
49
|
mut_fields: vec![true],
|
|
50
50
|
field_defaults: Vec::new(),
|
|
51
|
+
std_only: false,
|
|
51
52
|
}],
|
|
52
53
|
kind: crate::ast::TypeKind::Struct(crate::ast::StructInfo::default()),
|
|
53
54
|
})
|
compiler/core/tests/core/formatter_test.rs
CHANGED
|
@@ -380,3 +380,11 @@ fn blocksAndListLinesFormat() {
|
|
|
380
380
|
assert_eq!(once, expected);
|
|
381
381
|
assertFormatsUnchanged(expected);
|
|
382
382
|
}
|
|
383
|
+
|
|
384
|
+
/// An attribute is followed by one space: `@final fun` in a trait, `| @std GoTo(..)`.
|
|
385
|
+
#[test]
|
|
386
|
+
fn attributesKeepTheirPlace() {
|
|
387
|
+
let input = "trait Screen =\n @final fun name(self) -> Str = \"s\"\n\n fun view(self) -> Int = 1\n\nenum Cmd =\n | @std GoTo(screen: Str)\n | Exit\n";
|
|
388
|
+
let once = formatSource(input).expect("first pass");
|
|
389
|
+
assert_eq!(once, input, "got: {once}");
|
|
390
|
+
}
|
compiler/tooling/tree-sitter-plum/grammar.js
CHANGED
|
@@ -131,7 +131,7 @@ module.exports = grammar({
|
|
|
131
131
|
optional(field("implements", $.implements)),
|
|
132
132
|
optional($.old_implements),
|
|
133
133
|
// No body: a marker trait (`trait UnitTest`).
|
|
134
|
-
optional(seq("=", $._indent, field("methods", repeat($.fn)), $._dedent)),
|
|
134
|
+
optional(seq("=", $._indent, field("methods", repeat(choice($.fn, alias($.final_fn, $.fn)))), $._dedent)),
|
|
135
135
|
),
|
|
136
136
|
type: ($) =>
|
|
137
137
|
choice(
|
|
@@ -234,6 +234,8 @@ module.exports = grammar({
|
|
|
234
234
|
enum_field: ($) =>
|
|
235
235
|
seq(
|
|
236
236
|
"|",
|
|
237
|
+
// `| @std GoTo(screen: Str)`: only std builds the variant (any file may match it).
|
|
238
|
+
optional(field("attribute", $.decl_attribute)),
|
|
237
239
|
field("name", $.type_identifier),
|
|
238
240
|
field(
|
|
239
241
|
"parameters",
|
|
@@ -272,34 +274,15 @@ module.exports = grammar({
|
|
|
272
274
|
optional(seq("=", field("default", $.expression))),
|
|
273
275
|
),
|
|
274
276
|
|
|
275
|
-
fn: ($) =>
|
|
276
|
-
prec.left(
|
|
277
|
-
seq(
|
|
278
|
-
// `extern fun foo(...)` (no `=` body at all) declares a function backed
|
|
279
|
-
// by a host-provided wasm import instead of a compiled Plum body — see
|
|
280
|
-
|
|
277
|
+
// `@final` before a trait's default method, `@std` before an enum variant: a name the
|
|
281
|
-
// vs. legitimately absent is enforced by `plum-checker` (a clear semantic
|
|
282
|
-
|
|
278
|
+
// compiler checks (docs/language.md, "Attributes").
|
|
279
|
+
decl_attribute: ($) => seq("@", field("name", $.var_identifier)),
|
|
280
|
+
|
|
283
|
-
|
|
281
|
+
// `@final fun name(self) -> Str = ..` in a trait: no type writes its own (a `fn` with
|
|
284
|
-
// the wasm module under its own name, with the `extern` boundary ABI.
|
|
285
|
-
optional(choice(field("externKw", "extern"), field("exportKw", "export"))),
|
|
286
|
-
// `fip fun`: a compile-time guarantee that the body's updates run in place.
|
|
287
|
-
optional(field("fipKw", "fip")),
|
|
288
|
-
field("kw", "fun"),
|
|
289
|
-
field("name", $.fn_identifier),
|
|
290
|
-
// Declared type parameters: `fun map<B>(..)`, `fun id<Elem>(..)`.
|
|
291
|
-
optional(field("generics", $.fn_generics)),
|
|
292
|
-
// A method's receiver is implicit from nesting the `fn` inside a
|
|
293
|
-
// `type`/`enum` body (see `class`/`enum` above) — there is no top-level
|
|
294
|
-
// `<Receiver>` annotation form. `self` may still appear as a bare first
|
|
295
|
-
// parameter to spell out that a nested `fn` is an instance method; it
|
|
296
|
-
// carries no type of its own, so the parser discards it rather than
|
|
297
|
-
|
|
282
|
+
// an attribute; only a trait's methods take one).
|
|
298
|
-
field("params", seq("(", optional(commaSep1(choice($.self, $.param))), ")")),
|
|
299
|
-
|
|
283
|
+
final_fn: ($) => prec.left(seq(field("attribute", $.decl_attribute), ...fnParts($))),
|
|
284
|
+
|
|
300
|
-
|
|
285
|
+
fn: ($) => prec.left(seq(...fnParts($))),
|
|
301
|
-
)
|
|
302
|
-
),
|
|
303
286
|
|
|
304
287
|
body: ($) => seq($._indent, repeat($._statement), $._dedent),
|
|
305
288
|
|
|
@@ -934,3 +917,32 @@ function productBody($, keyword) {
|
|
|
934
917
|
optional(seq("=", $._indent, field("methods", repeat(choice($.fn, $.const))), $._dedent)),
|
|
935
918
|
);
|
|
936
919
|
}
|
|
920
|
+
|
|
921
|
+
// The parts of a `fn`, after an attribute when it has one (`final_fn`).
|
|
922
|
+
function fnParts($) {
|
|
923
|
+
return [
|
|
924
|
+
// `extern fun foo(...)` (no `=` body at all) declares a function backed
|
|
925
|
+
// by a host-provided wasm import instead of a compiled Plum body — see
|
|
926
|
+
// std/Io's `printLn`. Whether the body is actually present
|
|
927
|
+
// vs. legitimately absent is enforced by `plum-checker` (a clear semantic
|
|
928
|
+
// error either way), not the grammar, to keep this rule simple.
|
|
929
|
+
// `export fun foo(...) = ...` is a normal function that is also exported from
|
|
930
|
+
// the wasm module under its own name, with the `extern` boundary ABI.
|
|
931
|
+
optional(choice(field("externKw", "extern"), field("exportKw", "export"))),
|
|
932
|
+
// `fip fun`: a compile-time guarantee that the body's updates run in place.
|
|
933
|
+
optional(field("fipKw", "fip")),
|
|
934
|
+
field("kw", "fun"),
|
|
935
|
+
field("name", $.fn_identifier),
|
|
936
|
+
// Declared type parameters: `fun map<B>(..)`, `fun id<Elem>(..)`.
|
|
937
|
+
optional(field("generics", $.fn_generics)),
|
|
938
|
+
// A method's receiver is implicit from nesting the `fn` inside a
|
|
939
|
+
// `type`/`enum` body (see `class`/`enum` above) — there is no top-level
|
|
940
|
+
// `<Receiver>` annotation form. `self` may still appear as a bare first
|
|
941
|
+
// parameter to spell out that a nested `fn` is an instance method; it
|
|
942
|
+
// carries no type of its own, so the parser discards it rather than
|
|
943
|
+
// emitting a `param` — see `parse_fn`.
|
|
944
|
+
field("params", seq("(", optional(commaSep1(choice($.self, $.param))), ")")),
|
|
945
|
+
field("returns", optional(seq("->", choice($.type, $.fn_value_type)))),
|
|
946
|
+
optional(field("body", seq("=", choice($.expression, $.body)))),
|
|
947
|
+
];
|
|
948
|
+
}
|
compiler/tooling/tree-sitter-plum/queries/plum/format.scm
CHANGED
|
@@ -423,6 +423,9 @@
|
|
|
423
423
|
|
|
424
424
|
(fn "export" @append_space)
|
|
425
425
|
|
|
426
|
+
; `@final fun ..` in a trait and `| @std GoTo(..)`: an attribute, then what it marks.
|
|
427
|
+
(decl_attribute) @append_space
|
|
428
|
+
|
|
426
429
|
; ============================================================
|
|
427
430
|
; List literals and call blocks — written across lines, one item a line between
|
|
428
431
|
; the brackets (items may be separated by line breaks alone, so they must stay
|
compiler/tooling/tree-sitter-plum/queries/plum/highlights.scm
CHANGED
|
@@ -144,6 +144,10 @@
|
|
|
144
144
|
"@" @function.builtin
|
|
145
145
|
name: (var_identifier) @function.builtin)
|
|
146
146
|
|
|
147
|
+
(decl_attribute
|
|
148
|
+
"@" @attribute
|
|
149
|
+
name: (var_identifier) @attribute)
|
|
150
|
+
|
|
147
151
|
"crash" @keyword.control.exception
|
|
148
152
|
|
|
149
153
|
"match" @keyword
|
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/decl_attribute.txt
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
================================================================================
|
|
2
|
+
final trait default
|
|
3
|
+
================================================================================
|
|
4
|
+
|
|
5
|
+
trait Screen =
|
|
6
|
+
@final fun name(self) -> Str = "s"
|
|
7
|
+
|
|
8
|
+
fun view(self) -> Int = 1
|
|
9
|
+
|
|
10
|
+
--------------------------------------------------------------------------------
|
|
11
|
+
|
|
12
|
+
(source
|
|
13
|
+
(trait
|
|
14
|
+
(type_identifier)
|
|
15
|
+
(fn
|
|
16
|
+
(decl_attribute
|
|
17
|
+
(var_identifier))
|
|
18
|
+
(fn_identifier)
|
|
19
|
+
(self)
|
|
20
|
+
(type
|
|
21
|
+
(type_identifier))
|
|
22
|
+
(expression
|
|
23
|
+
(primary_expression
|
|
24
|
+
(string
|
|
25
|
+
(string_start)
|
|
26
|
+
(string_content)
|
|
27
|
+
(string_end)))))
|
|
28
|
+
(fn
|
|
29
|
+
(fn_identifier)
|
|
30
|
+
(self)
|
|
31
|
+
(type
|
|
32
|
+
(type_identifier))
|
|
33
|
+
(expression
|
|
34
|
+
(primary_expression
|
|
35
|
+
(integer))))))
|
|
36
|
+
|
|
37
|
+
================================================================================
|
|
38
|
+
std-only variant
|
|
39
|
+
================================================================================
|
|
40
|
+
|
|
41
|
+
enum Cmd =
|
|
42
|
+
| @std GoTo(screen: Str)
|
|
43
|
+
| Exit
|
|
44
|
+
|
|
45
|
+
--------------------------------------------------------------------------------
|
|
46
|
+
|
|
47
|
+
(source
|
|
48
|
+
(enum
|
|
49
|
+
(type_identifier)
|
|
50
|
+
(field
|
|
51
|
+
(decl_attribute
|
|
52
|
+
(var_identifier))
|
|
53
|
+
(type_identifier)
|
|
54
|
+
(enum_named_field
|
|
55
|
+
(var_identifier)
|
|
56
|
+
(type
|
|
57
|
+
(type_identifier))))
|
|
58
|
+
(field
|
|
59
|
+
(type_identifier))))
|
docs/game.md
CHANGED
|
@@ -334,7 +334,7 @@ A missing file stops the game and names the file, so typos show up straight away
|
|
|
334
334
|
|
|
335
335
|
## Screens
|
|
336
336
|
|
|
337
|
-
A game with more than one screen (a title, a level select, the play) gives each its own `Screen` type, with its own state and its own view; the game finds a screen by its type, so a game has one screen of each type (two of one type stop the program when the game is made: `game: two screens are of the type 'PlayScreen'`). A screen's `name()` is its type's name (`"PlayingScreen"`, `@typeName(Self)` in the trait's default), which `transition(from)`, `showing()` and `wentTo()` give; a screen
|
|
337
|
+
A game with more than one screen (a title, a level select, the play) gives each its own `Screen` type, with its own state and its own view; the game finds a screen by its type, so a game has one screen of each type (two of one type stop the program when the game is made: `game: two screens are of the type 'PlayScreen'`). A screen's `name()` is its type's name (`"PlayingScreen"`, `@typeName(Self)` in the trait's default), which `transition(from)`, `showing()` and `wentTo()` give; the default is `@final`, so a screen that writes its own `name` is a compile error ("PlayScreen.name: 'name' is `@final` in trait Screen, so a type can't write its own: remove it"). What sits over a view (a game over, a pause, a dialog) is not a screen: it is part of the view of the screen it sits on, drawn while the state says so, as Orbit Runner's game over `Overlay`. The keys still go to the screen's subscriptions, so Enter can play again while the game over shows.
|
|
338
338
|
|
|
339
339
|
The first screen of the list shows first. A screen never gets the game: it changes screen with a command (below). A screen says how it comes in with `transition(self, from: Str) -> Transition`: `Cut` (the default), `Fade(secs: 0.5)` or `Slide(from: FromRight, secs: 0.4)`. While a transition runs, the game draws both screens, the one going out and then the one coming in, each on its own `background()`, moved and faded. Only the screen coming in gets ticks, and its pointer events are dropped until the transition is over (a press on a screen still sliding in lands nowhere); keys still come.
|
|
340
340
|
|
|
@@ -433,7 +433,7 @@ What a slice's `update` asks of the game is data, an `enum Cmd` (`std/game/Cmd`)
|
|
|
433
433
|
|
|
434
434
|
| `Cmd` | What the game does |
|
|
435
435
|
|---|---|
|
|
436
|
-
| `Cmd.goTo<OverScreen>()` (a `GoTo
|
|
436
|
+
| `Cmd.goTo<OverScreen>()` (a `GoTo`) | shows the game's screen of that type from the next tick on, as it was left, coming in by its `transition(from)`. It is the only way to make a `GoTo`: the variant is `@std`, so `GoTo(screen: "OverScreen")` outside std is a compile error ("`GoTo` is a `@std` variant of Cmd: only std builds one, so use the static of Cmd that makes it (any file may match it)"); a `GoTo` is matched like any variant. A type that is not a `Screen` is a compile error (`Cmd.goTo<Int>()`: "Int does not implement Screen (the bound of S in Cmd.goTo)"); a screen type the game has none of stops the program and lists the screens (`game: no screen is a 'OverScreen' (the screens are MenuScreen, TurnScreen)`). |
|
|
437
437
|
| `Exit` | no tick runs after this one. |
|
|
438
438
|
| `Undo`, `Redo`, `RewindTo(tick: k)` | once the tick is recorded, a move through the game's history ([Undo and time travel](#undo-and-time-travel)); nothing if the game keeps none |
|
|
439
439
|
| `Play(sound: s, volume: v)`, `Loop(sound: s, volume: v)`, `Stop(sound: s)` | plays the sound once, starts it looping, or stops it (`Sound.Silent`, a test's, calls no host) |
|
|
@@ -524,7 +524,7 @@ The engine has master's shape at e91c40ce (`View` and `Actor`, `Screen` with its
|
|
|
524
524
|
| a replay's ticks and the ticker's in a growable array, read by index | `Replay.ticks: List<Input>`; the `Ticker` replaying holds the ticks not yet played (`played`), its head dropped each tick, with no cursor; the kit's recording is a value too (`t.recorded()`) | a replay is a value: the kit's rig, itself a value, no longer pushes into an array its copies share |
|
|
525
525
|
| an action enum writes its `toStr` for a test's names | `enum PlayAction[Show] = ..`: `[Show]` (std/Str) derives `toStr`, `Steer(1.0, -1.0)` ([language.md](language.md#structs), "Derived methods") | the names a test compares are the variant and its fields; a derive writes them once |
|
|
526
526
|
| `Game` mutated by `update(&self, ..)` | `update(self, io, input, dt) -> Game`, `step(self, io, input, dt, pixels) -> Game` | the game is a value |
|
|
527
|
-
| `Control` (`goTo`, `exit`, `undo`, `redo`, `rewindTo`) handed to an effect | `enum Cmd` (`GoTo`, `Exit`, `Undo`, `Redo`, `RewindTo`, `Play`, `Loop`, `Stop`) returned by `update`; `Cmd.goTo<TurnScreen>()` goes to a screen by its type | commands are values: a test reads them (`t.cmds`), and a sound is one of them; a screen's name is its type's (
|
|
527
|
+
| `Control` (`goTo`, `exit`, `undo`, `redo`, `rewindTo`) handed to an effect | `enum Cmd` (`GoTo`, `Exit`, `Undo`, `Redo`, `RewindTo`, `Play`, `Loop`, `Stop`) returned by `update`; `Cmd.goTo<TurnScreen>()` goes to a screen by its type | commands are values: a test reads them (`t.cmds`), and a sound is one of them; a screen's name is its type's (`name()` is `@final`), and a `GoTo` is made only by `Cmd.goTo<T>()` (the variant is `@std`), so a goTo names a type the compiler checks is a screen, never a string |
|
|
528
528
|
| `rewindTo`, `undo`, `redo`, .. `-> Bool` | `-> Game`, with `game.moved` | the move returns the moved game |
|
|
529
529
|
| the kit's `t.press(k)` (in place) | `u := t.press(k)` | a rig is a value |
|
|
530
530
|
| a view literal's `if`, `for`, `..` elements | `if` and `..` items and children blocks (`Overlay(..) {` + an item a line + `}`); no `for` item: `..xs.map(..)` | a `for` item would be a second way to write a `map` |
|
docs/language.md
CHANGED
|
@@ -287,6 +287,8 @@ primitive Demo[App] =
|
|
|
287
287
|
|
|
288
288
|
A variant's field may have a default, as a struct's may (see [field defaults](#structs)). `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`.
|
|
289
289
|
|
|
290
|
+
A variant marked `@std` (`| @std GoTo(screen: Str)`) is built only by std, through a function std gives for it (`Cmd.goTo<MenuScreen>()`); any file may match it (see [Attributes](#attributes)).
|
|
291
|
+
|
|
290
292
|
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.
|
|
291
293
|
|
|
292
294
|
Enums can be recursive and generic:
|
|
@@ -733,6 +735,8 @@ enum Dot[Shape] =
|
|
|
733
735
|
|
|
734
736
|
A type implements a trait only where the type is declared. A method with a trait method's name but another signature is an error, so a typo can't fall back to the default.
|
|
735
737
|
|
|
738
|
+
A default marked `@final` is every implementer's: a type that writes a method of its name is an error, and so is a subtrait that gives it another default (see [Attributes](#attributes)). std/game's `Screen` has one, `@final fun name(self) -> Str = @typeName(Self)`, so a screen's name is always its type's.
|
|
739
|
+
|
|
736
740
|
**Trait objects.** The trait's name used as a type (`Shape`, `List<Shape>`, `fn(Shape) -> Shape`) holds a value of any type that implements it. On it you can call the trait's methods and nothing else, and each call runs the value's own method or the default:
|
|
737
741
|
|
|
738
742
|
```plum
|
|
@@ -965,6 +969,24 @@ primitive Int =
|
|
|
965
969
|
|
|
966
970
|
It is an error to write `@native` anywhere else: inside an expression, in a block with other statements, in a closure, a constant or a test, or in a file outside std. A `@native` function the compiler has no implementation for is an error at the function.
|
|
967
971
|
|
|
972
|
+
### Attributes
|
|
973
|
+
|
|
974
|
+
An attribute is `@name` before a declaration, and the compiler checks what it says. There are two:
|
|
975
|
+
|
|
976
|
+
| Attribute | On | Means |
|
|
977
|
+
|-----------|----|-------|
|
|
978
|
+
| `@final` | a trait's method with a default: `@final fun name(self) -> Str = @typeName(Self)` | the default is every implementer's: a type that writes a method of that name is an error, and so is a subtrait that gives it another default |
|
|
979
|
+
| `@std` | an enum variant: `\| @std GoTo(screen: Str)` | only std builds the variant, through a function it gives for it (`Cmd.goTo<S>()`); a construction in any other file is an error at it. Matching one is not restricted |
|
|
980
|
+
|
|
981
|
+
The errors, for a screen that writes `fun name(self)` and for `GoTo(screen: "MenuScreen")` outside std:
|
|
982
|
+
|
|
983
|
+
```
|
|
984
|
+
PlayScreen.name: 'name' is `@final` in trait Screen, so a type can't write its own: remove it
|
|
985
|
+
`GoTo` is a `@std` variant of Cmd: only std builds one, so use the static of Cmd that makes it (any file may match it)
|
|
986
|
+
```
|
|
987
|
+
|
|
988
|
+
Any other name, or one on something else (`@final` on a method with no default, `@std` on a trait's method), is an error; a function outside a trait, a struct and a field take none (a syntax error).
|
|
989
|
+
|
|
968
990
|
## Modules
|
|
969
991
|
|
|
970
992
|
Each file is a module. A file starts with its imports. Nothing is implicit, not even `Int` or `Str` methods, and each file imports what it uses.
|
docs/std.md
CHANGED
|
@@ -274,7 +274,7 @@ Tests live in the `tests/` mirror of the code (std's in `tests/std/...`), as the
|
|
|
274
274
|
|
|
275
275
|
## Game screens and slices
|
|
276
276
|
|
|
277
|
-
A game (`std/game/Game`) is a list of screens. A screen (`std/game/Screen`) has its type's name (`name()`,
|
|
277
|
+
A game (`std/game/Game`) is a list of screens. A screen (`std/game/Screen`) has its type's name (`name()`, `@final`, so it can't write its own) and a `view(self) -> List<View>`, what the frame shows, made again from its fields every frame (`std/game/View`: stateless views, the ready-made `Group`, `Box`, `Circle`, `Line`, `Sprite`, `Label`, `Blend` (its children in a blend mode) and `Overlay`, and actors, `Actor[View]`, with `step(self, dt) -> Self`, which a screen steps through its `stepped(dt)`, derived for every screen from its fields holding actors, a `List<View>` among them), and may have a `hud(window)` drawn over it one unit a pixel and a `camera(base)` (`Viewport.lookAt`); a screen with rules is a `ScreenSlice<A>` (`std/game/ScreenSlice`), in the Elm style: its fields are its state, `A` its actions, `update(self, a) -> Next<Self, A>` its one entry point (pure, with no `Io`, so the same actions from the same state give the same state), returning the next screen with what follows: the actions that follow and the commands for the game (`std/game/Cmd`: a sound, `Cmd.goTo<PlayingScreen>()`, which goes to the game's screen of that type and is the only way to make a `GoTo`, a `@std` variant), done after the tick. Its `subscriptions(self) -> List<Sub<A>>` say which of each tick's input (`std/game/Input`: its events, and what is held after them, `Held`, their fold) and which frames become its actions: `OnFrame(|dt| ..)`, `OnKeyDown(key:, act:)`, `OnKeyUp`, `OnHeld(|h| ..)`, `OnWheel`, `OnPointerDown`, `OnPointerUp`, `OnPointerMove`, read once a tick; a press on an item that says what it means, a `Presses<A>` such as a `Button` from `std/game/Button`, is that action by default. The frame is an action: the screen steps its actors in it. std keeps the screen each `update` returns. An actor's motion is a `Body` (`std/game/Body`): `pos`, `vel`, `push`, `drag`, `edge` (`Free`, `Halt(box)`, `Bounce(box)`, `Wrap(box)`, a `Walls`), `angle`, `turn` and `faceAbove`, declared, with `step(dt)` written once in std and `place(origin)` where to draw it; a field holding one is stepped by the screen's derived `stepped` or an actor's `Steps` (any field whose type has `step(self, dt: Float) -> Self`). An actor that lists `Round` (`std/game/Round`) declares its `radius()` and is that circle about its pivot (`Place.pivot`, the point its place turns about), and `a.touches(b)` is whether two round actors overlap; under it, `Vec2.near(other, dist)` (`std/math/Vec2`) is the overlap test of two circles (`a.near(b, ra + rb)`). A run records as a `Replay` (`std/game/Replay`: the seed and a `List<Input>`, one a tick). All of it is in [the game engine](game.md).
|
|
278
278
|
|
|
279
279
|
```plum
|
|
280
280
|
import std/Int
|
std/game/Cmd.plum
CHANGED
|
@@ -21,7 +21,8 @@ import std/game/Screen
|
|
|
21
21
|
# left, coming in by its `transition(from)`. Made by `Cmd.goTo<S>()`, which
|
|
22
22
|
# takes a type that is a `Screen` (another is a compile error) and keeps its
|
|
23
23
|
# name; a type the game has no screen of stops the program and lists the
|
|
24
|
-
# screens.
|
|
24
|
+
# screens. It is the only way to make one: the variant is `@std`, so
|
|
25
|
+
# `GoTo(screen: "..")` outside std is a compile error. Any file may match it.
|
|
25
26
|
# Exit no tick runs after this one.
|
|
26
27
|
# Undo goes back to just before the last user action (docs/game.md, "Undo and time
|
|
27
28
|
# travel"); nothing if there is none, or the game keeps no history
|
|
@@ -36,7 +37,7 @@ import std/game/Screen
|
|
|
36
37
|
# then does its `GoTo`s again and nothing else, so no sound plays twice and no rewind
|
|
37
38
|
# rewinds again.
|
|
38
39
|
enum Cmd =
|
|
39
|
-
| GoTo(screen: Str)
|
|
40
|
+
| @std GoTo(screen: Str)
|
|
40
41
|
| Exit
|
|
41
42
|
| Undo
|
|
42
43
|
| Redo
|
std/game/Screen.plum
CHANGED
|
@@ -54,8 +54,8 @@ import std/game/ScreenSlice
|
|
|
54
54
|
#
|
|
55
55
|
# By convention a screen struct's name ends in `Screen` (`PlayingScreen`).
|
|
56
56
|
#
|
|
57
|
-
# name the name of its type ("PlayingScreen"), which the game finds it by:
|
|
57
|
+
# name the name of its type ("PlayingScreen"), which the game finds it by:
|
|
58
|
-
# screen
|
|
58
|
+
# `@final`, so a screen that writes its own is a compile error.
|
|
59
59
|
# view what it draws, made again each frame from its fields: a list of views
|
|
60
60
|
# (std/game/View) in the world's coordinates, drawn in order (later on
|
|
61
61
|
# top). Empty by default.
|
|
@@ -98,7 +98,7 @@ import std/game/ScreenSlice
|
|
|
98
98
|
# gets ticks, and it gets no pointer events until the transition is over (keys still
|
|
99
99
|
# come).
|
|
100
100
|
trait Screen =
|
|
101
|
-
fun name(self) -> Str = @typeName(Self)
|
|
101
|
+
@final fun name(self) -> Str = @typeName(Self)
|
|
102
102
|
|
|
103
103
|
fun view(self) -> List<View> = Nil
|
|
104
104
|
|
tests/std/game/Cmd.plum
CHANGED
|
@@ -10,12 +10,13 @@ import std/Test
|
|
|
10
10
|
|
|
11
11
|
primitive CmdTest[UnitTest] =
|
|
12
12
|
fun commandsAreValuesThatNameThemselves() =
|
|
13
|
-
cmds: List<Cmd> := [
|
|
13
|
+
cmds: List<Cmd> := [Cmd.goTo<Lobby>(), Exit, Undo, Redo, RewindTo(tick: 12), Play(sound: Sound.Silent, volume: 0.5), Loop(sound: Sound(id: 3), volume: 1.0), Stop(sound: Sound(id: 3))]
|
|
14
|
-
assert Cmd.names(cmds) == "goTo(
|
|
14
|
+
assert Cmd.names(cmds) == "goTo(Lobby) exit undo redo rewindTo(12) play(-1, 0.5) loop(3, 1.0) stop(3)"
|
|
15
15
|
assert cmds.filter(|c| c.travels()).length() == 3
|
|
16
16
|
|
|
17
17
|
# goTo names a screen by its type, which must be a screen (`Cmd.goTo<Int>()` is a compile
|
|
18
|
-
# error: "Int does not implement Screen (the bound of S in Cmd.goTo)")
|
|
18
|
+
# error: "Int does not implement Screen (the bound of S in Cmd.goTo)"); a `GoTo` is only
|
|
19
|
+
# made so (it is `@std`), and matched like any variant
|
|
19
20
|
fun goToNamesAScreenByItsType() =
|
|
20
21
|
assert Cmd.goTo<Lobby>().toStr() == "goTo(Lobby)"
|
|
21
22
|
assert Cmd.names([Cmd.goTo<Lobby>(), Exit]) == "goTo(Lobby) exit"
|