diff --git a/.gitignore b/.gitignore index 8cefff9b..af5ba1fb 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,4 @@ compiler/compiler.wasi.d.cts compiler/compiler.wasi-browser.js compiler/wasi-worker.mjs compiler/wasi-worker-browser.mjs +compiler/guide/ diff --git a/compiler/package.json b/compiler/package.json index bc07d885..2eb3b286 100644 --- a/compiler/package.json +++ b/compiler/package.json @@ -25,6 +25,7 @@ "index.d.ts", "vite.mjs", "vite.d.mts", + "guide/", "README.md" ], "scripts": { @@ -33,6 +34,7 @@ "artifacts": "napi artifacts", "create-npm-dirs": "napi create-npm-dirs", "version": "napi version && node scripts/sync-optional-deps.mjs", + "prepack": "node scripts/guide.mjs", "test": "node test/node.mjs" }, "napi": { diff --git a/compiler/scripts/guide.mjs b/compiler/scripts/guide.mjs new file mode 100644 index 00000000..004867d0 --- /dev/null +++ b/compiler/scripts/guide.mjs @@ -0,0 +1,11 @@ +// prepack: the guide ships in the package (guide/diagnostics.md is the page each diagnostic code points to, and +// language.md, async.md and reference.md are what it points on to), copied from the repository's guide/. +import { copyFileSync, mkdirSync, readdirSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const from = path.join(here, "../../guide"); +const to = path.join(here, "../guide"); +mkdirSync(to, { recursive: true }); +for (const f of readdirSync(from).filter(f => f.endsWith(".md"))) copyFileSync(path.join(from, f), path.join(to, f)); diff --git a/compiler/src/app.rs b/compiler/src/app.rs index 60ca99c9..ca1f7cd4 100644 --- a/compiler/src/app.rs +++ b/compiler/src/app.rs @@ -32,7 +32,13 @@ pub fn app(entry: &str, target: Target, module_name: &str, spa: bool) -> Value { if read_disk(entry).is_none() { return Err(json!({ "error": format!("{entry}: no such file") })); } - let set = load_modules(entry, &read_disk).map_err(|e| json!({ "error": format!("{entry}: {}", e.0) }))?; + let set = load_modules(entry, &read_disk).map_err(|e| { + // a parse error is a diagnostic like the checker's, with its code (PARSE, or the habit it names) + let file = e.2.clone().unwrap_or_else(|| entry.to_string()); + let mut d = crate::serve::parse_error_in(&file, &e, read_disk(&file).as_deref()); + d["msg"] = json!(crate::serve::parse_message(&e)); + json!({ "diagnostics": [d] }) + })?; let checked = check_modules(&set, spa); if !checked.diags.is_empty() { return Err(json!({ "diagnostics": checked.diags.iter().map(|d| { let mut j = d.to_json(); if j["file"].is_null() { j["file"] = json!(set.entry); } j }).collect::>() })); diff --git a/compiler/src/main.rs b/compiler/src/main.rs index 58cd9e93..b612ae72 100644 --- a/compiler/src/main.rs +++ b/compiler/src/main.rs @@ -153,6 +153,17 @@ fn lower_one(r: &Value) -> Value { v } +/// A parse error as `rxc check` prints a diagnostic: `file:line:column: error CODE [rule] message`, the message without the +/// `file: line n:` it carries. +fn parse_error_text(f: &str, e: &reactivescript::parse::ParseError) -> String { + let v = parse_error_json(f, e); + let msg = serve::parse_message(e); + let at = match (v["range"]["start"]["line"].as_i64(), v["range"]["start"]["column"].as_i64()) { + (Some(l), Some(c)) => format!("{}:{}", l, c + 1), + _ => "1".into(), + }; + format!("{}:{}: error {} [{}] {}", v["file"].as_str().unwrap_or(f), at, e.3, v["rule"].as_str().unwrap_or("07"), msg) +} /// A parse error as `diagnostic_json` writes a diagnostic: from where the parser stopped to the end of that line. fn parse_error_json(f: &str, e: &reactivescript::parse::ParseError) -> Value { let file = e.2.clone().unwrap_or_else(|| abs(f)); @@ -264,7 +275,7 @@ fn main() { let set = match load_modules(&abs(file), &read_disk) { Ok(s) => s, Err(e) => { - eprintln!("{}: parse error: {}", file, e.0); + eprintln!("{}", parse_error_text(file, &e)); std::process::exit(1); } }; @@ -318,7 +329,7 @@ fn main() { if as_json { found.push(parse_error_json(f, &e)); } else { - eprintln!("{}: parse error: {}", f, e.0); + eprintln!("{}", parse_error_text(f, &e)); } continue; } diff --git a/compiler/src/modules.rs b/compiler/src/modules.rs index e411dcc4..c318a88e 100644 --- a/compiler/src/modules.rs +++ b/compiler/src/modules.rs @@ -85,10 +85,10 @@ impl Loader<'_> { let Some(src) = (self.read)(path) else { return Ok(()) }; let mut p = if self.recover { let (p, errs) = crate::parse::parse_program_recovering(&src); - self.parse_errors.extend(errs.into_iter().map(|e| ParseError(e.0, e.1, Some(path.to_string())))); + self.parse_errors.extend(errs.into_iter().map(|e| ParseError(e.0, e.1, Some(path.to_string()), e.3))); p } else { - parse_program(&src).map_err(|e| ParseError(format!("{}: {}", path, e.0), e.1, Some(path.to_string())))? + parse_program(&src).map_err(|e| ParseError(format!("{}: {}", path, e.0), e.1, Some(path.to_string()), e.3))? }; self.state.insert(path.to_string(), State::Busy); for d in p.decls.iter_mut() { @@ -98,7 +98,7 @@ impl Loader<'_> { let dts = join_path(path, &(replace_js_ext(from) + ".d.rx")); if !self.declarations.contains_key(&dts) { if let Some(src) = (self.read)(&dts) { - let ds = parse_declarations(&src).map_err(|e| ParseError(format!("{}: {}", dts, e.0), e.1, Some(dts.clone())))?; + let ds = parse_declarations(&src).map_err(|e| ParseError(format!("{}: {}", dts, e.0), e.1, Some(dts.clone()), e.3))?; self.declarations.insert(dts.clone(), ds); } } @@ -134,7 +134,7 @@ impl Loader<'_> { // MO-9: no body — its signature, read in place let dts = to.strip_suffix(".rx").map(|s| format!("{}.d.rx", s)).unwrap_or_else(|| to.clone()); if let Some(sig) = (self.read)(&dts) { - let s = parse_signature(&sig, &to).map_err(|e| ParseError(e.0, None, Some(dts.clone())))?; + let s = parse_signature(&sig, &to).map_err(|e| ParseError(e.0, None, Some(dts.clone()), "PARSE"))?; self.signatures.insert(to.clone(), s); continue; } diff --git a/compiler/src/parse.rs b/compiler/src/parse.rs index 78b0b40e..3393da02 100644 --- a/compiler/src/parse.rs +++ b/compiler/src/parse.rs @@ -7,8 +7,9 @@ use std::collections::HashSet; use std::sync::LazyLock; #[derive(Debug, Clone, PartialEq)] -/// What failed to parse; where (a byte offset), and in which file, when known. -pub struct ParseError(pub String, pub Option, pub Option); +/// What failed to parse; where (a byte offset), and in which file, when known; and its code: the habit `hint` recognised +/// (guide/diagnostics.md), else `PARSE`. +pub struct ParseError(pub String, pub Option, pub Option, pub &'static str); impl std::fmt::Display for ParseError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(&self.0) @@ -151,7 +152,11 @@ impl<'a> Cursor<'a> { } pub fn fail(&self, msg: &str) -> R { let near: String = self.rest().chars().take(20).collect(); - Err(ParseError(format!("line {}: {} near '{}'", self.line(), msg, near), Some(self.i), None)) + let near = near.split('\n').next().unwrap_or(""); + let near = if near.trim().is_empty() { "at the end of the line".to_string() } else { format!("near '{}'", near) }; + let h = hint(self.src, self.i, msg); + let tail = h.as_ref().map(|(_, t)| format!(" — {}", t)).unwrap_or_default(); + Err(ParseError(format!("line {}: {} {}{}", self.line(), msg, near, tail), Some(self.i), None, h.map(|(c, _)| c).unwrap_or("PARSE"))) } pub fn ident(&mut self) -> Option { let m = IDENT.find(self.rest())?; @@ -253,6 +258,47 @@ fn parse_classes(c: &mut Cursor) -> R>> { Ok(Some(out)) } +re!(JS_APIS, r"\b(useState|useReducer|useMemo|useCallback|useEffect|useRef|createSignal|createMemo|createEffect|createStore|createResource|createAsync)\s*\("); +re!(JS_FUNCTION, r"^(export\s+)?(default\s+)?(async\s+)?function\b"); +re!(JS_LOCAL, r"^(const|let|var)\b"); +re!(JS_RETURN, r"^return\b"); +re!(NAME_BEFORE, r"([A-Za-z_$][A-Za-z0-9_$.]*)\s*$"); +re!(ARROW_BEFORE, r"=>\s*[A-Za-z_$][A-Za-z0-9_$.]*\s*$"); +re!(OP_ASSIGN, r"^(\+\+|--|(\*\*|\|\||&&|\?\?|[-+*/%])=)"); + +/// What a parse failure at `i` most likely meant, when the line reads like JavaScript, React or Solid: its code and the +/// text appended to the message. `ref/src/parse.ts` `hint` is the same function. +pub fn hint(src: &str, i: usize, msg: &str) -> Option<(&'static str, String)> { + let i = i.min(src.len()); + let rest = &src[i..]; + let at = if !rest.is_empty() && !rest.split('\n').next().unwrap_or("").trim().is_empty() { i as i64 } else { src[..i].trim_end().len() as i64 - 1 }; + let p = at.max(0) as usize; + let start = if p == 0 { 0 } else { src[..p].rfind('\n').map(|j| j + 1).unwrap_or(0) }; + let end = src[p..].find('\n').map(|j| p + j).unwrap_or(src.len()); + let line = src[start..end].trim(); + let before = &src[src[..i].rfind('\n').map(|j| j + 1).unwrap_or(0)..i]; + let name = NAME_BEFORE.captures(before).map(|c| c[1].to_string()).unwrap_or_else(|| "x".into()); + if msg.starts_with("W-2") && rest.starts_with(":=") && ARROW_BEFORE.is_match(before) { + return Some(("REACTIVE_WRITE_IN_OWNED_SCOPE", format!("an arrow that writes takes a braced body, `() => {{ {} := … }}`: an expression-bodied arrow is a pure function (SC-3)", name))); + } + if OP_ASSIGN.is_match(rest) || (rest.starts_with('=') && !rest[1..].starts_with('=') && !rest[1..].starts_with('>')) { + return Some(("ASSIGNMENT", format!("a source is written with `:=`, as a statement in a handler or action: `{n} := {n} + 1`, or `{n} := v => v + 1` (W-1, W-6); .rx has no `=`, `+=` or `++` on state", n = name))); + } + if JS_FUNCTION.is_match(line) { + return Some(("JS_FUNCTION", "`function` is not .rx: a pure function is `fn f(x) => …`, one that writes or awaits is `action f(x) { … }`, one that renders is `component F(props) { … }`".into())); + } + if let Some(c) = JS_LOCAL.captures(line) { + return Some(("JS_LOCAL", format!("`{}` declares a local only in a handler or action body: in a component or at a module's top level, state is `source x := …` and a value computed from others is an equation, `x = …`", &c[1]))); + } + if JS_RETURN.is_match(line) { + return Some(("JS_RETURN", "a component has no `return`: its body is declarations, then its markup".into())); + } + if let Some(c) = JS_APIS.captures(line) { + return Some(("JS_API", format!("`{}` is not .rx: state is `source x := …`, a value computed from others is `x = …`, a side effect is `effect (x) {{ … }}`", &c[1]))); + } + None +} + pub fn parse_program(src: &str) -> R { let mut c = Cursor::new(src); let mut decls = vec![]; @@ -266,7 +312,7 @@ pub fn parse_program(src: &str) -> R { let view = parse_markup(&mut c, Close::Top)?; c.ws(true); if !c.eof() { - return c.fail("declaration or markup"); + return c.fail("expected a declaration or markup"); } let dflt: Vec<&Decl> = decls.iter().filter(|d| matches!(d, Decl::Component { is_default: true, .. })).collect(); if dflt.len() > 1 { @@ -298,7 +344,7 @@ pub fn parse_program_recovering(src: &str) -> (Program, Vec) { match parse_markup(&mut c, Close::Top) { Ok(view) if !view.is_empty() => { let mut errors = c.errors; - errors.push(ParseError("line 1: markup at a module's top level (MO-1c)".into(), Some(at), None)); + errors.push(ParseError("line 1: markup at a module's top level (MO-1c)".into(), Some(at), None, "PARSE")); return (Program { decls, view, legacy_view: Some(true) }, errors); } Ok(_) => break, @@ -1564,14 +1610,14 @@ fn parse_markup(c: &mut Cursor, close: Close) -> R> { } if c.i == start { // the reference loops here forever (a stray `}`); this ends it - return c.fail("declaration or markup"); + return c.fail("expected a declaration or markup"); } continue; } if s.contains(":=") { return c.fail("W-2: write in reactive scope (no statement position)"); } - return c.fail("declaration or markup"); + return c.fail("expected a declaration or markup"); } if broke && matches!(out.last(), Some(Markup { kind: MarkupKind::Text(_), .. })) { out.push(Markup { kind: MarkupKind::Text(" ".into()), line: None, span: Span::NONE }); @@ -1582,7 +1628,7 @@ fn parse_markup(c: &mut Cursor, close: Close) -> R> { } if c.i == start { // the reference loops here forever (a stray `}` in an element); this ends it - return c.fail("declaration or markup"); + return c.fail("expected a declaration or markup"); } } } diff --git a/compiler/src/serve.rs b/compiler/src/serve.rs index f4898806..78035689 100644 --- a/compiler/src/serve.rs +++ b/compiler/src/serve.rs @@ -26,8 +26,15 @@ pub fn diagnostic_json(set: &crate::modules::ModuleSet, d: &crate::check::Diagno v } +/// A parse error's message without the `file: line n:` it carries (the diagnostic's own fields say where). +pub fn parse_message(e: &crate::parse::ParseError) -> &str { + e.0.split_once("line ").filter(|(pre, _)| pre.is_empty() || pre.ends_with(": ")).and_then(|(_, r)| r.split_once(": ")).map(|(_, m)| m).unwrap_or(&e.0) +} + pub fn parse_error_in(file: &str, e: &crate::parse::ParseError, src: Option<&str>) -> Value { - let mut v = json!({ "file": file, "code": "PARSE", "rule": "07", "message": e.0 }); + static RULE: std::sync::LazyLock = std::sync::LazyLock::new(|| regex::Regex::new(r"\b([A-Z]+-\d+[a-z]?)\b").unwrap()); + let rule = RULE.captures(&e.0).map(|c| c[1].to_string()).unwrap_or_else(|| "07".into()); + let mut v = json!({ "file": file, "code": e.3, "rule": rule, "message": parse_message(e) }); if let (Some(at), Some(src)) = (e.1, src) { let at = at.min(src.len()); let end = src[at..].find('\n').map(|j| at + j).unwrap_or(src.len()); diff --git a/compiler/tests/diagnostics_page.rs b/compiler/tests/diagnostics_page.rs new file mode 100644 index 00000000..b3078759 --- /dev/null +++ b/compiler/tests/diagnostics_page.rs @@ -0,0 +1,77 @@ +//! guide/diagnostics.md, the page each diagnostic code points to: every code the crate (and its type prelude) can +//! report has a section, every `rx before` fence gets its section's code, and every `rx after` fence checks clean. + +use reactivescript::check::check_modules; +use reactivescript::modules::load_modules; +use regex::Regex; +use std::collections::BTreeSet; +use std::path::Path; + +fn root() -> &'static Path { + Path::new(env!("CARGO_MANIFEST_DIR")).parent().unwrap() +} + +/// The codes a program `src` gets: its parse error's, else its checker diagnostics'. +fn codes(src: &str) -> Vec { + let entry = "/page/main.rx"; + let read = |p: &str| if p == entry { Some(src.to_string()) } else { None }; + match load_modules(entry, &read) { + Err(e) => vec![e.3.to_string()], + Ok(set) => check_modules(&set, false).diags.into_iter().map(|d| format!("{} ({}: {})", d.code, d.line, d.msg)).collect(), + } +} + +#[test] +fn every_code_has_a_section_and_its_examples_hold() { + let page = std::fs::read_to_string(root().join("guide/diagnostics.md")).unwrap(); + let heading = Regex::new(r"^#{2,3} ([A-Z][A-Z_]+)$").unwrap(); + let mut sections = BTreeSet::new(); + let mut failures = vec![]; + let (mut code, mut fence): (Option, Option<(String, String)>) = (None, None); + for line in page.lines() { + if let Some((mark, body)) = &mut fence { + if line == "```" { + let got = codes(body); + let c = code.clone().unwrap_or_default(); + let ok = if mark == "before" { got.iter().any(|g| g == &c || g.starts_with(&format!("{} (", c))) } else { got.is_empty() }; + if !ok { + failures.push(format!("{} `rx {}`: got {:?}\n{}", c, mark, got, body)); + } + fence = None; + } else { + body.push_str(line); + body.push('\n'); + } + continue; + } + if let Some(m) = heading.captures(line) { + code = Some(m[1].to_string()); + sections.insert(m[1].to_string()); + } else if let Some(mark) = line.strip_prefix("```rx ") { + fence = Some((mark.to_string(), String::new())); + } + } + let mut emitted = BTreeSet::new(); + let patterns = [ + r#"err\(\s*"([A-Z][A-Z_]+)""#, + r#"code: "([A-Z][A-Z_]+)""#, + r#"\{ "([A-Z][A-Z_]+)" \} else \{ "([A-Z][A-Z_]+)" \}"#, + r#"Some\(\("([A-Z][A-Z_]+)""#, + r#"unwrap_or\("([A-Z][A-Z_]+)"\)"#, + r#""([A-Z][A-Z_]+): "#, + ]; + for f in std::fs::read_dir(root().join("compiler/src")).unwrap() { + let p = f.unwrap().path(); + let src = std::fs::read_to_string(&p).unwrap(); + for pat in &patterns { + for m in Regex::new(pat).unwrap().captures_iter(&src) { + for g in m.iter().skip(1).flatten() { + emitted.insert(g.as_str().to_string()); + } + } + } + } + let missing: Vec<_> = emitted.difference(§ions).collect(); + assert!(missing.is_empty(), "codes with no section in guide/diagnostics.md: {:?}", missing); + assert!(failures.is_empty(), "examples that do not hold:\n\n{}", failures.join("\n\n")); +} diff --git a/compiler/vite.mjs b/compiler/vite.mjs index 9e4460e9..d65161b4 100644 --- a/compiler/vite.mjs +++ b/compiler/vite.mjs @@ -13,12 +13,23 @@ // changes. The crate's output imports its dependencies as `./x.rx?rx-dep`, and a dependency is served from the build // of a program that contains it. A module several programs share is one module: its instance is keyed by its factory // (11 CP-4b `module`), not by its place in a program. -import { statSync } from "node:fs"; +import { existsSync, statSync } from "node:fs"; import { createRequire } from "node:module"; import path from "node:path"; +import { fileURLToPath } from "node:url"; const { app } = createRequire(import.meta.url)("./index.js"); const DEP = "rx-dep"; +// the page each code points to: the package's copy (scripts/guide.mjs), else the repository's +const GUIDE = [path.join(path.dirname(fileURLToPath(import.meta.url)), "guide/diagnostics.md"), path.join(path.dirname(fileURLToPath(import.meta.url)), "../guide/diagnostics.md")].find(existsSync) + ?? "https://github.com/solidjs/reactivescript/blob/main/guide/diagnostics.md"; +const at = d => d.range ? `${d.range.start.line}:${d.range.start.column + 1}` : `${d.line}`; +/** The diagnostics as `rxc check` prints them, then, once per code, where its fix is explained. */ +const report = ds => [ + ...ds.map(d => `${d.file}:${at(d)}: error ${d.code} [${d.rule}] ${d.msg}`), + "", + ...[...new Set(ds.map(d => d.code))].map(c => `${c}: why, and the fix — ${GUIDE}#${c.toLowerCase()}`), +].join("\n"); const mtime = file => { try { return statSync(file).mtimeMs; } catch { return -1; } }; const isDep = moduleId => new URLSearchParams(moduleId.split("?")[1] ?? "").has(DEP); // `import __m0 from "./catalog.rx";` → `"./catalog.rx?rx-dep"` (one line each: the module's map is by line, CP-1c) @@ -55,7 +66,7 @@ export default function rx() { const spa = target === "dom" && solid.hydratable === false; const dep = isDep(moduleId); const { entry, out } = dep ? containing(file, target, moduleName, spa) : build(file, target, moduleName, spa); - if (out.diagnostics) throw new Error(out.diagnostics.map(d => `${d.file}:${d.line}: error ${d.code} [${d.rule}] ${d.msg}`).join("\n")); + if (out.diagnostics) throw new Error(report(out.diagnostics)); if (out.error) throw new Error(out.error); const m = out.modules[file]; for (const p of Object.keys(out.modules)) if (p !== file) addWatchFile(p); diff --git a/guide/diagnostics.md b/guide/diagnostics.md new file mode 100644 index 00000000..1e0b26d3 --- /dev/null +++ b/guide/diagnostics.md @@ -0,0 +1,1103 @@ +# .rx diagnostics: every code and its fix + +`rxc check` and the editor report a diagnostic as `file:line:column: error CODE [rule] message`. The message already +says what to do. This page says why, with a program that gets the code and the same program fixed, one section per +code. Codes keep Solid 2.0's names where Solid has the same check at run time (`REACTIVE_WRITE_IN_OWNED_SCOPE`, +`ASYNC_STORE_SETTER`, …), so a compile error here and a dev-mode warning from Solid mean the same thing. + +The `[rule]` is the id of the rule in `spec/` (`grep -n "^- \*\*AC-1c" spec/*.md`). `reference.md` has every rule in +one line; you rarely need more than this page and that one. + +Fences marked `rx before` get the section's code and fences marked `rx after` check clean: the compiler's tests run +every one of them (`compiler/tests/diagnostics_page.rs`). Fences with no mark are sketches that need other modules. + +## Parse errors: habits from JavaScript, React and Solid + +A parse error names the habit it looks like, when it recognises one; otherwise its code is `PARSE`. + +### PARSE + +The text has no `.rx` reading at that point. The message says what the parser expected and quotes what it found. +`reference.md`'s grammar is the whole syntax. + +### JS_LOCAL + +`const`, `let` and `var` declare locals in a handler or an action body only. A component and a module's top level hold +declarations: a value that changes is a `source`, one computed from others is an equation (E-1). + +```rx before +export default component App() { + const n = 1 + let d = n * 2 +

{d}

+} +``` + +```rx after +export default component App() { + source n := 1 + d = n * 2 +

{d}

+} +``` + +### JS_FUNCTION + +There is no `function`. A pure function is `fn`, code that writes or awaits is an `action`, code that renders is a +`component`. + +```rx before +function twice(x) { return x * 2 } +export default component App() { +

{twice(1)}

+} +``` + +```rx after +fn twice(x) => x * 2 +export default component App() { +

{twice(1)}

+} +``` + +### JS_RETURN + +A component's body is its declarations, then its markup. There is no `return`. + +```rx before +export default component App() { + source n := 1 + return

{n}

+} +``` + +```rx after +export default component App() { + source n := 1 +

{n}

+} +``` + +### JS_API + +`createSignal`, `useState`, `createMemo`, `useEffect` and the rest are spelled as declarations: `source x := v` is +state, `x = e` is a memo, `effect (x) { … }` is an effect. + +```rx before +export default component App() { + [n, setN] = createSignal(0) + +} +``` + +```rx after +export default component App() { + source n := 0 + +} +``` + +### ASSIGNMENT + +A source is written with `:=` as a statement, in a handler or an action (W-1). There is no `=`, `+=` or `++` on state. +To write from the value as it stands at the write, give a function: `n := v => v + 1` (W-6). + +```rx before +export default component App() { + source n := 0 + +} +``` + +```rx after +export default component App() { + source n := 0 + +} +``` + +### REACTIVE_WRITE_IN_OWNED_SCOPE + +A write happens in imperative scope only: a handler, an action, an effect's apply block (W-2). A closure created in a +component or an equation is a pure function (SC-3), so an arrow that writes needs a braced body in a handler position, +and a reusable writer is an `action`. Solid throws the same code at run time. + +```rx before +export default component App() { + source n := 0 + +} +``` + +```rx after +export default component App() { + source n := 0 + +} +``` + +```rx before +export default component App() { + source n := 1 + reset = () => { n := 0 } + +} +``` + +```rx after +export default component App() { + source n := 1 + action reset() { n := 0 } + +} +``` + +## Writes + +### WRITE_TO_NON_SOURCE + +Only sources are written (W-1). An equation is always equal to its right side, and props, parameters and contexts are +read-only (O-4): the block that declares a source writes it, and others get an action that does. + +```rx before +export default component App() { + source n := 1 + double = n * 2 + +} +``` + +```rx after +export default component App() { + source n := 1 + double = n * 2 + +} +``` + +A source imported from another module is written through an action that module exports (MO-2): + +```rx +// store.rx +export source selected := 0 +export action select(id: number) { selected := id } + +// App.rx +import { selected, select } from "./store.rx" +export default component App() { + +} +``` + +### STALE_OWN_READ + +All the writes of one run land together when the run ends, so after `count := count + 1` the run still reads the old +`count` (W-3, W-4). Keep the value you wrote in a local and read that. + +```rx before +export default component App() { + source count := 0 + source seen := 0 + +} +``` + +```rx after +export default component App() { + source count := 0 + source seen := 0 + +} +``` + +### STALE_WRITE_BACK + +A write after an `await` that is computed from a read before it overwrites whatever changed the source in between +(another action, a reload). Write functionally, so the write applies to the value as it stands (W-6), or guess it with +`optimistic` and let the answer replace the guess (AC-3). + +```rx before +export default component App() { + source log := "" + action add(x: string) { + let before = log + let r = await fetch(x) catch (e) => "" + log := before + x + } + +} +``` + +```rx after +export default component App() { + source log := "" + action add(x: string) { + let r = await fetch(x) catch (e) => "" + log := v => v + x + } + +} +``` + +### SNAPSHOT_INITIALIZER + +A source's `:=` seed is read once. Reading another reactive value there takes a snapshot, which must say so with +`peek(…)` (E-4). If the value should follow its input, it is an equation, or a source with a question (`source x = e`, +ST-5). + +```rx before +export default component App() { + source form := { email: "a@x" } + source email := form.email +

{email}

+} +``` + +```rx after +export default component App() { + source form := { email: "a@x" } + source email := peek(form.email) +

{email}

+} +``` + +### SNAPSHOT_ARGUMENT + +A `fn` that declares state (an effect, a source) reads its value parameters once. Declare the parameter `ref` to pass +the reactive value itself, or pass `peek(…)` to say a snapshot is meant (E-10). + +```rx before +export default component App() { + fn watch(v) { + effect (v) { log(v) } + v + } + source n := 1 + w = watch(n) +

{w}

+} +``` + +```rx after +export default component App() { + fn watch(ref v) { + effect (v) { log(v) } + v + } + source n := 1 + w = watch(n) +

{w}

+} +``` + +### DUPLICATE_DECLARATION + +A name is declared once in a block (E-7). Rename one. + +```rx before +export default component App() { + source x := 1 + x = 2 +

{x}

+} +``` + +```rx after +export default component App() { + source x := 1 + y = 2 +

{x} {y}

+} +``` + +### CYCLE + +Equations that read each other in one instant have no value (C-1). Break the loop with `pre`, the value before the +last change (C-2), or make one side a source written by an event. + +```rx before +export default component App() { + source s := 0 + a = b + 1 + b = a + 1 +

{a}

+} +``` + +```rx after +export default component App() { + source s := 0 + a = s + 1 + b = a + 1 +

{b}

+} +``` + +### PRE_OF_NON_REACTIVE + +`pre x` is `x`'s value before its last change, so `x` has to be reactive: a source or an equation (C-2). + +```rx before +export default component App() { + fn f(x) => x + y = pre f +

{y}

+} +``` + +```rx after +export default component App() { + source n := 1 + y = pre n -> 0 +

{y}

+} +``` + +### EFFECT_WRITES_OWN_SOURCE + +An effect that writes what it reads runs again from its own write: a loop across instants (C-3). Derive the value as an +equation, as a source with a question (ST-5), or write it from the event that changes the inputs. + +```rx before +export default component App() { + source n := 0 + effect (n) { n := n + 1 } +

{n}

+} +``` + +```rx after +export default component App() { + source n := 0 + shown = n + 1 +

{shown}

+} +``` + +## Actions, guesses and holds + +### HELD_WRITE + +A handler that writes and awaits is an action (AC-1b), and an action's writes land when its body ends (AC-1). So a +write before the `await` does not show while the work runs. Say which you meant: `optimistic x := …` for state that +shows while the work runs (on a source with a question, ST-5c); `onFlush(() => { x := … })` for a reset that lands now +(EF-8); a declared `action` to hold it on purpose; or write it after the `await`. `async.md` ("What lands together, and +what waits") is the long form. + +```rx before +export default component App() { + source status := "" + +} +``` + +```rx after +export default component App() { + source status := "" + +} +``` + +### AWAIT_IN_EXPRESSION + +In imperative code a run suspends only at a statement (AC-1). Bind the answer first, `let v = await e`, then use `v`. + +```rx before +export default component App() { + source status := "" + action place() { + try { status := `got ${await fetch("checkout")}` } catch {} + } + +} +``` + +```rx after +export default component App() { + source status := "" + action place() { + try { + let r = await fetch("checkout") + status := `got ${r}` + } catch {} + } + +} +``` + +### OPTIMISTIC_OUTSIDE_HOLD + +A guess lives in an action's hold until the server answers it (AC-3). An effect's apply block is never an action, so +declare one and call it from the block. + +```rx before +export default component App() { + source draft := "a" + source saved = "a" + effect (draft) { optimistic saved := $0 } +

{saved}

+} +``` + +```rx after +export default component App() { + source draft := "a" + source saved = "a" + action save(v: string) { + optimistic saved := v + await fetch("save:" + v) catch (e) => null + } + effect (draft) { save($0) } +

{saved}

+} +``` + +### OPTIMISTIC_NO_QUESTION + +A guess is confirmed or replaced by the answer to a question, so `optimistic` writes a source declared with `=` (a +source with a question, ST-5c). A source seeded with `:=` has no question; write it plainly. + +```rx before +export default component App() { + source shown := "Ann" + action fix() { optimistic shown := "Zed"; await fetch("x") catch (e) => null } + +} +``` + +```rx after +export default component App() { + source shown = await fetch("name") catch (e) => "Ann" + action fix() { optimistic shown := "Zed"; await fetch("x") catch (e) => null } + +} +``` + +### INVALID_REFRESH_TARGET + +`refresh x` re-asks `x`'s question (AC-4), so `x` is an equation that awaits or a source declared with `=`. A source +seeded with `:=` has nothing to re-ask: write it instead. + +```rx before +export default component App() { + source base := 1 + +} +``` + +```rx after +export default component App() { + source id := 1 + base = await fetch("b:" + id) catch (e) => 0 + +} +``` + +### INVALID_AFFECTS_TARGET + +`affects x` makes `pending? x` true until the action commits (AC-5), so `x` is a source or an equation of this +program, not a parameter or a plain value. + +```rx before +export default component App() { + action go(n) { affects n } +

x

+} +``` + +```rx after +export default component App() { + source total := 0 + action go(n: number) { + affects total + let r = await fetch("add:" + n) catch (e) => 0 + total := r + } + +} +``` + +### HOOK_CALLBACK + +`onFlush` and `onSettled` take a closure with no parameters, `onFlush(() => { … })`: its body is the run they schedule +(EF-7, EF-8). + +```rx before +export default component App() { + source open := true + +} +``` + +```rx after +export default component App() { + source open := true + +} +``` + +### SETTLED_CLEANUP_UNOWNED + +A callback passed to `onSettled` runs once and has no region to bind a cleanup to (EF-7). Setup with teardown is an +`effect` whose apply block returns the cleanup (EF-4, EF-5). + +```rx before +export default component App() { + source n := 0 + +} +``` + +```rx after +export default component App() { + source n := 0 + effect (n) { return () => { log($0) } } + +} +``` + +### UNTIL_PREDICATE + +`until` waits for a condition to become true, so it takes a predicate, `until(() => e)` (AC-6). A plain value is read +once and never changes. + +```rx before +export default component App() { + source ok := false + action wait() { await until(ok) } + +} +``` + +```rx after +export default component App() { + source ok := false + action wait() { await until(() => ok) } + +} +``` + +## Reactive scope and io + +### IO_IN_REACTIVE + +An io function (an import without `pure`, `until`, an action) runs in imperative scope only: a handler, an action, an +effect's apply block (R-io-3, AC-6). An equation re-runs whenever its inputs change, so it may only ask pure questions. + +```rx before +export default component App() { + source ok := false + done = until(() => ok) +

{ok}

+} +``` + +```rx after +export default component App() { + source ok := false + action wait() { await until(() => ok) } + +} +``` + +### ACTION_CALLED_IN_OWNED_SCOPE + +An action is called from a handler or another action, never from an equation or the markup (R-io-3). Solid throws the +same code at run time. + +```rx before +export default component App() { + source n := 1 + action bump() { n := n + 1 } + x = bump() +

{x}

+} +``` + +```rx after +export default component App() { + source n := 1 + action bump() { n := n + 1 } + +} +``` + +### IO_IN_FN + +A `fn` is pure by definition (R-io-2). Code that calls io is an `action`, or the io call moves into the handler. + +```rx +import { log } from "./prelude" +export default component App() { + fn noisy(v) => log(v) // IO_IN_FN + action noisy2(v: number) { log(v) } // fixed + source n := 1 + +} +``` + +### ASYNC_STORE_SETTER + +A draft block is a synchronous transaction on its draft `d` (ST-3b): it holds `let`, expressions and writes to `d`, +nothing that awaits, refreshes or calls io. Do that work in an action and write the result. Solid throws the same code +when a store setter returns a promise. + +```rx before +export default component App() { + source id := 1 + sel = draft(pre sel -> {}) { refresh id } +

{sel}

+} +``` + +```rx after +export default component App() { + source id := 1 + sel = draft(pre sel -> {}) { d[str(id)] := true } +

{sel}

+} +``` + +### DRAFT_WRITE_OUTSIDE_DRAFT + +A draft block writes only its draft, `d` (ST-3a). Other sources are written by the event that changes them. + +```rx before +export default component App() { + source id := 1 + source other := {} + selected = draft(pre selected -> {}) { other[str(id)] := true } +

{selected}

+} +``` + +```rx after +export default component App() { + source id := 1 + selected = draft(pre selected -> {}) { d[str(id)] := true } +

{selected}

+} +``` + +## Failures and loading + +### UNHANDLED_FAILURE + +A value that can fail is read where nothing handles the failure (R-f-5). Wrap the reader in an `errored` region, or +catch the failure where it is read, `e catch (err) => alt`. + +```rx before +export default component App() { + source id := 1 + user = await fetch("u:" + id) +

{user}

+} +``` + +```rx after +export default component App() { + source id := 1 + user = await fetch("u:" + id) + {errored fallback(e) {

failed: {e.message}

} {

{user}

}} +} +``` + +### UNCAUGHT_ACTION_FAILURE + +An action catches its own failures (R-f-6): a handler cannot, since it does not await the action. Put a +`try { … } catch (e) { … }` in the body, or `catch (e) => alt` on the `await`. + +```rx before +export default component App() { + source saved := "" + action save() { + let r = await fetch("save") + saved := r + } + +} +``` + +```rx after +export default component App() { + source saved := "" + action save() { + let r = await fetch("save") catch (e) => "failed" + saved := r + } + +} +``` + +### NOT_AN_ERROR_CLASS + +A `catch` or `errored` that names a class narrows to error classes declared with `error` (R-f-1). Declare the class, +or drop the name to take any failure. + +```rx before +export default component App() { + source id := 1 + user = await fetch("u:" + id) + {errored fallback(e: Missing) {

{e.message}

} {

{user}

}} +} +``` + +```rx after +export default component App() { + source id := 1 + user = await fetch("u:" + id) + {errored fallback(e) {

{e.message}

} {

{user}

}} +} +``` + +### ROW_NARROWER_THAN_INFERRED + +A declared row (`lane`, `fails(…)`) says less than the value does (CN-4a, RG-7e). Widen the declaration, or drop it and +let the compiler infer it. + +```rx before +export default component App() { + source id := 1 + user: lane string = await fetch("u:" + id) +

{user}

+} +``` + +### UNGUARDED_SNAPSHOT + +A handler reads a value as a snapshot when it can have no value yet (a first load) or can fail, so the click sees no +value or throws (R-8). Put the element inside the `loading` / `errored` regions whose content reads the value, with +`disabled={pending? x}` while a new question is out; or catch the failure in the handler. + +```rx +export default component App() { + source id := 1 + user = await fetch("u:" + id) + {errored fallback(e) {

failed

} { + {loading fallback {

loading…

} { + + }} + }} +} +``` + +### ASYNC_OUTSIDE_LOADING_BOUNDARY + +In a client-only build (`--spa`), a value with no answer yet and no `loading` region above it shows nothing until it +answers (CN-3d). Put it under `loading fallback { … } { … }`, or give the await a first paint, `await f() -> v`. Later +answers are transitions and need no region. + +### LOADING_ON_OUTSIDE_HOLD + +A value is read outside the `loading on(x)` region that waits on it, so that read holds the change: the region's +fallback never shows and the old content stays up with no sign of the wait (CN-3e). Move the read under the region, or +read `latest x` there. Solid warns with the same code at run time. + +```rx before +export default component App() { + source id := 1 + data = await fetch("d:" + id) + {errored fallback(e) {

error: {e.message}

} { +
{loading on(id) fallback {

spinner

} {

{data}

}} {loading fallback {

spinner

} {

{data}

}}
+ }} +} +``` + +## Components, regions and contexts + +### UNBOUND + +The name is not declared where it is read. A component sees its declaration site, not its caller (RG-7a): pass the +value as a prop, provide it in a context, or import it. + +```rx before +component Row(props) {

{caption}

} +component List(props) { + caption = "hi" + +} +export default component App() { + +} +``` + +```rx after +component Row(props: { caption: string }) {

{props.caption}

} +component List(props) { + caption = "hi" + +} +export default component App() { + +} +``` + +### UNKNOWN_COMPONENT + +A capitalised tag names a component declared or imported in this module (RG-4a). + +```rx before +export default component App() { + +} +``` + +```rx after +component Nope(props) {

nope

} +export default component App() { + +} +``` + +### COMPONENT_AS_VALUE + +A component is applied in markup, ``, not stored or called as a function (RG-4a). + +```rx before +component Greeting(props) {

{props.name}

} +export default component App() { + x = Greeting +

{x}

+} +``` + +```rx after +component Greeting(props: { name: string }) {

{props.name}

} +export default component App() { + +} +``` + +### INSTANTIATION_NOT_BOUND + +A `fn` that declares state makes new state each time it is called, so its result is bound to a name, `x = f(…)`, and +the name is read (E-9, RG-6). + +```rx before +export default component App() { + fn counter(ref base) { + source extra := 0 + base + extra + } + source n := 1 +

{counter(n)}

+} +``` + +```rx after +export default component App() { + fn counter(ref base) { + source extra := 0 + base + extra + } + source n := 1 + c = counter(n) +

{c}

+} +``` + +### REGION_ESCAPE + +A closure that captures something from a region that ends sooner (a `for` row, an `if` branch) is stored where it +outlives that region (O-3). Keep the state at the level that stores the closure, or pass the value rather than a +closure over it. + +### UNSTABLE_LIST_IDENTITY + +The rows of a `for` are rebuilt as fresh records on every change, so every row's state and effects start over +(ST-4b). Declare a key, `rows key id = …`, so rows keep identity. + +```rx before +export default component App() { + source rows := [{ id: 1, name: "a" }, { id: 2, name: "b" }] + view = map(rows, fn(r) => { id: r.id, name: r.name + "!" }) + {for r in view { + effect (r.name) { log(r.id, $0) } +

{r.name}

+ }} +} +``` + +```rx after +export default component App() { + source rows := [{ id: 1, name: "a" }, { id: 2, name: "b" }] + view key id = map(rows, fn(r) => { id: r.id, name: r.name + "!" }) + {for r in view { + effect (r.name) { log(r.id, $0) } +

{r.name}

+ }} +} +``` + +### CONTEXT_NOT_FOUND + +`use x` reads the nearest provision of context `x` above the region, and some path that renders it has none (RG-7b). +Provide it above the component (`provide x = …`), or give the context a default (`context x: T = v`). + +```rx before +context room: number +component Room(props: { id: number }) { +

{(use room) == props.id ? "*" : "-"}

+} +export default component App() { + +} +``` + +```rx after +context room: number +component Room(props: { id: number }) { +

{(use room) == props.id ? "*" : "-"}

+} +export default component App() { + provide room = 1 + +} +``` + +### CONTEXT_AS_VALUE + +A context is read with `use`, which gives the nearest provision (RG-7): `{use theme}`, not `{theme}`. + +### NOT_A_CONTEXT + +`provide` and `use` name a `context` declaration (RG-7). Declare one, `context picked: number`, and provide it. + +```rx before +export default component App() { + source picked := 1 + provide picked = 2 + {picked} +} +``` + +```rx after +context picked: number +export default component App() { + provide picked = 2 + {use picked} +} +``` + +### SOURCE_CONTEXT + +A context is read-only beneath its provision (O-4); `context x: source T` was withdrawn (RG-7c, 2026-10-31). Provide the +value and the writes you allow, as actions: `context picked: { current: number; set: (v: number) => void }`. + +## Modules + +### TOP_LEVEL_MARKUP + +A module is declarations (MO-1c). The app's view is a component: `export default component App() { … }`. + +### SHADOWED_IMPORT + +A local declaration has the name of an import (MO-1d). Rename one: `import { initials as initialsOf } from "./store.rx"`. + +### NOT_EXPORTED + +The module, or its `.d.rx` declaration file, does not export that name (MO-6, MO-8). Check the spelling, or declare the +export. + +### MODULE_NOT_FOUND + +No file at that import path (MO-6). `.rx` modules are imported with their extension, `"./ui.rx"`; JavaScript modules +without it. + +### MODULE_CYCLE + +Two modules import each other, directly or through others (MO-5). Move what both need into a third module. + +### IMPORT_ROW_MISMATCH + +An import restates what its source already declares (MO-4, MO-8, SF-5): `pure` on a function that is io, `fails(…)` on +an `.rx` module (its rows are its signature's), or `server` / `client` on a name its `.d.rx` declares otherwise. Drop +the annotation on the import and let the declaration say it. + +## Server functions + +### SERVER_CAPTURE + +A server function runs in its own request on the server, so it cannot read the client's state: a module source, a +context (`use`), `refresh`, `affects`, `action { … }` (SF-3). Pass what it needs as an argument, and do the client's +part in the action that awaited the call. + +```rx +source n := 1 +server fn f(v: number) { return v } // was: server fn f() { return n } +x = await f(n) catch (e) => 0 +export default component App() { +

{x}

+} +``` + +### SERVER_WRITE + +A server function cannot write client state (SF-4). Return the value and write it in the action that awaited the call: +`let r = await save(x); status := r`. + +### SERVER_ONLY + +A `server` JS import is not in the client bundle (SF-5a). Call it in a `server fn` body and await that from the client. + +### CLIENT_IN_SERVER + +A `client` JS import (the browser's API) is called in a server function's body, which runs on the server (SF-5c). Call +it from the client and pass the value as an argument. + +### CLIENT_NOT_AWAITED + +In reactive scope a `client` JS function is a client question, asked once the browser has the page (SV-7b), so it is +awaited: `width = await viewport() -> 0`. + +### CLIENT_QUESTION_UNHELD + +The server never asks a client question, so the page needs a `loading` region above the reader, or a first paint on +the await, `await viewport() -> 0` (SV-7b). + +## Markup and styles + +### CONTENT_MODEL + +The browser's HTML parser rewrites some nestings (a `` outside a table, a `
` inside a `

`), so the page the +server sends is not the tree the client builds and hydration fails (SV-7d). Nest the elements the way HTML allows. + +### STYLE_PLACEMENT + +A view has one `

x

+} +``` + +```rx after +export default component App() { + +

x

+} +``` + +## Types (`rx-tsc`, the editor) + +These come from the TypeScript layer, which checks the program's projection (13). + +### MISSING_AWAIT + +An equation's value is a promise or a stream, which Solid would consume as a value (R-1a, TY-5b). Write `await e`, or +`await* e` for a stream. + +### WIRE_VALUE + +A server function's result or parameter is not data: a function or a class instance does not cross the wire (SF). Return +plain data. diff --git a/guide/language.md b/guide/language.md index 8c6dfd46..d3271437 100644 --- a/guide/language.md +++ b/guide/language.md @@ -3,7 +3,7 @@ ReactiveScript is TypeScript's expressions and JSX, plus a few reactive forms spelled with words. It compiles to Solid 2.0. This page is the whole working language; `async.md` is how to talk to a server; `reference.md` is the grammar and the rules on one page. The rules cited (E-1, AC-3, …) are in full in `spec/`; you don't need them to write -code. +code. When the compiler reports an error, `diagnostics.md` has its code: why, and the fix. ## Modules diff --git a/ref/src/modules.ts b/ref/src/modules.ts index d38e1a38..ae9c0837 100644 --- a/ref/src/modules.ts +++ b/ref/src/modules.ts @@ -27,12 +27,12 @@ export function loadModules(entry: string, read: (path: string) => string | unde const src = read(path); if (src === undefined) return; // reported at the import that names it let p: Program; - try { p = parseProgram(src); } catch (e) { if (e instanceof ParseError) throw new ParseError(`${path}: ${e.message}`); throw e; } + try { p = parseProgram(src); } catch (e) { if (e instanceof ParseError) throw Object.assign(new ParseError(`${path}: ${e.message}`), { code: e.code }); throw e; } programs.set(path, p); state.set(path, "busy"); for (const d of p.decls) { if (d.k === "import" && !isRx(d.from) && d.from.startsWith(".")) { // MO-8: a JS module with a declaration file beside it const dts = joinPath(path, d.from.replace(/\.(m?js|ts)$/, "") + ".d.rx"); - if (!declarations.has(dts)) { const src = read(dts); if (src !== undefined) { try { declarations.set(dts, parseDeclarations(src)); } catch (e) { if (e instanceof ParseError) throw new ParseError(`${dts}: ${e.message}`); throw e; } } } + if (!declarations.has(dts)) { const src = read(dts); if (src !== undefined) { try { declarations.set(dts, parseDeclarations(src)); } catch (e) { if (e instanceof ParseError) throw Object.assign(new ParseError(`${dts}: ${e.message}`), { code: e.code }); throw e; } } } const ds = declarations.get(dts); if (ds) { d.declared = dts; d.declaredErrors = ds.filter(x => x.kind === "error").map(x => x.name); d.declaredPure = ds.filter(x => x.kind === "fn" && x.pure).map(x => x.name); d.declaredSide = Object.fromEntries(ds.flatMap(x => x.kind === "fn" && x.side ? [[x.name, x.side]] : [])); } continue; diff --git a/ref/src/parse.ts b/ref/src/parse.ts index d669669b..bdc5143d 100644 --- a/ref/src/parse.ts +++ b/ref/src/parse.ts @@ -1,7 +1,36 @@ // Hand-rolled scanner/parser for the abstract syntax (spec/02-core.md §1). import type { Decl, Expr, Markup, Param, Program, Stmt, Target } from "./ast.ts"; -export class ParseError extends Error {} +/** A parse error; `code` names the habit it looks like when `hint` recognises one (guide/diagnostics.md), else `PARSE`. */ +export class ParseError extends Error { code = "PARSE"; } + +const JS_APIS = /\b(useState|useReducer|useMemo|useCallback|useEffect|useRef|createSignal|createMemo|createEffect|createStore|createResource|createAsync)\s*\(/; +/** What a parse failure at `i` most likely meant, when the line reads like JavaScript, React or Solid: `[code, text]`. + * `src/parse.rs` `hint` is the same function. */ +export function hint(src: string, i: number, msg: string): [string, string] | null { + const rest = src.slice(i); + const at = rest.length && !/^\s*$/.test(rest.split("\n")[0]) ? i : src.slice(0, i).trimEnd().length - 1; + const p = Math.max(0, at); + const lineStart = (k: number) => src.slice(0, k).lastIndexOf("\n") + 1; + const line = src.slice(lineStart(p), (src.indexOf("\n", p) + 1 || src.length + 1) - 1).trim(); + const before = src.slice(lineStart(i), i); + const name = /([A-Za-z_$][A-Za-z0-9_$.]*)\s*$/.exec(before)?.[1] ?? "x"; + if (msg.startsWith("W-2") && rest.startsWith(":=") && /=>\s*[A-Za-z_$][A-Za-z0-9_$.]*\s*$/.test(before)) + return ["REACTIVE_WRITE_IN_OWNED_SCOPE", `an arrow that writes takes a braced body, \`() => { ${name} := … }\`: an expression-bodied arrow is a pure function (SC-3)`]; + if (/^(\+\+|--|(\*\*|\|\||&&|\?\?|[-+*\/%])=|=(?![=>]))/.test(rest)) + return ["ASSIGNMENT", `a source is written with \`:=\`, as a statement in a handler or action: \`${name} := ${name} + 1\`, or \`${name} := v => v + 1\` (W-1, W-6); .rx has no \`=\`, \`+=\` or \`++\` on state`]; + if (/^(export\s+)?(default\s+)?(async\s+)?function\b/.test(line)) + return ["JS_FUNCTION", "`function` is not .rx: a pure function is `fn f(x) => …`, one that writes or awaits is `action f(x) { … }`, one that renders is `component F(props) { … }`"]; + const local = /^(const|let|var)\b/.exec(line); + if (local) + return ["JS_LOCAL", `\`${local[1]}\` declares a local only in a handler or action body: in a component or at a module's top level, state is \`source x := …\` and a value computed from others is an equation, \`x = …\``]; + if (/^return\b/.test(line)) + return ["JS_RETURN", "a component has no `return`: its body is declarations, then its markup"]; + const api = JS_APIS.exec(line); + if (api) + return ["JS_API", `\`${api[1]}\` is not .rx: state is \`source x := …\`, a value computed from others is \`x = …\`, a side effect is \`effect (x) { … }\``]; + return null; +} let viewAt = 0; /** The offset where a program's view begins (after its last declaration) — for tools that edit programs. */ export function viewStart(src: string): number { parseProgram(src); return viewAt; } @@ -25,7 +54,13 @@ class Cursor { startsWith(s: string) { return this.src.startsWith(s, this.i); } eat(s: string) { if (this.startsWith(s)) { this.i += s.length; return true; } return false; } expect(s: string) { if (!this.eat(s)) this.fail(`expected '${s}'`); } - fail(msg: string): never { throw new ParseError(`line ${this.line}: ${msg} near '${this.src.slice(this.i, this.i + 20)}'`); } + fail(msg: string): never { + const h = hint(this.src, this.i, msg); + const near = this.src.slice(this.i, this.i + 20).split("\n")[0]; + const e = new ParseError(`line ${this.line}: ${msg} ${near.trim() ? `near '${near}'` : "at the end of the line"}${h ? ` — ${h[1]}` : ""}`); + if (h) e.code = h[0]; + throw e; + } ident(): string | null { const m = /^[A-Za-z_$][A-Za-z0-9_$]*/.exec(this.src.slice(this.i)); if (!m) return null; @@ -85,7 +120,7 @@ export function parseProgram(src: string): Program { viewAt = c.i; const view = parseMarkup(c, null); c.ws(); - if (!c.eof()) c.fail("declaration or markup"); + if (!c.eof()) c.fail("expected a declaration or markup"); const dflt = decls.filter(d => d.k === "component" && d.isDefault); if (dflt.length > 1) c.fail("two default components: a module has one entry"); if (view.length === 0 && dflt.length) return { decls, view: [{ k: "el", tag: (dflt[0] as { name: string }).name, attrs: [], children: [], line: dflt[0].line }] }; // MO-1c: the mounted view is the default component, applied @@ -488,7 +523,7 @@ function parseMarkup(c: Cursor, closeTag: string | null): Markup[] { // outside an element, bare text is not markup: a block is declarations, then markup if (s.trim() === "") { if (c.peek() === "\n") c.i++; continue; } if (s.includes(":=")) c.fail("W-2: write in reactive scope (no statement position)"); - c.fail("declaration or markup"); + c.fail("expected a declaration or markup"); } if (broke && out.length && out[out.length - 1].k === "text") out.push({ k: "text", s: " " }); // text on two lines: one space between if (s) out.push({ k: "text", s }); diff --git a/ref/src/scenario.ts b/ref/src/scenario.ts index fdc03af7..d6ba8f85 100644 --- a/ref/src/scenario.ts +++ b/ref/src/scenario.ts @@ -161,7 +161,7 @@ export function runScenario(sc: Scenario): Result { continue; } const rule = e instanceof RuleError ? e.rule : e instanceof ParseError ? (/([A-Z]+-\d+)/.exec(e.message)?.[1] ?? "parse") : "crash"; - if (rule === rj.rule) lines.push(` ✓ rejected(${rj.rule}): ${(e as Error).message}`); + if (rule === rj.rule || (e instanceof ParseError && e.code === rj.rule)) lines.push(` ✓ rejected(${rj.rule}): ${(e as Error).message}`); else { ok = false; lines.push(` ✗ rejected(${rj.rule}): got ${rule}: ${(e as Error).message}`); } } } diff --git a/scenarios/S-parse-hints.md b/scenarios/S-parse-hints.md new file mode 100644 index 00000000..5b49203f --- /dev/null +++ b/scenarios/S-parse-hints.md @@ -0,0 +1,95 @@ +# S-parse-hints — JavaScript habits name their .rx form + +Rules exercised: W-1, W-2, W-6, SC-3, 07. Each rejected variant is a line a JavaScript, React or Solid writer would +write; the parse error carries the code (guide/diagnostics.md) and the `.rx` it most likely meant. + +## Program + +``` +export default component App() { + source n := 0 + double = n * 2 + +} +``` + +## Frames + +| instant | action | frame | +| ------- | ------------------- | ----- | +| 0 | mount | `0 0` | +| 1 | handler `n := 2` | `2 4` | + +## Rejected variants + +``` +-- reject: JS_LOCAL +export default component App() { + const n = 1 +

{n}

+} +``` + +``` +-- reject: JS_LOCAL +let n = 1 +export default component App() { +

{n}

+} +``` + +``` +-- reject: JS_FUNCTION +function twice(x) { return x * 2 } +export default component App() { +

{twice(1)}

+} +``` + +``` +-- reject: JS_RETURN +export default component App() { + source n := 1 + return

{n}

+} +``` + +``` +-- reject: JS_API +export default component App() { + [n, setN] = createSignal(0) +

{n}

+} +``` + +``` +-- reject: ASSIGNMENT +export default component App() { + source n := 0 + +} +``` + +``` +-- reject: ASSIGNMENT +export default component App() { + source n := 0 + +} +``` + +``` +-- reject: ASSIGNMENT +export default component App() { + source n := 0 + +} +``` + +``` +-- reject: REACTIVE_WRITE_IN_OWNED_SCOPE +export default component App() { + source n := 0 + +} +``` diff --git a/spec/99-diagnostics.md b/spec/99-diagnostics.md index 28e01b23..eff454bd 100644 --- a/spec/99-diagnostics.md +++ b/spec/99-diagnostics.md @@ -150,6 +150,22 @@ equation written the long way, with a one-instant tear, but also how a source is synced into a JS-owned one) stays advisory. `DYNAMIC_ASYNC_COMPONENT` is a type question for the type layer (13); `UNRECOGNIZED_INSERT_VALUE` stays Solid's, at run time (13 TY-3b). `LOADING_ON_OUTSIDE_HOLD` was one; since 2026-10-30 (Ryan) it is an error, 08 CN-3e: the old content stays up with no sign of the wait, a silent hold, which is a defect, not advice. (`SERVER_WRITE` was one; 12 SF-4 makes it a row rule.) +## Parse errors that name a habit + +Not Solid codes: a parse error (U by construction) whose line reads like JavaScript, React or Solid carries the code of +the habit and the `.rx` it most likely meant, appended to the parser's own message (`hint` in `ref/src/parse.ts` and +`compiler/src/parse.rs`; scenario S-parse-hints). Any other parse error is `PARSE`. Every code, here and above, has a +section with a fix in `guide/diagnostics.md`, and the compiler's tests check its examples. + +| Code | What it looks like | +| ------------ | -------------------------------------------------------- | +| `JS_LOCAL` | `const` / `let` / `var` in a component or at top level | +| `JS_FUNCTION`| `function f() { … }` | +| `JS_RETURN` | `return
…
` in a component | +| `JS_API` | `createSignal(…)`, `useState(…)`, … on a failing line | +| `ASSIGNMENT` | `x = …`, `x += …`, `x++` where a write `x := …` was meant (W-1) | +| `REACTIVE_WRITE_IN_OWNED_SCOPE` | `() => x := …`: the arrow needs a braced body (W-2, SC-3) | + ## Counting | bin | codes | diff --git a/tooling/rx-language-server/bin/tsc.js b/tooling/rx-language-server/bin/tsc.js index 24d77d48..7f8d89b2 100755 --- a/tooling/rx-language-server/bin/tsc.js +++ b/tooling/rx-language-server/bin/tsc.js @@ -8,7 +8,7 @@ // every `.rx` module in the program: a module that does not parse has no projection, so TypeScript alone would pass it. const path = require("node:path"); const { runTsc } = require("@volar/typescript/lib/quickstart/runTsc"); -const { rxLanguagePlugin, analyses } = require("../src/index.js"); +const { rxLanguagePlugin, analyses, guideUrl } = require("../src/index.js"); const tsc = require.resolve("typescript/lib/tsc"); @@ -16,15 +16,18 @@ process.on("exit", code => { const watching = process.argv.includes("--watch") || process.argv.includes("-w"); if (watching) return; let errors = 0; + const codes = new Set(); for (const { file, result } of analyses()) { for (const d of result.diagnostics ?? []) { errors++; + codes.add(d.code); const where = d.range ? `${d.range.start.line}:${d.range.start.column + 1}` : "1:1"; process.stdout.write(`${path.relative(process.cwd(), file)}:${where} - error ${d.code}: ${d.message} (${d.rule})\n`); } } if (errors) { process.stdout.write(`\nFound ${errors} ReactiveScript error${errors === 1 ? "" : "s"}.\n`); + for (const c of codes) process.stdout.write(`${c}: why, and the fix — ${guideUrl(c)}\n`); if (!code) process.exitCode = 1; } }); diff --git a/tooling/rx-language-server/src/index.js b/tooling/rx-language-server/src/index.js index 78b417e0..b6f7582b 100644 --- a/tooling/rx-language-server/src/index.js +++ b/tooling/rx-language-server/src/index.js @@ -3,6 +3,9 @@ // type errors come back through them. The crate's own diagnostics (rule IDs, spec/99) are a service of their own. const { analyze, preludeFor } = require("./rxc"); +/** The page that explains a diagnostic code and its fix (the compiler's guide/diagnostics.md, one section a code). */ +const guideUrl = code => `https://github.com/solidjs/reactivescript/blob/main/guide/diagnostics.md#${String(code).toLowerCase()}`; + /** Every feature, where the projection copies the `.rx`'s text (a name, a member, a literal, a type, a tag). */ const EXACT = { verification: true, completion: true, semantic: true, navigation: true, structure: true, format: false }; /** Where it wrote text for a piece of the `.rx` (an expression, a statement): only for placing type errors. */ @@ -87,6 +90,7 @@ function rxDiagnostics() { severity: 1, source: "rx", code: d.code, + codeDescription: { href: guideUrl(d.code) }, message: `${d.message} (${d.rule})`, })); }, @@ -98,4 +102,4 @@ function rxDiagnostics() { /** Every `.rx` module analyzed so far, with its last analysis (the command line reports their crate diagnostics). */ const analyses = () => [...cache].filter(([f]) => isModule(f)).map(([file, { result }]) => ({ file, result })); -module.exports = { rxLanguagePlugin, rxDiagnostics, analysis, analyses }; +module.exports = { rxLanguagePlugin, rxDiagnostics, analysis, analyses, guideUrl };