Skip to content

Commit 5615b7c

Browse files
committed
Destructuring: rest patterns, { a, ...rest } and [x, ...rest]
An object rest is Solid's `omit` of the named keys, a live view (an internal `omit` expression in every runner and the crate); an array rest is `.slice(n)`. In a `let`, an object rest is a copy (`{ ...omit(…) }`). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0117BoWP7LmQhib6M9zGnmBH
1 parent f66861a commit 5615b7c

21 files changed

Lines changed: 143 additions & 66 deletions

File tree

‎compiler/src/ast.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,8 @@ pub enum ExprKind {
9090
/// RG-7b
9191
Use(String),
9292
Spread(Box<Expr>),
93+
/// RG-4b: an object rest, `{ a, ...rest } = e` (the parser's own; Solid's `omit`)
94+
Omit { e: Box<Expr>, keys: Vec<String> },
9395
/// R-f-3
9496
Throw(Box<Expr>),
9597
/// R-f-4: `e catch (x: A | B) => alt`; classes absent: every failure
@@ -422,6 +424,7 @@ impl Expr {
422424
ExprKind::Draft { .. } => "draft",
423425
ExprKind::Use(_) => "use",
424426
ExprKind::Spread(_) => "spread",
427+
ExprKind::Omit { .. } => "omit",
425428
ExprKind::Throw(_) => "throw",
426429
ExprKind::Catch { .. } => "catch",
427430
ExprKind::StyleMap { .. } => "stylemap",
@@ -439,6 +442,7 @@ impl Expr {
439442
ExprKind::Un { op, e } => obj(vec![("k", k), ("op", s(op)), ("e", b(e))]),
440443
ExprKind::Pre { name, init } => obj(vec![("k", k), ("name", s(name)), ("init", ob(init))]),
441444
ExprKind::Peek(e) | ExprKind::Latest(e) | ExprKind::Pending(e) | ExprKind::Spread(e) | ExprKind::Throw(e) => obj(vec![("k", k), ("e", b(e))]),
445+
ExprKind::Omit { e, keys } => obj(vec![("k", k), ("e", b(e)), ("keys", Some(strs(keys)))]),
442446
ExprKind::Await { e, init, stream } => obj(vec![("k", k), ("e", b(e)), ("init", ob(init)), ("stream", Some(Value::Bool(*stream)))]),
443447
ExprKind::If { c, t, f } => obj(vec![("k", k), ("c", b(c)), ("t", b(t)), ("f", b(f))]),
444448
ExprKind::Tpl(parts) => obj(vec![

‎compiler/src/check.rs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -353,7 +353,7 @@ pub(crate) fn children<'a>(n: Node<'a>, paths: bool) -> Vec<Node<'a>> {
353353
Node::E(e) => match &e.k {
354354
ExprKind::Lit(_) | ExprKind::Id(_) | ExprKind::Use(_) | ExprKind::StyleMap { .. } => {}
355355
ExprKind::Bin { l, r, .. } => out.extend([Node::E(l), Node::E(r)]),
356-
ExprKind::Un { e, .. } | ExprKind::Peek(e) | ExprKind::Latest(e) | ExprKind::Pending(e) | ExprKind::Spread(e) | ExprKind::Throw(e) => out.push(Node::E(e)),
356+
ExprKind::Un { e, .. } | ExprKind::Peek(e) | ExprKind::Latest(e) | ExprKind::Pending(e) | ExprKind::Spread(e) | ExprKind::Omit { e, .. } | ExprKind::Throw(e) => out.push(Node::E(e)),
357357
ExprKind::Pre { init, .. } => out.extend(init.iter().map(|x| Node::E(x))),
358358
ExprKind::Await { e, init, .. } => {
359359
out.push(Node::E(e));
@@ -438,7 +438,7 @@ fn free_names(e: &Expr, bound: &HashSet<String>, out: &mut IndexSet<String>) {
438438
go(i, out);
439439
}
440440
}
441-
ExprKind::Latest(x) | ExprKind::Pending(x) | ExprKind::Un { e: x, .. } | ExprKind::Spread(x) => go(x, out),
441+
ExprKind::Latest(x) | ExprKind::Pending(x) | ExprKind::Un { e: x, .. } | ExprKind::Spread(x) | ExprKind::Omit { e: x, .. } => go(x, out),
442442
ExprKind::Bin { l, r, .. } => {
443443
go(l, out);
444444
go(r, out);
@@ -2051,7 +2051,7 @@ impl<'a> Checker<'a> {
20512051
self.expr(x, env, ctx, None);
20522052
self.model.probe = save;
20532053
}
2054-
ExprKind::Un { e: x, .. } | ExprKind::Spread(x) => self.expr(x, env, ctx, None),
2054+
ExprKind::Un { e: x, .. } | ExprKind::Spread(x) | ExprKind::Omit { e: x, .. } => self.expr(x, env, ctx, None),
20552055
ExprKind::Await { e: inner, init, .. } => {
20562056
if ctx.imperative && !self.stmt_awaits.contains(&(e as *const Expr)) {
20572057
let sh = show(e);

‎compiler/src/emit.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1178,6 +1178,8 @@ impl<'p> Gen<'p> {
11781178
rtc("preOr", vec![call(id(p), vec![]), thunk(i)])
11791179
}
11801180
ExprKind::Peek(x) => rtc("untrack", vec![thunk(self.expr(x, env, &sub)?)]),
1181+
// RG-4b: Solid's live view
1182+
ExprKind::Omit { e: x, keys } => rtc("omit", std::iter::once(self.expr(x, env, &sub)).chain(keys.iter().map(|k| Ok(str(k.clone())))).collect::<Result<Vec<_>, _>>()?),
11811183
ExprKind::Await { e: x, stream, .. } => {
11821184
if let Some(v) = self.hoisted.get(&(e as *const Expr)) {
11831185
return Ok(call(id(v.clone()), vec![]));

‎compiler/src/infer.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -271,7 +271,7 @@ impl Walker {
271271
self.read(l, st, sh, local, depth);
272272
self.read(r, st, sh, local, depth);
273273
}
274-
ExprKind::Un { e, .. } | ExprKind::Spread(e) | ExprKind::Throw(e) => self.read(e, st, sh, local, depth),
274+
ExprKind::Un { e, .. } | ExprKind::Spread(e) | ExprKind::Omit { e, .. } | ExprKind::Throw(e) => self.read(e, st, sh, local, depth),
275275
ExprKind::Await { e, init, .. } => {
276276
self.read(e, st, sh, local, depth);
277277
if let Some(i) = init {
@@ -362,7 +362,7 @@ impl Walker {
362362
self.deps(l, st, sh, out);
363363
self.deps(r, st, sh, out);
364364
}
365-
ExprKind::Un { e, .. } | ExprKind::Spread(e) | ExprKind::Throw(e) => self.deps(e, st, sh, out),
365+
ExprKind::Un { e, .. } | ExprKind::Spread(e) | ExprKind::Omit { e, .. } | ExprKind::Throw(e) => self.deps(e, st, sh, out),
366366
ExprKind::If { c, t, f } => {
367367
self.deps(c, st, sh, out);
368368
self.deps(t, st, sh, out);

‎compiler/src/parse.rs‎

Lines changed: 45 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -536,11 +536,27 @@ fn params_typed(c: &mut Cursor) -> R<(Vec<String>, Vec<Option<String>>)> {
536536
Ok((params, ptypes))
537537
}
538538

539-
/// RG-4b, 07 §5: a destructuring pattern, `{ a, b: c, d = 1, e: { f } }` or `[a, , b]`. Rest (`...r`) is not yet.
539+
/// RG-4b, 07 §5: a destructuring pattern, `{ a, b: c, d = 1, e: { f }, ...rest }` or `[a, , b, ...rest]`.
540540
enum Pat {
541541
Name { name: String, line: usize, span: Span },
542-
Obj(Vec<(String, Pat, Option<Expr>)>),
543-
Arr(Vec<Option<(Pat, Option<Expr>)>>),
542+
Obj(Vec<(String, Pat, Option<Expr>)>, Option<Box<Pat>>),
543+
Arr(Vec<Option<(Pat, Option<Expr>)>>, Option<Box<Pat>>),
544+
}
545+
/// `...name`, the last element of a pattern closed by `close`.
546+
fn parse_rest(c: &mut Cursor, close: &str) -> R<Pat> {
547+
c.i += 3;
548+
c.ws(true);
549+
let (line, start) = (c.line(), c.i);
550+
let name = match c.ident() {
551+
Some(n) if !is_kw(&n) => n,
552+
_ => return c.fail("a name for the rest"),
553+
};
554+
let span = Span::new(start, c.i);
555+
c.ws(true);
556+
if !c.starts_with(close) {
557+
return c.fail(&format!("a rest element is last, with no default: `...{name}{close}`"));
558+
}
559+
Ok(Pat::Name { name, line, span })
544560
}
545561
fn pat_default(c: &mut Cursor) -> R<Option<Expr>> {
546562
if c.peek() == '=' && c.peek_at(1) != '=' && c.peek_at(1) != '>' {
@@ -560,7 +576,9 @@ fn parse_pattern(c: &mut Cursor) -> R<Pat> {
560576
break;
561577
}
562578
if c.starts_with("...") {
563-
return c.fail("RG-4b: a rest pattern (`...rest`) is not supported yet: name the fields, or read them from the value");
579+
let rest = parse_rest(c, "}")?;
580+
c.expect("}")?;
581+
return Ok(Pat::Obj(props, Some(Box::new(rest))));
564582
}
565583
let (kline, kstart) = (c.line(), c.i);
566584
let key = c.ident_or("a field name")?;
@@ -577,7 +595,7 @@ fn parse_pattern(c: &mut Cursor) -> R<Pat> {
577595
}
578596
c.ws(true);
579597
c.expect("}")?;
580-
return Ok(Pat::Obj(props));
598+
return Ok(Pat::Obj(props, None));
581599
}
582600
if c.eat("[") {
583601
let mut items = vec![];
@@ -592,7 +610,9 @@ fn parse_pattern(c: &mut Cursor) -> R<Pat> {
592610
continue;
593611
}
594612
if c.starts_with("...") {
595-
return c.fail("RG-4b: a rest pattern (`...rest`) is not supported yet: name the items, or read them from the value");
613+
let rest = parse_rest(c, "]")?;
614+
c.expect("]")?;
615+
return Ok(Pat::Arr(items, Some(Box::new(rest))));
596616
}
597617
let pat = parse_pattern(c)?;
598618
c.ws(true);
@@ -605,7 +625,7 @@ fn parse_pattern(c: &mut Cursor) -> R<Pat> {
605625
}
606626
c.ws(true);
607627
c.expect("]")?;
608-
return Ok(Pat::Arr(items));
628+
return Ok(Pat::Arr(items, None));
609629
}
610630
let (line, start) = (c.line(), c.i);
611631
let name = c.ident();
@@ -615,8 +635,9 @@ fn parse_pattern(c: &mut Cursor) -> R<Pat> {
615635
}
616636
}
617637
/// Each name a pattern binds, with its projection of `base` (a default applies when the field is `undefined`, as in JS).
618-
/// The projections are the parser's own: they have no span (CP-8).
619-
fn expand_pattern(pat: &Pat, base: Expr, out: &mut Vec<(String, Expr, usize, Span)>) {
638+
/// The projections are the parser's own: they have no span (CP-8). An object rest is `omit` of the named keys: Solid's
639+
/// live view in reactive scope, a copy of it when `snap` (a `let`).
640+
fn expand_pattern(pat: &Pat, base: Expr, out: &mut Vec<(String, Expr, usize, Span)>, snap: bool) {
620641
let syn = |k: ExprKind| Expr::new(k, Span::NONE);
621642
let dfl = |v: Expr, d: &Option<Expr>| match d {
622643
Some(d) => syn(ExprKind::If {
@@ -628,19 +649,27 @@ fn expand_pattern(pat: &Pat, base: Expr, out: &mut Vec<(String, Expr, usize, Spa
628649
};
629650
match pat {
630651
Pat::Name { name, line, span } => out.push((name.clone(), base, *line, *span)),
631-
Pat::Obj(props) => {
652+
Pat::Obj(props, rest) => {
632653
for (key, p, d) in props {
633654
let v = syn(ExprKind::Member { o: Box::new(base.clone()), p: key.clone(), opt: false });
634-
expand_pattern(p, dfl(v, d), out);
655+
expand_pattern(p, dfl(v, d), out, snap);
656+
}
657+
if let Some(r) = rest {
658+
let o = syn(ExprKind::Omit { e: Box::new(base.clone()), keys: props.iter().map(|(k, _, _)| k.clone()).collect() });
659+
expand_pattern(r, if snap { syn(ExprKind::Rec(vec![Field::Spread(o)])) } else { o }, out, snap);
635660
}
636661
}
637-
Pat::Arr(items) => {
662+
Pat::Arr(items, rest) => {
638663
for (i, it) in items.iter().enumerate() {
639664
if let Some((p, d)) = it {
640665
let v = syn(ExprKind::Index { o: Box::new(base.clone()), i: Box::new(syn(ExprKind::Lit(Lit::Num(i as f64)))), opt: false });
641-
expand_pattern(p, dfl(v, d), out);
666+
expand_pattern(p, dfl(v, d), out, snap);
642667
}
643668
}
669+
if let Some(r) = rest {
670+
let f = syn(ExprKind::Member { o: Box::new(base.clone()), p: "slice".into(), opt: false });
671+
expand_pattern(r, syn(ExprKind::Call { f: Box::new(f), args: vec![syn(ExprKind::Lit(Lit::Num(items.len() as f64)))] }), out, snap);
672+
}
644673
}
645674
}
646675
}
@@ -707,7 +736,7 @@ fn parse_destructuring_decl(c: &mut Cursor) -> R<Vec<Decl>> {
707736
base = Expr::new(ExprKind::Id(t), Span::NONE);
708737
}
709738
let mut names = vec![];
710-
expand_pattern(&pat, base, &mut names);
739+
expand_pattern(&pat, base, &mut names, false);
711740
for (name, e, line, span) in names {
712741
out.push(Decl::Eq { name, e, line, span, deferred: false, key: None, ty: None, exported: false });
713742
}
@@ -1038,7 +1067,7 @@ fn parse_decl_at(c: &mut Cursor) -> R<Decl> {
10381067
let (mut decls, view) = parse_block_body(c)?;
10391068
if let Some(sig) = &sig {
10401069
let mut names = vec![];
1041-
expand_pattern(sig, Expr::new(ExprKind::Id(props.clone()), Span::NONE), &mut names);
1070+
expand_pattern(sig, Expr::new(ExprKind::Id(props.clone()), Span::NONE), &mut names, false);
10421071
let pre: Vec<Decl> = names.into_iter().map(|(name, e, line, span)| Decl::Eq { name, e, line, span, deferred: false, key: None, ty: None, exported: false }).collect();
10431072
decls.splice(0..0, pre);
10441073
}
@@ -1164,7 +1193,7 @@ fn parse_stmt(c: &mut Cursor) -> R<Stmt> {
11641193
base = Expr::new(ExprKind::Id(t), Span::NONE);
11651194
}
11661195
let mut names = vec![];
1167-
expand_pattern(&pat, base, &mut names);
1196+
expand_pattern(&pat, base, &mut names, true);
11681197
for (name, e, _, span) in names {
11691198
out.push(Stmt { k: StmtKind::Let { name, e, ty: None }, span });
11701199
}

‎compiler/src/prelude.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ export declare function eq<T>(v: T, ok: Async<T> extends true ? "MISSING_AWAIT:
99
export declare function first<T, I>(v: T, init: I): T | I;
1010
export declare function pre<T>(init?: T): T;
1111
export declare function pending(v: unknown): boolean;
12+
/** RG-4b: an object rest, \`{ a, ...rest } = e\` (Solid's \`omit\`). */
13+
export declare function omit<T, K extends string>(v: T, ...keys: K[]): Omit<T, K>;
1214
export declare function caught<T, R>(v: T, alt: (e: any) => R): T | R;
1315
export declare function raise(e: unknown): never;
1416
/** W-1/W-6: a write checks its value (or its function of the slot) against the target — whose type alone decides it. */

‎compiler/src/project.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -803,6 +803,10 @@ impl Proj<'_> {
803803
Code::of("({ ").c(Code::join(fs, ", ")).t(" })")
804804
}
805805
ExprKind::Spread(x) => Code::of("...").c(go!(x)),
806+
ExprKind::Omit { e: x, keys } => {
807+
let ks: String = keys.iter().map(|k| format!(", {}", js_str(k))).collect();
808+
Code::of("__.omit(").c(go!(x)).t(&ks).t(")")
809+
}
806810
ExprKind::Fn { params, body, stmts } => {
807811
let mut from = sp.start as usize;
808812
let ps = Code::join(params.iter().map(|p| self.name(p, sp, &mut from)).collect(), ", ");

‎compiler/src/spans.rs‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -128,8 +128,8 @@ impl Spans<'_> {
128128
let at = e.span;
129129
if !self.inside(at, parent, e.kind()) {
130130
// the expressions the parser makes: a statement-bodied arrow's `body`, and a destructured name's projection
131-
// (RG-4b: `.field`, `[i]`, the default's `=== undefined ? d : v`, the right side's temp or `props`)
132-
if !matches!(e.k, ExprKind::Lit(Lit::Undefined) | ExprKind::Lit(Lit::Num(_)) | ExprKind::Member { .. } | ExprKind::Index { .. } | ExprKind::If { .. } | ExprKind::Bin { .. } | ExprKind::Id(_)) {
131+
// (RG-4b: `.field`, `[i]`, the default's `=== undefined ? d : v`, the right side's temp or `props`, a rest's `omit`, `.slice(n)` or `{ ...omit }`)
132+
if !matches!(e.k, ExprKind::Lit(Lit::Undefined) | ExprKind::Lit(Lit::Num(_)) | ExprKind::Member { .. } | ExprKind::Index { .. } | ExprKind::If { .. } | ExprKind::Bin { .. } | ExprKind::Id(_) | ExprKind::Omit { .. } | ExprKind::Call { .. } | ExprKind::Rec(_)) {
133133
self.bad(parent, format!("a {} expression has no span", e.kind()));
134134
}
135135
return;
@@ -150,7 +150,7 @@ impl Spans<'_> {
150150
sub(l);
151151
sub(r);
152152
}
153-
ExprKind::Un { e, .. } | ExprKind::Peek(e) | ExprKind::Latest(e) | ExprKind::Pending(e) | ExprKind::Spread(e) | ExprKind::Throw(e) => sub(e),
153+
ExprKind::Un { e, .. } | ExprKind::Peek(e) | ExprKind::Latest(e) | ExprKind::Pending(e) | ExprKind::Spread(e) | ExprKind::Omit { e, .. } | ExprKind::Throw(e) => sub(e),
154154
ExprKind::Pre { init, .. } => init.iter().for_each(|x| sub(x)),
155155
ExprKind::Await { e, init, .. } => {
156156
sub(e);
@@ -353,7 +353,7 @@ pub fn walk(p: &Program, f: &mut dyn FnMut(Span)) {
353353
match &e.k {
354354
ExprKind::Lit(_) | ExprKind::Id(_) | ExprKind::Use(_) | ExprKind::StyleMap { .. } => {}
355355
ExprKind::Bin { l, r, .. } => sub.extend([&**l, &**r]),
356-
ExprKind::Un { e, .. } | ExprKind::Peek(e) | ExprKind::Latest(e) | ExprKind::Pending(e) | ExprKind::Spread(e) | ExprKind::Throw(e) => sub.push(e),
356+
ExprKind::Un { e, .. } | ExprKind::Peek(e) | ExprKind::Latest(e) | ExprKind::Pending(e) | ExprKind::Spread(e) | ExprKind::Omit { e, .. } | ExprKind::Throw(e) => sub.push(e),
357357
ExprKind::Pre { init, .. } => sub.extend(init.iter().map(|x| &**x)),
358358
ExprKind::Await { e, init, .. } => sub.extend(std::iter::once(&**e).chain(init.iter().map(|x| &**x))),
359359
ExprKind::If { c, t, f } => sub.extend([&**c, &**t, &**f]),

‎guide/language.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,8 @@ type Item = { id: number; name: string }
3737

3838
There is no `let` at the top level or in a component: a value that changes is a `source`, and one computed from
3939
others is an equation. Bare `x = e` is always an equation and `let x = e` (in imperative code) always a snapshot, as
40-
in JS; that holds for destructuring too. Mutation is only `:=` and `guess`. Destructuring has no rest (`...r`) yet. Equations are lazy and exact: an arm of `c ? a : b` that isn't taken isn't evaluated.
40+
in JS; that holds for destructuring too. Mutation is only `:=` and `guess`. A rest, `{ id, ...rest } = props`, is the other fields
41+
(Solid's `omit`) and keeps updating too. Equations are lazy and exact: an arm of `c ? a : b` that isn't taken isn't evaluated.
4142

4243
## Expressions
4344

‎ref/compile/emit.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -452,6 +452,7 @@ class Gen {
452452
case "un": return `(${e.op}${go(e.e)})`;
453453
case "draft": throw new CompileError("a draft is an equation's whole expression");
454454
case "spread": throw new CompileError("spread outside an array literal");
455+
case "omit": return `__rt.omit(${[go(e.e), ...e.keys.map(k => J(k))].join(", ")})`; // RG-4b: Solid's live view
455456
}
456457
}
457458
private ref(name: string, env: Env, ctx: Ctx): string {

0 commit comments

Comments
 (0)