Skip to content

Commit ea67d8c

Browse files
authored
Merge pull request #57 from solidjs/claude/project-thread-5liu5g
MO-10: use Solid libraries from .rx (spec + ref + crate)
2 parents 129f318 + 0b30229 commit ea67d8c

20 files changed

Lines changed: 880 additions & 28 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,14 @@
11
# Changelog
22

3+
## Unreleased
4+
5+
**New**
6+
7+
- Solid libraries (MO-10): declare a primitive once in a `.d.rx` (`export pure fn createToggle(v: boolean): [ref
8+
boolean, (v: boolean) => void]`) and use it like .rx: it is called once, `ref` arguments go in as accessors, readers
9+
are read without a call, and setters are io. A package's `.d.rx` sits beside the file its import resolves to.
10+
`guide/libraries.md`.
11+
312
## 0.2.0
413

514
`@reactivescript/compiler`, `@reactivescript/runtime`, `@reactivescript/language-server` and the editor extension,

‎compiler/src/check.rs‎

Lines changed: 74 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,11 @@ use crate::content::{misnested, misnested_inside, Shape, P_CLOSERS, P_SCOPE};
1111
use crate::infer::{inferred_action, run_findings, trigger_text, Code};
1212
use crate::model::{ModelBuilder, ModelSymbol};
1313
use crate::modules::ModuleSet;
14-
use crate::parse::{js_trim, JsDecl};
14+
use crate::parse::{js_trim, JsDecl, Part, Shape as FShape};
1515
use crate::signature::{Catch, CompSig, ExportSig, ModSig, Own, PropSig, SigParam, HOLD};
1616
use indexmap::{IndexMap, IndexSet};
1717
use regex::Regex;
18+
use std::cell::Cell;
1819
use std::collections::{HashMap, HashSet};
1920
use std::sync::LazyLock;
2021

@@ -238,6 +239,10 @@ struct Sym<'a> {
238239
server_rejects: Option<ServerRejects<'a>>,
239240
fn_decl: Option<&'a Decl>,
240241
decl_env: Option<EId>,
242+
/// MO-10: a declared JS primitive (a fn) or an instance of one, or a part of it (an equation): what its result is
243+
foreign: Option<FShape>,
244+
/// MO-10d: bound from a foreign accessor — it may hold, as a question's reader does
245+
reader: bool,
241246
}
242247
impl<'a> Sym<'a> {
243248
fn new(kind: SymKind, name: &str, region: RId, line: i64) -> Self {
@@ -271,6 +276,8 @@ impl<'a> Sym<'a> {
271276
server_rejects: None,
272277
fn_decl: None,
273278
decl_env: None,
279+
foreign: None,
280+
reader: false,
274281
}
275282
}
276283
}
@@ -834,6 +841,8 @@ pub struct Opts<'a> {
834841
}
835842

836843
pub struct Checker<'a> {
844+
/// MO-10d: CN-3e asks what may hold, where a foreign reader counts (R-8 asks what may be absent, where it does not)
845+
holds_mode: Cell<bool>,
837846
pub diags: Vec<Diagnostic>,
838847
pub model: ModelBuilder,
839848
opts: Opts<'a>,
@@ -913,6 +922,7 @@ pub fn check_modules(set: &ModuleSet, spa: bool) -> Checked {
913922
impl<'a> Checker<'a> {
914923
pub fn new(opts: Opts<'a>) -> Self {
915924
Checker {
925+
holds_mode: Cell::new(false),
916926
diags: vec![],
917927
model: ModelBuilder::default(),
918928
opts,
@@ -1201,6 +1211,7 @@ impl<'a> Checker<'a> {
12011211
}
12021212
}
12031213
}
1214+
self.foreign_part(&mut sym, e, env);
12041215
if let Some(sf) = unwrap_server(e) {
12051216
sym.kind = SymKind::Server;
12061217
if let ExprKind::ServerFn { params, .. } = &sf.k {
@@ -1417,7 +1428,22 @@ impl<'a> Checker<'a> {
14171428
self.bind(env, alias, Sym::new(SymKind::ErrClass, alias, region, line));
14181429
continue;
14191430
}
1420-
JsDecl::Fn { pure: xpure, side: xside, rejects, .. } => {
1431+
JsDecl::Fn { pure: xpure, side: xside, rejects, params: xparams, refs, shape, instantiates, .. } => {
1432+
if *instantiates {
1433+
// MO-10a: a primitive is an instantiation (RG-6)
1434+
if *pure && !xpure {
1435+
self.err("IMPORT_ROW_MISMATCH", "MO-8", format!("{} is declared io in {} (`export fn`, not `export pure fn`); `pure` on the import cannot lower it", name, file));
1436+
}
1437+
let mut s = Sym::new(SymKind::Fn, alias, region, line);
1438+
s.params = Some(xparams.iter().enumerate().map(|(i, n)| SigParam { name: n.clone(), r#ref: refs.get(i).copied().unwrap_or(false), ty: None }).collect());
1439+
s.instantiating = true;
1440+
s.foreign = Some(shape.clone());
1441+
s.rows = Some(RowsT::Fixed(IndexSet::new()));
1442+
s.fails_t = Some(FailsT::Fixed(IndexSet::new()));
1443+
s.rejects = Some(IndexSet::new());
1444+
self.bind(env, alias, s);
1445+
continue;
1446+
}
14211447
if *pure && !xpure {
14221448
self.err("IMPORT_ROW_MISMATCH", "MO-8", format!("{} is declared io in {} (`export fn`, not `export pure fn`); `pure` on the import cannot lower it", name, file));
14231449
}
@@ -1440,6 +1466,39 @@ impl<'a> Checker<'a> {
14401466
}
14411467
}
14421468

1469+
/// MO-10b: an equation bound from a primitive's result, or from a part of it (`[a, b] = f(…)`, `x.k`): a `ref` part is
1470+
/// a reader (it may hold, MO-10d), a function part is io (R-io-3), anything else is a value.
1471+
fn foreign_part(&self, sym: &mut Sym<'a>, e: &Expr, env: EId) {
1472+
let shape: Option<FShape> = match &e.k {
1473+
ExprKind::Call { f, .. } => match &f.k {
1474+
ExprKind::Id(n) => self.lookup(env, n).and_then(|t| if self.syms[t].kind == SymKind::Fn { self.syms[t].foreign.clone() } else { None }),
1475+
_ => None,
1476+
},
1477+
ExprKind::Index { o, i, .. } => match (&o.k, &i.k) {
1478+
(ExprKind::Id(on), ExprKind::Lit(Lit::Num(v))) => match self.lookup(env, on).and_then(|t| self.syms[t].foreign.clone()) {
1479+
Some(FShape::Items(items)) if *v >= 0.0 && v.fract() == 0.0 => items.get(*v as usize).map(|p| FShape::Part(*p)),
1480+
_ => None,
1481+
},
1482+
_ => None,
1483+
},
1484+
ExprKind::Member { o, p, .. } => match &o.k {
1485+
ExprKind::Id(on) => match self.lookup(env, on).and_then(|t| self.syms[t].foreign.clone()) {
1486+
Some(FShape::Fields(fields)) => fields.iter().find(|f| &f.0 == p).map(|f| FShape::Part(f.1)),
1487+
_ => None,
1488+
},
1489+
_ => None,
1490+
},
1491+
_ => None,
1492+
};
1493+
let Some(shape) = shape else { return };
1494+
if shape == FShape::Part(Part::Fn) {
1495+
sym.io = true;
1496+
}
1497+
if shape == FShape::Part(Part::Ref) {
1498+
sym.reader = true;
1499+
}
1500+
sym.foreign = Some(shape);
1501+
}
14431502
/// MO-3: this module's signature — every export as an importer sees it.
14441503
pub fn signature(&mut self, p: &'a Program) -> ModSig {
14451504
let mut exports = IndexMap::new();
@@ -3225,6 +3284,15 @@ impl<'a> Checker<'a> {
32253284
if let Some(&b) = memo.get(&s) {
32263285
return b;
32273286
}
3287+
if self.holds_mode.get() {
3288+
// MO-10: a reader may hold; a primitive's other parts are bound as they are
3289+
if self.syms[s].reader {
3290+
return true;
3291+
}
3292+
if matches!(self.syms[s].foreign, Some(FShape::Part(Part::Fn | Part::Value))) {
3293+
return false;
3294+
}
3295+
}
32283296
let Some((e, env)) = self.syms[s].expr else { return false };
32293297
if !busy.insert(s) {
32303298
return false;
@@ -3388,7 +3456,10 @@ impl<'a> Checker<'a> {
33883456
ExprKind::Id(name) => {
33893457
if let Some(t) = self.lookup(env, name) {
33903458
if matches!(self.syms[t].kind, SymKind::Eq | SymKind::Source) && busy.insert(t) {
3391-
if self.absent(t, &mut HashMap::new(), &mut HashSet::new()) {
3459+
self.holds_mode.set(true);
3460+
let held = self.absent(t, &mut HashMap::new(), &mut HashSet::new());
3461+
self.holds_mode.set(false);
3462+
if held {
33923463
out.push(t);
33933464
}
33943465
if let Some((te, tenv)) = self.syms[t].expr {

‎compiler/src/emit.rs‎

Lines changed: 104 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ use crate::awaits::{is_handler, non_tail_awaits, view_readers};
99
use crate::check::{children, unwrap_server, Node};
1010
use crate::js::*;
1111
use crate::modules::ModuleSet;
12+
use crate::parse::{JsDecl, Part, Shape as FShape};
1213
use crate::signature::ExportSig;
1314
use indexmap::{IndexMap, IndexSet};
1415
use serde_json::Value;
@@ -41,6 +42,8 @@ enum Kind {
4142
Val,
4243
Fn,
4344
Ifn,
45+
/// MO-10: a declared JS primitive
46+
Jfn,
4447
Act,
4548
Comp,
4649
}
@@ -58,9 +61,12 @@ struct Bind {
5861
prev: Option<String>,
5962
/// `client` JS (12 SF-5b)
6063
client: bool,
64+
/// MO-10: a primitive's result (Jfn), or an instance's (with `inst`, the name of its raw result)
65+
shape: Option<FShape>,
66+
inst: Option<String>,
6167
}
6268
fn bind(kind: Kind, js: impl Into<String>) -> Bind {
63-
Bind { kind, js: js.into(), w: None, f: None, prev: None, client: false }
69+
Bind { kind, js: js.into(), w: None, f: None, prev: None, client: false, shape: None, inst: None }
6470
}
6571
fn val(js: impl Into<String>) -> Bind {
6672
bind(Kind::Val, js)
@@ -254,6 +260,11 @@ struct Gen<'p> {
254260
style_ids: u32,
255261
}
256262

263+
/// MO-10: the scenario prelude's `./prims`, a JS module of Solid primitives (`ref/compile/prims-solid.ts`).
264+
fn is_prims(from: &str) -> bool {
265+
from == "prims" || from == "prims.js" || from.ends_with("/prims") || from.ends_with("/prims.js")
266+
}
267+
257268
impl<'p> Gen<'p> {
258269
/// A JS import that becomes a real ES import (MO-8): a package's always; a relative one too when the modules go to a
259270
/// bundler (`by_source`, the product), where `./util.js` is the app's own file. `./api` stays the app's injected API
@@ -608,8 +619,17 @@ impl<'p> Gen<'p> {
608619
for d in decls {
609620
match d {
610621
Decl::Import { resolved: Some(_), .. } => {}
611-
Decl::Import { names, side, declared_side, .. } => {
622+
Decl::Import { names, side, declared_side, declared, .. } => {
612623
for n in names {
624+
// MO-10a: a declared primitive
625+
let x = declared.as_ref().and_then(|dp| self.set.declarations.get(dp)).and_then(|ds| ds.iter().find(|y| y.name() == n.name));
626+
if let Some(JsDecl::Fn { params, refs, shape, instantiates: true, .. }) = x {
627+
let mut b = bind(Kind::Jfn, mg(&n.alias));
628+
b.f = Some(FnRef { params: params.iter().enumerate().map(|(i, p)| (p.clone(), refs.get(i).copied().unwrap_or(false))).collect(), decl: None });
629+
b.shape = Some(shape.clone());
630+
self.set(env, &n.alias, b);
631+
continue;
632+
}
613633
let mut b = val(mg(&n.alias));
614634
b.client = *side == Some(crate::ast::Side::Client)
615635
|| declared_side.as_ref().is_some_and(|ds| ds.iter().any(|(k, s)| *k == n.name && *s == crate::ast::Side::Client));
@@ -634,6 +654,14 @@ impl<'p> Gen<'p> {
634654
Decl::Eq { name, e, .. } if unwrap_server(e).is_some() => self.set(env, name, val(mg(name))),
635655
Decl::Eq { name, e, deferred, .. } => {
636656
let mut b = bind(Kind::Acc, mg(name));
657+
if let ExprKind::Call { f, .. } = &e.k {
658+
if let ExprKind::Id(fname) = &f.k {
659+
if let Some(jf) = self.lookup(env, fname).filter(|x| x.kind == Kind::Jfn) {
660+
b.inst = Some(format!("r${name}"));
661+
b.shape = jf.shape.clone();
662+
}
663+
}
664+
}
637665
if self.guessed_eq(name, e, *deferred) {
638666
b.w = Some(format!("w${name}"));
639667
}
@@ -658,6 +686,9 @@ impl<'p> Gen<'p> {
658686
dot(id("__B"), name)
659687
} else if from.ends_with("/api") {
660688
rtc("api", vec![str(name.clone())])
689+
} else if is_prims(from) {
690+
// MO-10: the scenario prelude's Solid primitives
691+
rtc("prim", vec![str(name.clone())])
661692
} else {
662693
return fail(format!("{name} from \"{from}\" is not in the scenario prelude"));
663694
};
@@ -1001,6 +1032,9 @@ impl<'p> Gen<'p> {
10011032
}
10021033
}
10031034
}
1035+
if let Some(fx) = self.foreign(e, env, &b)? {
1036+
return fin(fx, self);
1037+
}
10041038
if let Some(k) = key {
10051039
let x = self.expr(e, env, &Ctx { tail: true, ..Ctx::default() })?;
10061040
return fin(vec![konst(b.js.clone(), rtc("keyed", vec![str(name.clone()), str(k.clone()), thunk(x)]))], self);
@@ -1133,6 +1167,74 @@ impl<'p> Gen<'p> {
11331167
body.push(S::Return(Some(t)));
11341168
Ok(S::Func(Func { name: Some(mg(name)), params: ps, directives: vec![], body, is_async: false, generator: false }))
11351169
}
1170+
/// MO-10: `x = f(…)` over a declared primitive — called once (RG-6), a ref argument as an accessor, a value one
1171+
/// untracked; and `y = x[i]` / `x.k` over its result. A `ref` part is bound to the accessor itself, any other part to
1172+
/// its value.
1173+
fn foreign(&mut self, e: &Expr, env: Env, b: &Bind) -> R<Option<Vec<S>>> {
1174+
fn part(r: E, p: Part) -> E {
1175+
if p == Part::Ref {
1176+
r
1177+
} else {
1178+
thunk(r)
1179+
}
1180+
}
1181+
let ix = |r: &str, k: E| E::Index(Box::new(id(r)), Box::new(k), false);
1182+
match &e.k {
1183+
ExprKind::Call { f, args } => {
1184+
let ExprKind::Id(fname) = &f.k else { return Ok(None) };
1185+
let Some(fb) = self.lookup(env, fname).filter(|x| x.kind == Kind::Jfn) else { return Ok(None) };
1186+
let refs: Vec<bool> = fb.f.as_ref().unwrap().params.iter().map(|p| p.1).collect();
1187+
let mut out = vec![];
1188+
for (i, a) in args.iter().enumerate() {
1189+
if !refs.get(i).copied().unwrap_or(false) {
1190+
out.push(rtc("untrack", vec![thunk(self.expr(a, env, &reactive())?)]));
1191+
continue;
1192+
}
1193+
if let ExprKind::Id(n) = &a.k {
1194+
if let Some(ab) = self.lookup(env, n).filter(|ab| matches!(ab.kind, Kind::Acc | Kind::Src)) {
1195+
out.push(id(ab.js));
1196+
continue;
1197+
}
1198+
}
1199+
out.push(rtc("memo", vec![E::Null, thunk(self.expr(a, env, &reactive())?)]));
1200+
}
1201+
let r = b.inst.clone().unwrap();
1202+
let whole = match fb.shape.as_ref().unwrap() {
1203+
FShape::Part(p) => part(id(r.clone()), *p),
1204+
FShape::Items(items) => rtc(
1205+
"memo",
1206+
vec![E::Null, thunk(E::Arr(items.iter().enumerate().map(|(i, p)| { let x = ix(&r, E::Num(i as f64)); if *p == Part::Ref { call(x, vec![]) } else { x } }).collect()))],
1207+
),
1208+
FShape::Fields(fields) => rtc(
1209+
"memo",
1210+
vec![E::Null, thunk(E::Obj(fields.iter().map(|(k, p)| { let x = ix(&r, str(k.clone())); Prop::Kv(Key::Str(k.clone()), if *p == Part::Ref { call(x, vec![]) } else { x }) }).collect()))],
1211+
),
1212+
};
1213+
Ok(Some(vec![konst(r.clone(), call(id(fb.js.clone()), out)), konst(b.js.clone(), whole)]))
1214+
}
1215+
ExprKind::Index { o, .. } | ExprKind::Member { o, .. } => {
1216+
let ExprKind::Id(on) = &o.k else { return Ok(None) };
1217+
let Some(ob) = self.lookup(env, on) else { return Ok(None) };
1218+
let (Some(inst), Some(sh)) = (ob.inst.clone(), ob.shape.clone()) else { return Ok(None) };
1219+
let (key, p) = match (&e.k, &sh) {
1220+
(ExprKind::Index { i, .. }, FShape::Items(items)) => match &i.k {
1221+
ExprKind::Lit(Lit::Num(v)) if *v >= 0.0 && v.fract() == 0.0 => match items.get(*v as usize) {
1222+
Some(p) => (E::Num(*v), *p),
1223+
None => return Ok(None),
1224+
},
1225+
_ => return Ok(None),
1226+
},
1227+
(ExprKind::Member { p: k, .. }, FShape::Fields(fields)) => match fields.iter().find(|f| &f.0 == k) {
1228+
Some(f) => (str(k.clone()), f.1),
1229+
None => return Ok(None),
1230+
},
1231+
_ => return Ok(None),
1232+
};
1233+
Ok(Some(vec![konst(b.js.clone(), part(ix(&inst, key), p))]))
1234+
}
1235+
_ => Ok(None),
1236+
}
1237+
}
11361238
fn instantiate(&mut self, e: &Expr, env: Env) -> R<E> {
11371239
let ExprKind::Call { f, args } = &e.k else { unreachable!() };
11381240
let ExprKind::Id(fname) = &f.k else { unreachable!() };

0 commit comments

Comments
 (0)