From 31802e54f376baba20f0509d135cea0dedfd0053 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:05:56 +0100 Subject: [PATCH 01/38] parser: ${...} holes and typed payloads for macro quotes A hole ${expr} parses, in expression, pattern and type position, as the extension res.hole whose payload is the expression, so the parsetree gains no node kind. %type(...) and %pat(...) take a type and a pattern as payload, and an extension named by a module path takes types as arguments in a type position. The scanner accepts $ inside identifiers only for macro-expanded source. Co-authored-by: Jaap Frolich Session: https://jakes-mac-mini.tail23a77e.ts.net:8443/session/os-01a1ca09-2757-709a-bbb1-e57ccc4d104f Signed-off-by: Jaap Frolich --- compiler-rust/src/parser/expr.rs | 18 +++++- compiler-rust/src/parser/grammar.rs | 7 +++ compiler-rust/src/parser/module.rs | 92 +++++++++++++++++++++++++++++ compiler-rust/src/parser/pattern.rs | 9 +++ compiler-rust/src/parser/scanner.rs | 14 ++++- compiler-rust/src/parser/state.rs | 6 ++ compiler-rust/src/parser/token.rs | 4 ++ compiler-rust/src/parser/typ.rs | 12 ++++ compiler-rust/tests/macros.rs | 81 +++++++++++++++++++++++++ 9 files changed, 240 insertions(+), 3 deletions(-) create mode 100644 compiler-rust/tests/macros.rs diff --git a/compiler-rust/src/parser/expr.rs b/compiler-rust/src/parser/expr.rs index 676119088a..404fed29bf 100644 --- a/compiler-rust/src/parser/expr.rs +++ b/compiler-rust/src/parser/expr.rs @@ -1503,8 +1503,13 @@ pub fn parse_atomic_expr(p: &mut Parser<'_>) -> Expression { p.next(); let name = super::module::parse_extension_id(p, id_start_idx); - let payload = super::module::parse_payload_region(p); - let payload = super::module::raw_source_extension_payload(p, &name, payload); + let payload = match super::module::parse_quote_payload(p, &name) { + Some(payload) => payload, + None => { + let payload = super::module::parse_payload_region(p); + super::module::raw_source_extension_payload(p, &name, payload) + } + }; let loc = p.mk_loc_idx_to_prev_end(start_pos_idx); Expression { @@ -1513,6 +1518,15 @@ pub fn parse_atomic_expr(p: &mut Parser<'_>) -> Expression { pexp_attributes: Attributes::new(), } } + Token::DollarLbrace => { + let extension = super::module::parse_hole_extension(p); + let loc = p.mk_loc_idx_to_prev_end(start_pos_idx); + Expression { + pexp_desc: ExpressionDesc::Pexp_extension(Box::new(extension)), + pexp_loc: loc, + pexp_attributes: Attributes::new(), + } + } Token::LessThan => parse_jsx(p), Token::Backtick | Token::TemplateTail { .. } | Token::TemplatePart { .. } => { // OCaml: after parse_template_expr, overrides location to [start_pos, p.prev_end_pos) diff --git a/compiler-rust/src/parser/grammar.rs b/compiler-rust/src/parser/grammar.rs index cfa7af3d67..2f81aed7fb 100644 --- a/compiler-rust/src/parser/grammar.rs +++ b/compiler-rust/src/parser/grammar.rs @@ -237,6 +237,7 @@ pub fn is_atomic_pattern_start(token: &Token<'_>) -> bool { | Token::Dict | Token::Exception | Token::Percent + | Token::DollarLbrace ) } @@ -261,6 +262,7 @@ pub fn is_atomic_expr_start(token: &Token<'_>) -> bool { | Token::LessThan | Token::Module | Token::Percent + | Token::DollarLbrace | Token::Forwardslash | Token::ForwardslashDot | Token::Regex { .. } @@ -279,6 +281,7 @@ pub fn is_atomic_typ_expr_start(token: &Token<'_>) -> bool { | Token::Uident(_) | Token::Lident(_) | Token::Percent + | Token::DollarLbrace ) } @@ -308,6 +311,7 @@ pub fn is_expr_start(token: &Token<'_>) -> bool { | Token::MinusDot | Token::Module | Token::Percent + | Token::DollarLbrace | Token::Plus | Token::PlusDot | Token::Bnot @@ -362,6 +366,7 @@ pub fn is_block_expr_start(token: &Token<'_>) -> bool { | Token::Module | Token::Open | Token::Percent + | Token::DollarLbrace | Token::Plus | Token::PlusDot | Token::String(_) @@ -423,6 +428,7 @@ pub fn is_pattern_start(token: &Token<'_>) -> bool { | Token::Hash | Token::Exception | Token::Percent + | Token::DollarLbrace | Token::Module | Token::At ) @@ -470,6 +476,7 @@ pub fn is_typ_expr_start(token: &Token<'_>) -> bool { | Token::Lident(_) | Token::Module | Token::Percent + | Token::DollarLbrace | Token::Lbrace ) } diff --git a/compiler-rust/src/parser/module.rs b/compiler-rust/src/parser/module.rs index c357c76403..69ab0c6785 100644 --- a/compiler-rust/src/parser/module.rs +++ b/compiler-rust/src/parser/module.rs @@ -4104,6 +4104,98 @@ pub fn parse_extension_id(p: &mut Parser<'_>, start_pos_idx: PosIdx) -> Located< with_loc(id_idx, p.mk_loc_idx_to_prev_end(start_pos_idx)) } +/// Name of the extension a macro quote hole `${expr}` is kept as. +pub const HOLE_EXTENSION: &str = "res.hole"; + +/// `${expr}`: a hole in a macro quote (`%code(...)`, `%type(...)`, +/// `%pat(...)`). It is an extension node named [`HOLE_EXTENSION`] whose +/// payload is the expression, so no parsetree node kind is added. +pub(super) fn parse_hole_extension(p: &mut Parser<'_>) -> Extension { + let start_pos_idx = p.start_pos_idx(); + p.expect(Token::DollarLbrace); + let expr = super::expr::parse_expr(p); + p.expect(Token::Rbrace); + let loc = p.mk_loc_idx_to_prev_end(start_pos_idx); + let expr_loc = expr.pexp_loc; + let expr_idx = p.arena_mut().push_expr(expr); + let name = p.arena_mut().push_string(HOLE_EXTENSION); + let item = StructureItem { + pstr_desc: StructureItemDesc::Pstr_eval(Box::new((expr_idx, Attributes::new()))), + pstr_loc: expr_loc, + }; + (with_loc(name, loc), Payload::PStr(Box::new(vec![item]))) +} + +/// The payload of the quotes `%type(...)` and `%pat(...)`, which hold a type +/// and a pattern where an extension payload is otherwise a structure. +pub(super) fn parse_quote_payload(p: &mut Parser<'_>, id: &StringLoc) -> Option { + if !(p.token == Token::Lparen && p.start_pos.cnum == p.prev_end_pos.cnum) { + return None; + } + let quote_type = match p.arena().get_string(id.txt) { + "type" => true, + "pat" => false, + _ => return None, + }; + p.leave_breadcrumb(Grammar::AttributePayload); + p.next(); + let payload = if quote_type { + let typ = super::typ::parse_typ_expr(p); + Payload::PTyp(p.arena_mut().push_core_type(typ)) + } else { + let pat = super::pattern::parse_pattern(p); + Payload::PPat(Box::new((p.arena_mut().push_pat(pat), None))) + }; + p.expect(Token::Rparen); + p.eat_breadcrumb(); + Some(payload) +} + +/// The arguments of a macro in a type position, `%Partial.t(user)`: the +/// name is a module path, which no PPX extension is, and the arguments are +/// types. One argument is kept as that type, several as a tuple of them. +pub(super) fn parse_macro_type_arguments(p: &mut Parser<'_>, id: &StringLoc) -> Option { + if !(p.token == Token::Lparen && p.start_pos.cnum == p.prev_end_pos.cnum) { + return None; + } + if !p + .arena() + .get_string(id.txt) + .starts_with(|c: char| c.is_ascii_uppercase()) + { + return None; + } + p.leave_breadcrumb(Grammar::AttributePayload); + let start_pos_idx = p.start_pos_idx(); + p.next(); + let mut types = Vec::new(); + while p.token != Token::Rparen && p.token != Token::Eof { + let typ = super::typ::parse_typ_expr(p); + types.push(p.arena_mut().push_core_type(typ)); + if p.token == Token::Comma { + p.next(); + } else { + break; + } + } + p.expect(Token::Rparen); + p.eat_breadcrumb(); + let payload = match types.as_slice() { + [] => Payload::PStr(Box::default()), + [single] => Payload::PTyp(*single), + _ => { + let loc = p.mk_loc_idx_to_prev_end(start_pos_idx); + let tuple = CoreType { + ptyp_desc: CoreTypeDesc::Ptyp_tuple(p.arena_mut().push_type_list(&types)), + ptyp_loc: loc, + ptyp_attributes: Attributes::new(), + }; + Payload::PTyp(p.arena_mut().push_core_type(tuple)) + } + }; + Some(payload) +} + /// OCaml `parse_extension ?(module_language = false)` (res_core.ml:7683-7689). pub(super) fn parse_extension(p: &mut Parser<'_>, module_language: bool) -> Extension { // Capture start position BEFORE consuming % or %% so extension location includes it diff --git a/compiler-rust/src/parser/pattern.rs b/compiler-rust/src/parser/pattern.rs index c4a3d3cc23..fa3be91be1 100644 --- a/compiler-rust/src/parser/pattern.rs +++ b/compiler-rust/src/parser/pattern.rs @@ -302,6 +302,15 @@ fn parse_pattern_with(p: &mut Parser<'_>, alias: bool, or_: bool) -> Pattern { attrs.clone(), ) } + Token::DollarLbrace => { + let extension = super::module::parse_hole_extension(p); + let loc = p.mk_loc_idx_to_prev_end(start_pos_idx); + pat( + PatternDesc::Ppat_extension(Box::new(extension)), + loc, + attrs.clone(), + ) + } Token::Eof => { p.err_unexpected(); recover::default_pattern(p.arena_mut()) diff --git a/compiler-rust/src/parser/scanner.rs b/compiler-rust/src/parser/scanner.rs index 038d61d691..68402aaa51 100644 --- a/compiler-rust/src/parser/scanner.rs +++ b/compiler-rust/src/parser/scanner.rs @@ -45,6 +45,9 @@ pub struct ScannerSnapshot { /// The lexical scanner state. #[derive(Debug)] pub struct Scanner<'src> { + /// Macro-expanded source: identifiers may contain `$`, which source + /// written by hand cannot, so generated names never collide with it. + pub generated_names: bool, /// Source filename (interned string index for sharing in marshal output). pub filename: StrIdx, /// Source code being scanned. @@ -97,6 +100,7 @@ impl<'src> Scanner<'src> { }; Self { + generated_names: false, filename, src, bytes, @@ -409,7 +413,9 @@ impl<'src> Scanner<'src> { let start_off = self.offset; // Skip valid identifier characters (all ASCII, so byte == char) - while matches!(self.ch, 'A'..='Z' | 'a'..='z' | '0'..='9' | '_' | '\'') { + while matches!(self.ch, 'A'..='Z' | 'a'..='z' | '0'..='9' | '_' | '\'') + || (self.ch == '$' && self.generated_names && self.peek() != '{') + { self.next(); } @@ -1048,6 +1054,12 @@ impl<'src> Scanner<'src> { } } + // A hole in a macro quote: `%code(${e} + 1)`. + '$' if self.peek() == '{' => { + self.next2(); + Token::DollarLbrace + } + '|' => match (self.peek(), self.peek2()) { ('|', '|') => { self.next3(); diff --git a/compiler-rust/src/parser/state.rs b/compiler-rust/src/parser/state.rs index e8e1d58371..ee74dd7965 100644 --- a/compiler-rust/src/parser/state.rs +++ b/compiler-rust/src/parser/state.rs @@ -191,6 +191,12 @@ impl<'src> Parser<'src> { parser } + /// Accept `$` inside identifiers, as macro-expanded source uses for + /// generated names. Call before the first token is consumed. + pub fn set_generated_names(&mut self, enabled: bool) { + self.scanner.generated_names = enabled; + } + /// Create a location for the current token (start_pos to end_pos). /// Uses the stored start_pos_idx and end_pos_idx directly. pub fn mk_loc_current(&mut self) -> LocIdx { diff --git a/compiler-rust/src/parser/token.rs b/compiler-rust/src/parser/token.rs index ffd2d0fbf3..8d9276c04e 100644 --- a/compiler-rust/src/parser/token.rs +++ b/compiler-rust/src/parser/token.rs @@ -238,6 +238,8 @@ pub enum Token<'a> { Percent, /// `%%` PercentPercent, + /// `${`: opens a hole in a macro quote (`%code(...)`). + DollarLbrace, /// ` `` ` (backtick) Backtick, /// `<<` (left shift) @@ -522,6 +524,7 @@ impl<'a> Token<'a> { Token::AtAt => Token::AtAt, Token::Percent => Token::Percent, Token::PercentPercent => Token::PercentPercent, + Token::DollarLbrace => Token::DollarLbrace, Token::Backtick => Token::Backtick, Token::LeftShift => Token::LeftShift, Token::RightShift => Token::RightShift, @@ -642,6 +645,7 @@ impl<'a> std::fmt::Display for Token<'a> { Token::AtAt => write!(f, "@@"), Token::Percent => write!(f, "%"), Token::PercentPercent => write!(f, "%%"), + Token::DollarLbrace => write!(f, "${{"), Token::Comment(c) => write!(f, "Comment{}", c), Token::List => write!(f, "list{{"), Token::Dict => write!(f, "dict{{"), diff --git a/compiler-rust/src/parser/typ.rs b/compiler-rust/src/parser/typ.rs index b053d0a563..12d90628f1 100644 --- a/compiler-rust/src/parser/typ.rs +++ b/compiler-rust/src/parser/typ.rs @@ -801,6 +801,15 @@ fn parse_atomic_typ_expr_with_start( p.next(); parse_package_type_with_parens(p, start_pos_idx) } + Token::DollarLbrace => { + let ext = super::module::parse_hole_extension(p); + let loc = p.mk_loc_idx_to_prev_end(start_pos_idx); + CoreType { + ptyp_desc: CoreTypeDesc::Ptyp_extension(Box::new(ext)), + ptyp_loc: loc, + ptyp_attributes: Attributes::new(), + } + } Token::Percent => { // Extension: %ext let ext = parse_extension(p); @@ -2131,6 +2140,9 @@ fn parse_extension(p: &mut Parser<'_>) -> Extension { p.expect(Token::Percent); let id = super::module::parse_extension_id(p, id_start_idx); + if let Some(payload) = super::module::parse_macro_type_arguments(p, &id) { + return (id, payload); + } let payload = super::module::parse_payload_region(p); let payload = super::module::raw_source_extension_payload(p, &id, payload); diff --git a/compiler-rust/tests/macros.rs b/compiler-rust/tests/macros.rs new file mode 100644 index 0000000000..a498676a5c --- /dev/null +++ b/compiler-rust/tests/macros.rs @@ -0,0 +1,81 @@ +//! End-to-end tests of compile-time macros: each test compiles a small +//! project in memory, with the standard library type-checked from source. + +use std::path::PathBuf; + +use rescript_compiler::cmi::persistent_env::ModuleRegistry; +use rescript_compiler::driver::{self, CompilerOptions}; + +fn runtime_dir() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../packages/@rescript/runtime") +} + +struct Project { + registry: ModuleRegistry, +} + +impl Project { + fn new() -> Self { + let mut registry = ModuleRegistry::new(); + let mut modules: ahash::AHashMap = Default::default(); + for entry in std::fs::read_dir(runtime_dir()).unwrap() { + let path = entry.unwrap().path(); + let Some(ext) = path.extension().and_then(|e| e.to_str()) else { + continue; + }; + if ext != "res" && ext != "resi" { + continue; + } + let name = path.file_stem().unwrap().to_str().unwrap().to_string(); + if ext == "resi" || !modules.contains_key(&name) { + modules.insert(name, path); + } + } + registry.set_source_fallback_paths(modules); + Project { registry } + } + + fn compile(&mut self, filename: &str, source: &str) -> Result { + let module_name = driver::module_name_from_source_filename(filename); + let options = CompilerOptions { + source_filename: Some(filename.to_string()), + module_name: Some(module_name.clone()), + ..Default::default() + }; + match driver::compile_source_in_process( + source, + filename, + &module_name, + &options, + &self.registry, + false, + ) { + Ok(compiled) => { + if let Some(ps) = compiled.pers_struct { + self.registry.register_module( + &module_name, + ps, + rescript_compiler::cmi::persistent_env::InMemoryModuleInfo::new( + PathBuf::from(filename), + false, + Default::default(), + false, + ), + ); + } + Ok(compiled.js_output) + } + Err(e) => Err(format!("{e:#}")), + } + } +} + +#[test] +fn plain_module_compiles() { + let mut project = Project::new(); + let js = project + .compile("Plain.res", "let double = x => x * 2\nlet xs = [1, 2]->Array.map(double)\n") + .unwrap(); + println!("{js}"); + assert!(js.contains("double")); +} From 5b1c210725e466e71a598913508dc5fbc8bd9b40 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:27:37 +0100 Subject: [PATCH 02/38] Add compile-time macros: quotes, the engine and expression macros A macro is a ReScript function marked @macro that the compiler runs while it compiles another file. It returns code written as a quote, %code(...), with ${...} holes. - macros::quote lowers the quotes of a macro's own file to calls that build the quoted source text. - macros::discover is the type checker's side: at a macro use it runs the macro and records the result as an edit of the source text. An ordinary compilation stops at the first macro use instead and asks for expansion. - macros::expand applies the edits and type checks again until a pass finds nothing to expand; the compiler then compiles the expanded source with every position mapped back to the source as written. - macros::quickjs embeds QuickJS as the engine of native builds, without clock, randomness or file access. A macro's questions to the compiler (types, files) are answered by running it again with the answer. - The runtime gains the Macro module: the code, typ and pat types, the Type, Code, Pat, Attr and Decl helpers. Files that use no macro compile exactly as before. Co-authored-by: Jaap Frolich Session: https://jakes-mac-mini.tail23a77e.ts.net:8443/session/os-01a1ca09-2757-709a-bbb1-e57ccc4d104f Signed-off-by: Jaap Frolich --- compiler-rust/Cargo.lock | 50 + compiler-rust/Cargo.toml | 5 +- compiler-rust/src/arena.rs | 4 + compiler-rust/src/cli/bsc.rs | 1 + compiler-rust/src/driver.rs | 83 +- compiler-rust/src/js_ir/mod.rs | 5 + compiler-rust/src/lib.rs | 1 + compiler-rust/src/macros/discover.rs | 1473 ++++++++++++++++++++++++++ compiler-rust/src/macros/edit.rs | 235 ++++ compiler-rust/src/macros/expand.rs | 330 ++++++ compiler-rust/src/macros/host.js | 178 ++++ compiler-rust/src/macros/mod.rs | 69 ++ compiler-rust/src/macros/quickjs.rs | 158 +++ compiler-rust/src/macros/quote.rs | 414 ++++++++ compiler-rust/src/macros/reflect.rs | 411 +++++++ compiler-rust/src/parse_arena.rs | 9 + compiler-rust/src/parser/scanner.rs | 10 +- compiler-rust/src/parser/state.rs | 23 +- compiler-rust/src/types/typecore.rs | 30 +- compiler-rust/src/types/typemod.rs | 77 +- compiler-rust/tests/macros.rs | 63 +- packages/@rescript/runtime/Macro.res | 348 ++++++ 22 files changed, 3957 insertions(+), 20 deletions(-) create mode 100644 compiler-rust/src/macros/discover.rs create mode 100644 compiler-rust/src/macros/edit.rs create mode 100644 compiler-rust/src/macros/expand.rs create mode 100644 compiler-rust/src/macros/host.js create mode 100644 compiler-rust/src/macros/mod.rs create mode 100644 compiler-rust/src/macros/quickjs.rs create mode 100644 compiler-rust/src/macros/quote.rs create mode 100644 compiler-rust/src/macros/reflect.rs create mode 100644 packages/@rescript/runtime/Macro.res diff --git a/compiler-rust/Cargo.lock b/compiler-rust/Cargo.lock index 0a0ed662e4..4f0785f57c 100644 --- a/compiler-rust/Cargo.lock +++ b/compiler-rust/Cargo.lock @@ -168,6 +168,16 @@ dependencies = [ "rustversion", ] +[[package]] +name = "cc" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ff2a8126fff0f8c839080d619675a585e61720bb12d2baceae45769fd66f155" +dependencies = [ + "find-msvc-tools", + "shlex", +] + [[package]] name = "cfg-if" version = "1.0.4" @@ -418,6 +428,12 @@ version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + [[package]] name = "fnv" version = "1.0.7" @@ -1118,6 +1134,7 @@ dependencies = [ "oxc_span", "proptest", "rayon", + "rquickjs", "serde", "serde_json", "smallvec", @@ -1129,6 +1146,33 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "rquickjs" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c5227859c4dfc83f428e58f9569bf439e628c8d139020e7faff437e6f5abaa0" +dependencies = [ + "rquickjs-core", +] + +[[package]] +name = "rquickjs-core" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e82e0ca83028ad5b533b53b96c395bbaab905a5774de4aaf1004eeacafa3d85d" +dependencies = [ + "rquickjs-sys", +] + +[[package]] +name = "rquickjs-sys" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fed0097b0b4fbb2a87f6dd3b995a7c64ca56de30007eb7e867dfdfc78324ba5" +dependencies = [ + "cc", +] + [[package]] name = "rustc-hash" version = "2.1.1" @@ -1236,6 +1280,12 @@ dependencies = [ "zmij", ] +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + [[package]] name = "simdutf8" version = "0.1.5" diff --git a/compiler-rust/Cargo.toml b/compiler-rust/Cargo.toml index 23381868c2..a11461ddbd 100644 --- a/compiler-rust/Cargo.toml +++ b/compiler-rust/Cargo.toml @@ -49,6 +49,7 @@ oxc_span = "0.49" # WASM support wasm-bindgen = { version = "0.2", optional = true } +rquickjs = { version = "0.9", optional = true } [dev-dependencies] proptest = "1.5" @@ -58,7 +59,9 @@ tempfile = "3" [features] default = ["native"] -native = ["rayon", "env_logger", "clap"] +native = ["rayon", "env_logger", "clap", "macro-quickjs"] +# The embedded JavaScript engine that runs compile-time macros. +macro-quickjs = ["rquickjs"] wasm = ["wasm-bindgen"] [profile.release] diff --git a/compiler-rust/src/arena.rs b/compiler-rust/src/arena.rs index ff08dcf545..876bc63767 100644 --- a/compiler-rust/src/arena.rs +++ b/compiler-rust/src/arena.rs @@ -159,6 +159,10 @@ impl Arena { } /// Iterate over all items with their indices. + pub fn iter_mut(&mut self) -> impl Iterator { + self.items.iter_mut() + } + pub fn iter(&self) -> impl Iterator { self.items .iter() diff --git a/compiler-rust/src/cli/bsc.rs b/compiler-rust/src/cli/bsc.rs index 77265cbcd6..c00248f946 100644 --- a/compiler-rust/src/cli/bsc.rs +++ b/compiler-rust/src/cli/bsc.rs @@ -491,6 +491,7 @@ fn run(args: Vec, registry: Option) -> Result<()> { .and_then(|spec| parse_package_output(spec)); let compiler_opts = CompilerOptions { + macro_host: None, dump_lambda: opts.dump_lambda, dump_typed_sexp: opts.dump_typed_sexp, dump_typed_sexp_locs: opts.dump_typed_sexp_locs, diff --git a/compiler-rust/src/driver.rs b/compiler-rust/src/driver.rs index 60d6659ea6..838bbed1f4 100644 --- a/compiler-rust/src/driver.rs +++ b/compiler-rust/src/driver.rs @@ -554,6 +554,9 @@ fn place_location_free_warnings( /// Compiler options that can be passed to the driver. #[derive(Clone)] pub struct CompilerOptions { + /// The JavaScript engine that runs macros. Without one, a file that + /// uses macros does not compile. + pub macro_host: Option>, /// Print the Lambda IR to stderr (like OCaml's -drawlambda) pub dump_lambda: bool, /// Print the typed tree as sexp to stderr (like OCaml's -dtyped-sexp) @@ -821,6 +824,7 @@ fn parse_diagnostics_report(parser: &Parser<'_>, source: &str, filename: &str) - impl Default for CompilerOptions { fn default() -> Self { Self { + macro_host: None, dump_lambda: false, dump_typed_sexp: false, dump_typed_sexp_locs: false, @@ -12481,6 +12485,8 @@ pub struct InProcessCompileResult { pub dumps: Vec<(DumpKind, String)>, /// The warning reports the file compile prints to stderr. pub warnings: String, + /// The source after macro expansion, when the file uses macros. + pub expanded_source: Option, } /// Owned in-process compilation state after typechecking and Lambda lowering, @@ -12649,8 +12655,75 @@ pub fn compile_source_in_process( registry: &ModuleRegistry, has_interface: bool, ) -> Result { - let mut parser = Parser::new(filename, source); + let compile = |expanded: Option<&crate::macros::edit::SourceText>| { + compile_parsed_source_in_process( + source, + expanded, + filename, + module_name, + options, + registry, + has_interface, + ) + }; + match compile(None) { + // The file uses macros: expand it, then compile the expanded source. + Err(error) if error.is::() => { + let Some(host) = options.macro_host.clone() else { + return Err(UserDiagnostic::new( + format!("{filename}: this file uses macros, and this build has no macro engine.\n"), + 2, + ) + .into()); + }; + let expanded = crate::macros::expand::expand_source( + source, + filename, + module_name, + options, + registry, + host, + )?; + match compile(Some(&expanded)) { + Err(error) if error.is::() => { + Err(UserDiagnostic::new( + format!("{filename}: macro expansion left a macro unexpanded.\n"), + 2, + ) + .into()) + } + Ok(mut compiled) => { + compiled.expanded_source = Some(expanded.text().to_string()); + Ok(compiled) + } + Err(error) => Err(error), + } + } + result => result, + } +} + +/// Compile `source`, or its macro-expanded text when the file was expanded. +fn compile_parsed_source_in_process( + source: &str, + expanded: Option<&crate::macros::edit::SourceText>, + filename: &str, + module_name: &str, + options: &CompilerOptions, + registry: &ModuleRegistry, + has_interface: bool, +) -> Result { + let mut parser = match expanded { + Some(expanded) => Parser::for_expanded_source(filename, expanded.text()), + None => Parser::new(filename, source), + }; let structure = module::parse_structure(&mut parser); + if let Some(expanded) = expanded + && !parser.has_errors() + { + // From here on every position is one of the source as written. + crate::macros::expand::remap_positions(parser.arena_mut(), expanded, source); + } let mut frontend_output = String::new(); let frontend = run_implementation_frontend( &mut parser, @@ -13000,7 +13073,7 @@ pub fn compile_preprocessed_structure_in_process_with_signature_hook( } /// A fresh type context with the stamp counter where OCaml's starts. -fn fresh_type_context() -> TypeContext { +pub(crate) fn fresh_type_context() -> TypeContext { crate::ident::Ident::set_current_time(OCAML_NON_PREDEF_STAMP_START); let id_gen = IdGenerator::with_start_stamp(OCAML_NON_PREDEF_STAMP_START); // Match OCaml's Parmatch.extra_pat which eagerly calls Ident.create "+" @@ -13013,7 +13086,7 @@ fn fresh_type_context() -> TypeContext { /// implementation or interface is typed in: the registry's units are the persistent /// environment, Pervasives (and `-open`s) opened as `Res_compmisc.initial_env` /// does (res_compmisc.ml:56-62). -fn in_process_type_check_context<'a>( +pub(crate) fn in_process_type_check_context<'a>( type_ctx: &'a TypeContext, arena: &'a crate::parse_arena::ParseArena, options: &CompilerOptions, @@ -13242,6 +13315,9 @@ pub fn compile_preprocessed_structure_in_process_until_js( let (typed_structure, final_env) = match typed { Ok(result) => result, Err(e) => { + if tctx.macro_expansion_required { + return Err(crate::macros::MacroExpansionRequired.into()); + } // As in the file compile: the warnings reported so far precede // the error report. tctx.drain_open_slot_uses(); @@ -14043,6 +14119,7 @@ pub fn finish_preprocessed_structure_in_process_from_js_boundary_with_metadata_h } }); Ok(InProcessCompileResult { + expanded_source: None, js_output: js, js_outputs, signature: pre_js.signature, diff --git a/compiler-rust/src/js_ir/mod.rs b/compiler-rust/src/js_ir/mod.rs index e013d436aa..b4d4c5806d 100644 --- a/compiler-rust/src/js_ir/mod.rs +++ b/compiler-rust/src/js_ir/mod.rs @@ -287,6 +287,11 @@ impl ModulePathResolver { }, ), (PackageInfoQuery::Script, PackageInfoQuery::Script) => { + // A module compiled in memory (the playground, tests) has no + // file to find. + if env.module_has_in_memory_info(module_name) { + return None; + } let js_file = js_name_of_module_name(module_name, import_info.file_case, ".js"); (!env.file_exists_in_load_path_uncap(&js_file)) .then_some(ModulePathResolutionError::JsNotFound { js_file }) diff --git a/compiler-rust/src/lib.rs b/compiler-rust/src/lib.rs index 47a81dfb09..4f621976e4 100644 --- a/compiler-rust/src/lib.rs +++ b/compiler-rust/src/lib.rs @@ -45,6 +45,7 @@ pub mod intern; pub mod js_ir; pub mod lambda; pub mod location; +pub mod macros; pub mod misc; pub mod name; pub mod parse_arena; diff --git a/compiler-rust/src/macros/discover.rs b/compiler-rust/src/macros/discover.rs new file mode 100644 index 0000000000..4e0c218ae7 --- /dev/null +++ b/compiler-rust/src/macros/discover.rs @@ -0,0 +1,1473 @@ +//! The type checker's side of macro expansion. +//! +//! The type checker knows where macros are used: it is the one that resolves +//! `Json.encode` to a value marked `@generic`, and it has the types a macro +//! asks about. It does not expand anything in place. In a discovery pass it +//! runs the macro and records the result as an [`Edit`] of the source text; +//! [`super::expand`] applies the edits and type checks the new text, until a +//! pass records none. +//! +//! Outside a discovery pass ([`MacroMode::Off`], every ordinary compilation) +//! the first macro use stops type checking with +//! [`TypeCheckContext::macro_expansion_required`] set, which tells the driver +//! to expand the file first. + +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; + +use serde_json::{Value, json}; + +use crate::parse_arena::{ExprIdx, LocIdx, ParseArena}; +use crate::parser::ast::{ + ArgLabel, Constant, ExpressionDesc, Extension, PatternDesc, Payload, RecFlag, + StructureItem as ParsedStructureItem, StructureItemDesc as ParsedStructureItemDesc, +}; +use crate::parser::longident::Longident; +use crate::parser::module::HOLE_EXTENSION; +use crate::types::context::TypeContext; +use crate::types::decl::ValueDescription; +use crate::types::env::Env; +use crate::types::path::{Path, PathView}; +use crate::types::predef; +use crate::types::type_expr::{TypeArg, TypeDesc, TypeExprRef}; +use crate::types::typecore::{ + BuiltinExtensionError, TypeCheckContext, TypeCoreError, TypeCoreResult, +}; +use crate::types::typedtree::{Expression, ExpressionDesc as TypedExpressionDesc}; + +use super::edit::{Edit, SourceText}; +use super::reflect::{self, TypeTable}; +use super::{MacroHost, is_macro_name, quote}; + +/// Whether the type checker expands macros. +pub enum MacroMode { + /// An ordinary compilation: a macro use asks for expansion. + Off, + /// A discovery pass of [`super::expand`]. + Discover(Box), +} + +/// A problem a macro reported, or one with how a macro is used. +#[derive(Debug, Clone)] +pub struct MacroDiagnostic { + /// Characters of the text being expanded. + pub start: u32, + pub end: u32, + pub message: String, +} + +/// A `%comptime(expr)` found by a pass: evaluated between passes, when no +/// type checker is running. +#[derive(Debug, Clone)] +pub struct ComptimeSite { + pub start: u32, + pub end: u32, + /// The expression's source text. + pub expression: String, + /// How to write a value of the expression's type as a literal. + pub shape: Value, +} + +/// A generated function: `Json.encode` at the type `user`. +struct Instance { + name: String, + /// Original offset of the top-level item the instance was generated + /// for. Items at or after that offset can call it. + ordinal: u32, +} + +/// The instances of a file, kept from pass to pass. +#[derive(Default)] +pub struct InstanceTable { + by_key: HashMap>, + names: HashSet, +} + +impl InstanceTable { + fn find(&self, key: &str, ordinal: u32) -> Option<&str> { + self.by_key + .get(key)? + .iter() + .find(|instance| instance.ordinal <= ordinal) + .map(|instance| instance.name.as_str()) + } + + fn add(&mut self, key: String, base: &str, ordinal: u32) -> String { + let mut name = base.to_string(); + let mut counter = 1; + while self.names.contains(&name) { + counter += 1; + name = format!("{base}${counter}"); + } + self.names.insert(name.clone()); + self.by_key.entry(key).or_default().push(Instance { + name: name.clone(), + ordinal, + }); + name + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum ParamKind { + /// `code<'a>`: the argument's syntax. + Code, + /// `typ`: a type. + Typ, + /// `Type.decl`: the type declaration the macro is attached to. + Decl, + /// `Decl.value`: the `let` the macro is attached to. + Binding, + /// A plain type: the argument's value, known at compile time. + Value, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum ResultKind { + Code, + Decls, + Typ, + Pat, + Other, +} + +struct Signature { + params: Vec, + result: ResultKind, +} + +fn macro_type_name(ctx: &TypeContext, ty: TypeExprRef) -> Option<(String, Vec)> { + match &*ctx.get_desc(ctx.repr(ty)) { + TypeDesc::Tconstr { path, args, .. } => Some(( + path.name(), + ctx.type_list(*args).iter().collect(), + )), + _ => None, + } +} + +fn param_kind(ctx: &TypeContext, ty: TypeExprRef) -> ParamKind { + match macro_type_name(ctx, ty).as_ref().map(|(name, _)| name.as_str()) { + Some("Macro.code") | Some("Macro.decls") => ParamKind::Code, + Some("Macro.typ") => ParamKind::Typ, + Some("Macro.Type.decl") => ParamKind::Decl, + Some("Macro.Decl.value") => ParamKind::Binding, + _ => ParamKind::Value, + } +} + +fn result_kind(ctx: &TypeContext, ty: TypeExprRef) -> ResultKind { + match macro_type_name(ctx, ty).as_ref().map(|(name, _)| name.as_str()) { + Some("Macro.code") => ResultKind::Code, + Some("Macro.decls") => ResultKind::Decls, + Some("Macro.typ") => ResultKind::Typ, + Some("Macro.pat") => ResultKind::Pat, + _ => ResultKind::Other, + } +} + +fn is_unit(ctx: &TypeContext, ty: TypeExprRef) -> bool { + matches!(&*ctx.get_desc(ctx.repr(ty)), TypeDesc::Tconstr { path, .. } if path.same(&predef::path_unit())) +} + +/// Parameters and result of a macro, read from its type. +fn signature(ctx: &TypeContext, ty: TypeExprRef) -> (Signature, Vec, TypeExprRef) { + match &*ctx.get_desc(ctx.repr(ty)) { + TypeDesc::Tarrow { args, ret } => { + let types: Vec = ctx.type_args(*args).iter().map(|arg| arg.typ).collect(); + // `() => ...` takes no argument. + let types: Vec = if types.len() == 1 && is_unit(ctx, types[0]) { + Vec::new() + } else { + types + }; + ( + Signature { + params: types.iter().map(|ty| param_kind(ctx, *ty)).collect(), + result: result_kind(ctx, *ret), + }, + types, + *ret, + ) + } + _ => ( + Signature { + params: Vec::new(), + result: result_kind(ctx, ty), + }, + Vec::new(), + ty, + ), + } +} + +/// The type a `@generic` has where it is used: `code<'a> => code` +/// is called as `'a => JSON.t`. `None` when the value is not a function +/// that returns code. +fn erased_type(ctx: &TypeContext, ty: TypeExprRef) -> Option { + let TypeDesc::Tarrow { args, ret } = &*ctx.get_desc(ctx.repr(ty)) else { + return None; + }; + let (name, result_args) = macro_type_name(ctx, *ret)?; + if name != "Macro.code" { + return None; + } + let erased_args: Vec = ctx + .type_args(*args) + .iter() + .map(|arg| { + let erased = match macro_type_name(ctx, arg.typ) { + Some((name, inner)) if name == "Macro.code" && inner.len() == 1 => inner[0], + _ => arg.typ, + }; + TypeArg::with_label(arg.label(), erased) + }) + .collect(); + Some(ctx.new_type(TypeDesc::Tarrow { + args: ctx.new_type_args(&erased_args), + ret: *result_args.first()?, + })) +} + +/// How a value is marked. +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum MacroKind { + /// `@macro`: used as `%M.f(...)` or `@M.f`. + Macro, + /// `@generic`: called like a function. + Generic, +} + +pub fn macro_kind(desc: &ValueDescription) -> Option { + desc.val_attributes + .iter() + .find_map(|attr| match attr.attr_name.txt.as_str() { + "macro" => Some(MacroKind::Macro), + "generic" => Some(MacroKind::Generic), + _ => None, + }) +} + +/// A generic use found while typing an item, resolved when the item's types +/// are final. +struct PendingGeneric { + /// The identifier. + callee: (u32, u32), + /// The call, when the identifier is applied directly. + call: Option, + module: String, + name: String, + signature: Signature, + /// The erased type at this use. + ty: TypeExprRef, + env: Env, +} + +struct PendingCall { + range: (u32, u32), + /// Per argument: its source range and, for a literal, its value. + args: Vec<((u32, u32), Option)>, +} + +/// State of one discovery pass. +pub struct Discovery { + host: Arc, + text: Arc, + /// Directory `readFile` paths are resolved from. + base_dir: std::path::PathBuf, + pub edits: Vec, + pub errors: Vec, + /// Start of each top-level item that failed to type check. + pub failed_items: Vec, + pub instances: InstanceTable, + pub comptime: Vec, + pending: Vec, + /// Nesting of `type_structure`: 1 while typing a top-level item. + depth: u32, + /// The top-level item being typed. + item_start: u32, + /// The item stopped because one of its macros was expanded. + item_pending: bool, + /// The application whose function is being typed. + apply: Option<(LocIdx, PendingCall)>, + /// End of the instance group already in the text, by ordinal. + group_ends: HashMap, + /// Instances added by this pass that start a new group, by the offset of + /// the item they go before. + new_groups: Vec<(u32, Vec)>, +} + +/// What a discovery pass found. +pub struct PassResult { + pub edits: Vec, + pub errors: Vec, + pub failed_items: Vec, + pub instances: InstanceTable, + pub comptime: Vec, +} + +impl Discovery { + pub fn new( + host: Arc, + text: Arc, + base_dir: std::path::PathBuf, + instances: InstanceTable, + ) -> Self { + Discovery { + host, + text, + base_dir, + edits: Vec::new(), + errors: Vec::new(), + failed_items: Vec::new(), + instances, + comptime: Vec::new(), + pending: Vec::new(), + depth: 0, + item_start: 0, + item_pending: false, + apply: None, + group_ends: HashMap::new(), + new_groups: Vec::new(), + } + } + + pub fn finish(mut self) -> PassResult { + for (at, functions) in std::mem::take(&mut self.new_groups) { + self.edits.push(Edit::insert( + at, + format!( + "%%private(@warning(\"-39\") let rec {})\n", + functions.join("\nand ") + ), + )); + } + PassResult { + edits: self.edits, + errors: self.errors, + failed_items: self.failed_items, + instances: self.instances, + comptime: self.comptime, + } + } + + fn error(&mut self, at: (u32, u32), message: impl Into) { + self.errors.push(MacroDiagnostic { + start: at.0, + end: at.1, + message: message.into(), + }); + } + + fn add_instance(&mut self, function: String) { + let ordinal = self.text.origin(self.item_start); + if let Some(end) = self.group_ends.get(&ordinal).copied() { + // `%%private(let rec a = ... )`: stay inside the parentheses. + let at = if end > 0 && self.text.slice(end - 1, end) == ")" { + end - 1 + } else { + end + }; + self.edits.push(Edit::insert(at, format!("\nand {function}"))); + return; + } + match self + .new_groups + .iter_mut() + .find(|(at, _)| *at == self.item_start) + { + Some((_, functions)) => functions.push(function), + None => self.new_groups.push((self.item_start, vec![function])), + } + } + + /// Run a macro: ask the engine, answer its questions, ask again. + fn run( + &self, + tctx: &mut TypeCheckContext<'_>, + env: &Env, + table: &mut TypeTable, + mut request: Value, + ) -> Result)> { + let mut answers = serde_json::Map::new(); + for _ in 0..4096 { + request["answers"] = Value::Object(answers.clone()); + let response = self + .host + .call(&request.to_string()) + .map_err(|message| (format!("The macro engine failed: {message}"), None))?; + let response: Value = serde_json::from_str(&response) + .map_err(|error| (format!("The macro engine returned invalid JSON: {error}"), None))?; + if let Some(code) = response.get("ok").and_then(Value::as_str) { + return Ok(code.to_string()); + } + if let Some(message) = response.get("error").and_then(Value::as_str) { + let offset = response + .get("offset") + .and_then(Value::as_u64) + .map(|offset| offset as u32); + return Err((message.to_string(), offset)); + } + let Some(question) = response.get("need").and_then(Value::as_str) else { + return Err(("The macro engine returned an unknown response.".into(), None)); + }; + let answer = self.answer(tctx, env, table, question); + answers.insert(question.to_string(), answer); + } + Err(("The macro asked more than 4096 questions.".into(), None)) + } + + fn answer( + &self, + tctx: &mut TypeCheckContext<'_>, + env: &Env, + table: &mut TypeTable, + question: &str, + ) -> Value { + let ctx = tctx.type_ctx; + let failure = |message: String| json!({ "__error": message }); + let (kind, rest) = question.split_once(':').unwrap_or((question, "")); + match kind { + "info" => match rest.parse::().ok().and_then(|id| table.get(id)) { + Some(ty) => reflect::type_info(ctx, env, table, ty), + None => failure("Type.info: unknown type.".into()), + }, + "companion" => { + let (id, name) = rest.split_once(':').unwrap_or((rest, "")); + let Some(ty) = id.parse::().ok().and_then(|id| table.get(id)) else { + return failure("Type.companion: unknown type.".into()); + }; + let TypeDesc::Tconstr { path, .. } = &*ctx.get_desc(ctx.repr(ty)) else { + return Value::Null; + }; + let PathView::Pdot(module, _, _) = path.view() else { + return Value::Null; + }; + let value = format!("{}.{}", module.name(), name); + match lookup_value(tctx, env, &value) { + Some(_) => json!({ "c": value }), + None => Value::Null, + } + } + _ => answer_input(&self.base_dir, question) + .unwrap_or_else(|| failure(format!("Unknown question `{question}`."))), + } + } +} + +/// The answers that need no type checker: files and environment variables. +pub(crate) fn answer_input(base_dir: &std::path::Path, question: &str) -> Option { + let (kind, rest) = question.split_once(':')?; + match kind { + "readFile" => Some(match read_file(base_dir, rest) { + Some(text) => Value::String(text), + None => json!({ "__error": format!("readFile: cannot read `{rest}`.") }), + }), + "env" => Some(match std::env::var(rest) { + Ok(value) => Value::String(value), + Err(_) => Value::Null, + }), + _ => None, + } +} + +/// Read `path` relative to `base` or one of its ancestors. +fn read_file(base: &std::path::Path, path: &str) -> Option { + #[cfg(feature = "wasm")] + { + let _ = base; + let absolute = if path.starts_with('/') { + path.to_string() + } else { + format!("/{path}") + }; + return crate::wasm_vfs::read_file(&absolute).or_else(|| crate::wasm_vfs::read_file(path)); + } + #[cfg(not(feature = "wasm"))] + { + let relative = std::path::Path::new(path); + if relative.is_absolute() { + return std::fs::read_to_string(relative).ok(); + } + let mut dir = Some(base); + while let Some(current) = dir { + if let Ok(text) = std::fs::read_to_string(current.join(relative)) { + return Some(text); + } + dir = current.parent(); + } + std::fs::read_to_string(relative).ok() + } +} + +fn range(arena: &ParseArena, loc: LocIdx) -> (u32, u32) { + let location = arena.to_location(loc); + ( + location.loc_start.cnum.max(0) as u32, + location.loc_end.cnum.max(0) as u32, + ) +} + +fn error_at(loc: LocIdx, message: impl Into) -> TypeCoreError { + TypeCoreError::ExtensionError(BuiltinExtensionError { + loc, + message: message.into(), + sub: Vec::new(), + }) +} + +/// Stop an ordinary compilation at a macro use. +fn required(tctx: &mut TypeCheckContext<'_>, loc: LocIdx) -> TypeCoreError { + tctx.macro_expansion_required = true; + error_at(loc, "This file uses macros and has to be expanded first.") +} + +/// Stop typing the current item of a discovery pass: its edit, or the +/// macro's error, is recorded. +fn pending(tctx: &mut TypeCheckContext<'_>, loc: LocIdx) -> TypeCoreError { + if let MacroMode::Discover(discovery) = &mut tctx.macro_mode { + discovery.item_pending = true; + } + error_at(loc, "(macro expansion pending)") +} + +fn discovering(tctx: &TypeCheckContext<'_>) -> bool { + matches!(tctx.macro_mode, MacroMode::Discover(_)) +} + +/// Run `f` with the pass state taken out of the context, so `f` can use +/// both. +fn with_discovery( + tctx: &mut TypeCheckContext<'_>, + f: impl FnOnce(&mut TypeCheckContext<'_>, &mut Discovery) -> R, +) -> Option { + let MacroMode::Discover(mut discovery) = std::mem::replace(&mut tctx.macro_mode, MacroMode::Off) + else { + return None; + }; + let result = f(tctx, &mut discovery); + tctx.macro_mode = MacroMode::Discover(discovery); + Some(result) +} + +fn longident_of(arena: &ParseArena, name: &str) -> Option { + let mut longident: Option = None; + for segment in name.split('.') { + if segment.is_empty() { + return None; + } + let idx = arena + .find_string_idx(segment) + .unwrap_or_else(|| arena.push_typecheck_string(segment.to_string())); + longident = Some(match longident { + None => Longident::Lident(idx), + Some(prefix) => Longident::Ldot(Box::new(prefix), idx), + }); + } + longident +} + +fn lookup_value( + tctx: &mut TypeCheckContext<'_>, + env: &Env, + name: &str, +) -> Option<(Path, Arc)> { + let longident = longident_of(tctx.arena, name)?; + env.lookup_value_by_lid(&longident, tctx.arena, &mut tctx.persistent_env, tctx.type_ctx) +} + +/// `Json.encode` → (`Json`, `encode`): the module whose JavaScript the +/// engine loads and the export it calls. +fn split_macro_name(name: &str) -> (String, String) { + match name.rsplit_once('.') { + Some((module, value)) => (module.split('.').next().unwrap_or(module).to_string(), { + // A macro in a submodule is not reachable as an export by name. + let _ = module; + value.to_string() + }), + None => (String::new(), name.to_string()), + } +} + +fn literal(arena: &ParseArena, expr: ExprIdx) -> Option { + let expr = arena.get_expr(expr); + match &expr.pexp_desc { + ExpressionDesc::Pexp_constant(constant) => match constant { + Constant::String(text) => Some(Value::String(text.semantic(arena).to_string())), + Constant::Integer(text, None) => { + arena.get_string(*text).replace('_', "").parse::().ok().map(Value::from) + } + Constant::Float(text, None) => { + arena.get_string(*text).replace('_', "").parse::().ok().map(Value::from) + } + _ => None, + }, + ExpressionDesc::Pexp_construct(lid, args) if arena.expr_list(args.txt).is_empty() => { + match arena.get_longident(lid.txt) { + Longident::Lident(name) => match arena.get_string(*name) { + "true" => Some(Value::Bool(true)), + "false" => Some(Value::Bool(false)), + "()" => Some(Value::Null), + _ => None, + }, + _ => None, + } + } + _ => None, + } +} + +/// The argument expressions of `%M.f(a, b)`. +fn payload_expressions(arena: &ParseArena, payload: &Payload, arity: usize) -> Result, String> { + let Payload::PStr(items) = payload else { + return Err("The arguments of a macro are expressions here.".into()); + }; + match items.as_slice() { + [] => Ok(Vec::new()), + [item] => { + let ParsedStructureItemDesc::Pstr_eval(eval) = &item.pstr_desc else { + return Err("The arguments of a macro are expressions here.".into()); + }; + match &arena.get_expr(eval.0).pexp_desc { + ExpressionDesc::Pexp_tuple(elements) if arity != 1 => Ok(arena.expr_list(*elements).to_vec()), + _ => Ok(vec![eval.0]), + } + } + _ => Err("The arguments of a macro are expressions here.".into()), + } +} + +/// The JSON arguments of a `%M.f(...)` call. +fn call_arguments( + tctx: &mut TypeCheckContext<'_>, + env: &Env, + discovery: &Discovery, + table: &mut TypeTable, + name: &str, + signature: &Signature, + payload: &Payload, +) -> Result, String> { + let exprs = payload_expressions(tctx.arena, payload, signature.params.len())?; + if exprs.len() != signature.params.len() { + return Err(format!( + "The macro `{name}` takes {} argument{}, and {} {} given.", + signature.params.len(), + if signature.params.len() == 1 { "" } else { "s" }, + exprs.len(), + if exprs.len() == 1 { "is" } else { "are" }, + )); + } + let mut args = Vec::with_capacity(exprs.len()); + for (index, (expr_idx, kind)) in exprs.iter().zip(&signature.params).enumerate() { + let expr = tctx.arena.get_expr(*expr_idx); + let at = range(tctx.arena, expr.pexp_loc); + match kind { + ParamKind::Code => { + let mut code = json!({ "c": discovery.text.slice(at.0, at.1) }); + // The type as far as it is known here. An argument that + // does not type check on its own has none. + let ctx = tctx.type_ctx; + let expected = ctx.new_var(None); + if let Ok(typed) = crate::types::typecore::type_expect(tctx, env, expr, expected, None) { + code["t"] = reflect::type_ref(ctx, table, typed.exp_type); + } + args.push(code); + } + ParamKind::Value => match literal(tctx.arena, *expr_idx) { + Some(value) => args.push(value), + None => { + return Err(format!( + "Argument {} of the macro `{name}` is a compile-time value, so it has to be a literal.", + index + 1 + )); + } + }, + ParamKind::Typ => { + return Err(format!( + "Argument {} of the macro `{name}` is a type. Use the macro where a type is written: `type t = %{name}(...)`.", + index + 1 + )); + } + ParamKind::Decl | ParamKind::Binding => { + return Err(format!( + "The macro `{name}` works on a declaration. Attach it: `@{name}`." + )); + } + } + } + Ok(args) +} + +/// Look up the macro an extension or attribute names. +fn find_macro( + tctx: &mut TypeCheckContext<'_>, + env: &Env, + loc: LocIdx, + name: &str, +) -> Result, TypeCoreError> { + let Some((_, desc)) = lookup_value(tctx, env, name) else { + return Err(error_at(loc, format!("The macro `{name}` cannot be found."))); + }; + match macro_kind(&desc) { + Some(_) => Ok(desc), + None => Err(error_at( + loc, + format!("`{name}` is not a macro. A macro is a function marked with @macro."), + )), + } +} + +/// Run a macro for a call site and return its code, or record the failure. +#[allow(clippy::too_many_arguments)] +fn run_call( + tctx: &mut TypeCheckContext<'_>, + env: &Env, + discovery: &mut Discovery, + table: &mut TypeTable, + at: (u32, u32), + name: &str, + args: Result, String>, + expected: Option, +) -> Option { + let args = match args { + Ok(args) => args, + Err(message) => { + discovery.error(at, message); + return None; + } + }; + let (module, value) = split_macro_name(name); + let request = json!({ + "kind": "call", + "module": module, + "name": value, + "args": args, + "expected": expected, + }); + match discovery.run(tctx, env, table, request) { + Ok(code) => Some(code), + Err((message, _offset)) => { + discovery.error(at, format!("{name}: {message}")); + None + } + } +} + +/// `%name(...)` where an expression is expected. `None`: not a macro, the +/// type checker handles the extension as before. +pub(crate) fn expression_extension( + tctx: &mut TypeCheckContext<'_>, + env: &Env, + loc: LocIdx, + extension: &Extension, + expected_ty: TypeExprRef, +) -> Option> { + let name = tctx.arena.get_string(extension.0.txt).to_string(); + let is_hole = name == HOLE_EXTENSION; + if is_hole || quote::is_quote_name(&name) { + // Quotes are lowered before a discovery pass; one that is left has + // no payload. + return Some(Err(if !discovering(tctx) { + required(tctx, loc) + } else if is_hole { + error_at( + loc, + "A hole `${...}` can only be used inside a quote: %code(...), %type(...) or %pat(...).", + ) + } else { + error_at(loc, format!("The quote `%{name}` needs a payload: `%{name}(...)`.")) + })); + } + if name == "comptime" { + return Some(comptime(tctx, env, loc, extension, expected_ty)); + } + if !is_macro_name(&name) { + return None; + } + let desc = match find_macro(tctx, env, loc, &name) { + Ok(desc) => desc, + Err(error) => return Some(Err(error)), + }; + if !discovering(tctx) { + return Some(Err(required(tctx, loc))); + } + let ctx = tctx.type_ctx; + let macro_type = crate::types::instance(ctx, desc.val_type); + let (signature, _, result_type) = signature(ctx, macro_type); + let at = range(tctx.arena, loc); + if signature.result != ResultKind::Code { + return Some(Err(error_at( + loc, + format!("The macro `{name}` does not return an expression, so it cannot be used as one."), + ))); + } + let mut table = TypeTable::default(); + with_discovery(tctx, |tctx, discovery| { + let args = call_arguments(tctx, env, discovery, &mut table, &name, &signature, &extension.1); + if let Some(code) = run_call(tctx, env, discovery, &mut table, at, &name, args, None) { + discovery.edits.push(Edit::replace(at.0, at.1, format!("({code})"))); + } + }); + // Type the call as its declared result, `code` as `string`, so + // the rest of the item is checked as far as possible in this pass. + if let Some((_, inner)) = macro_type_name(ctx, result_type) + && let Some(inner) = inner.first() + { + let mut state = crate::types::ctype::UnifyState::default(); + let _ = crate::types::ctype::unify(ctx, &mut state, *inner, expected_ty); + } + Some(Ok(Expression::new( + TypedExpressionDesc::Texp_break, + loc, + expected_ty, + ctx.store_typed_env(env), + ))) +} + +/// `%comptime(expr)`: `expr` is typed as usual; its value replaces it +/// between passes. +fn comptime( + tctx: &mut TypeCheckContext<'_>, + env: &Env, + loc: LocIdx, + extension: &Extension, + expected_ty: TypeExprRef, +) -> TypeCoreResult { + if !discovering(tctx) { + return Err(required(tctx, loc)); + } + let expr_idx = match payload_expressions(tctx.arena, &extension.1, 1) { + Ok(exprs) if exprs.len() == 1 => exprs[0], + _ => return Err(error_at(loc, "%comptime takes one expression: `%comptime(expr)`.")), + }; + let expr = tctx.arena.get_expr(expr_idx); + let typed = crate::types::typecore::type_expect(tctx, env, expr, expected_ty, None)?; + let at = range(tctx.arena, loc); + let inner = range(tctx.arena, expr.pexp_loc); + let ctx = tctx.type_ctx; + let shape = reflect::value_shape(ctx, env, typed.exp_type, 0); + with_discovery(tctx, |_, discovery| { + let expression = discovery.text.slice(inner.0, inner.1).to_string(); + discovery.comptime.push(ComptimeSite { + start: at.0, + end: at.1, + expression, + shape, + }); + }); + Ok(typed) +} + +/// An application is about to be typed: remember its arguments for the case +/// that its function is a `@generic`. +pub(crate) fn note_application( + tctx: &mut TypeCheckContext<'_>, + loc: LocIdx, + funct: &crate::parser::ast::Expression, + args: &[(ArgLabel, ExprIdx)], +) { + let arena = tctx.arena; + let MacroMode::Discover(discovery) = &mut tctx.macro_mode else { + return; + }; + if !matches!(funct.pexp_desc, ExpressionDesc::Pexp_ident(_)) { + return; + } + let call = PendingCall { + range: range(arena, loc), + args: args + .iter() + .map(|(label, arg)| { + let value = match label { + ArgLabel::Nolabel => literal(arena, *arg), + _ => None, + }; + (range(arena, arena.get_expr(*arg).pexp_loc), value) + }) + .collect(), + }; + discovery.apply = Some((funct.pexp_loc, call)); +} + +/// An identifier resolved to `desc`. For a `@generic` of another file this +/// returns the type the identifier has here; otherwise `None`. +pub(crate) fn generic_use( + tctx: &mut TypeCheckContext<'_>, + env: &Env, + loc: LocIdx, + path: &Path, + desc: &ValueDescription, +) -> TypeCoreResult> { + let Some(kind) = macro_kind(desc) else { + return Ok(None); + }; + // In its own file a macro is an ordinary function. + let PathView::Pdot(..) = path.view() else { + return Ok(None); + }; + let name = path.name(); + if kind == MacroKind::Macro { + return Err(error_at( + loc, + format!("`{name}` is a macro. Use it as `%{name}(...)` or attach it as `@{name}`."), + )); + } + if !discovering(tctx) { + return Err(required(tctx, loc)); + } + let ctx = tctx.type_ctx; + let instance = crate::types::instance(ctx, desc.val_type); + let Some(erased) = erased_type(ctx, instance) else { + return Err(error_at( + loc, + format!("`{name}` is marked @generic, so it has to be a function that returns `code<...>`."), + )); + }; + let (signature, _, _) = signature(ctx, instance); + let callee = range(tctx.arena, loc); + let (module, value) = split_macro_name(&name); + let env = env.clone(); + if let MacroMode::Discover(discovery) = &mut tctx.macro_mode { + let call = match discovery.apply.take() { + Some((apply_loc, call)) if apply_loc == loc => Some(call), + _ => None, + }; + discovery.pending.push(PendingGeneric { + callee, + call, + module, + name: value, + signature, + ty: erased, + env, + }); + } + Ok(Some(erased)) +} + +fn instance_name(base: &str, parts: &[String]) -> String { + let mut name = String::from(base); + for part in parts { + name.push('$'); + let mut last_underscore = true; + for ch in part.chars() { + if ch.is_ascii_alphanumeric() { + name.push(ch); + last_underscore = false; + } else if !last_underscore { + name.push('_'); + last_underscore = true; + } + } + while name.ends_with('_') { + name.pop(); + } + } + name +} + +/// A top-level item is about to be typed. +pub(crate) fn begin_item(tctx: &mut TypeCheckContext<'_>, item: &ParsedStructureItem) { + let arena = tctx.arena; + let MacroMode::Discover(discovery) = &mut tctx.macro_mode else { + return; + }; + discovery.depth += 1; + if discovery.depth != 1 { + return; + } + let (start, end) = range(arena, item.pstr_loc); + discovery.item_start = start; + discovery.item_pending = false; + // An instance group that an earlier pass added. + if let ParsedStructureItemDesc::Pstr_value((RecFlag::Recursive, bindings)) = &item.pstr_desc + && let Some(first) = arena.vb_list(*bindings).first() + && let PatternDesc::Ppat_var(name) = &arena.get_pat(first.pvb_pat).ppat_desc + && arena.get_string(name.txt).contains('$') + { + let ordinal = discovery.text.origin(start); + discovery.group_ends.insert(ordinal, end); + } +} + +/// A top-level item was typed (`ok`) or failed. Resolves the generic uses +/// found in it. Returns whether the failure is only a recorded expansion. +pub(crate) fn end_item(tctx: &mut TypeCheckContext<'_>, ok: bool) { + let MacroMode::Discover(discovery) = &mut tctx.macro_mode else { + return; + }; + discovery.depth -= 1; + if discovery.depth != 0 { + return; + } + discovery.apply = None; + if !ok && !discovery.item_pending { + let start = discovery.item_start; + discovery.failed_items.push(start); + } + let pending = std::mem::take(&mut discovery.pending); + with_discovery(tctx, |tctx, discovery| { + for generic in pending { + resolve_generic(tctx, discovery, generic); + } + }); +} + +fn resolve_generic(tctx: &mut TypeCheckContext<'_>, discovery: &mut Discovery, generic: PendingGeneric) { + let ctx = tctx.type_ctx; + let full_name = format!("{}.{}", generic.module, generic.name); + let TypeDesc::Tarrow { args, ret } = &*ctx.get_desc(ctx.repr(generic.ty)) else { + return; + }; + let ret = *ret; + let arg_types: Vec = ctx.type_args(*args).iter().map(|arg| arg.typ).collect(); + + let mut table = TypeTable::default(); + let mut macro_args = Vec::new(); + let mut params = Vec::new(); + let mut call_args = Vec::new(); + let mut key_parts = Vec::new(); + let mut name_parts = Vec::new(); + for (index, kind) in generic.signature.params.iter().enumerate() { + match kind { + ParamKind::Code => { + let Some(ty) = arg_types.get(index).copied() else { + return; + }; + let printed = reflect::print_type(ctx, ty); + if reflect::is_unknown(ctx, ty) || printed.contains("'_") { + discovery.error( + generic.callee, + format!( + "`{full_name}` is generated per type, and the type of this argument is not known here. Add a type annotation." + ), + ); + return; + } + let param = format!("{}$", (b'a' + (params.len() % 26) as u8) as char); + let mut code = json!({ "c": param }); + code["t"] = reflect::type_ref(ctx, &mut table, ty); + macro_args.push(code); + params.push(format!("{param}: {printed}")); + key_parts.push(printed.clone()); + name_parts.push(printed); + if let Some(call) = &generic.call + && let Some((at, _)) = call.args.get(index) + { + call_args.push(discovery.text.slice(at.0, at.1).to_string()); + } + } + ParamKind::Value => { + let value = generic + .call + .as_ref() + .and_then(|call| call.args.get(index)) + .and_then(|(_, value)| value.clone()); + let Some(value) = value else { + discovery.error( + generic.callee, + format!( + "Argument {} of `{full_name}` is a compile-time value: call `{full_name}` directly, with a literal.", + index + 1 + ), + ); + return; + }; + key_parts.push(value.to_string()); + name_parts.push(match &value { + Value::String(text) => text.clone(), + other => other.to_string(), + }); + macro_args.push(value); + } + _ => { + discovery.error( + generic.callee, + format!("`{full_name}`: a @generic takes `code<...>` and compile-time values only."), + ); + return; + } + } + } + let has_values = generic.signature.params.contains(&ParamKind::Value); + let result = reflect::print_type(ctx, ret); + let key = format!("{full_name}({})->{result}", key_parts.join(",")); + let ordinal = discovery.text.origin(discovery.item_start); + + let name = match discovery.instances.find(&key, ordinal) { + Some(name) => name.to_string(), + None => { + let expected = reflect::type_ref(ctx, &mut table, ret); + let request = json!({ + "kind": "call", + "module": generic.module, + "name": generic.name, + "args": macro_args, + "expected": expected, + }); + let body = match discovery.run(tctx, &generic.env, &mut table, request) { + Ok(body) => body, + Err((message, _)) => { + discovery.error(generic.callee, format!("{full_name}: {message}")); + return; + } + }; + if name_parts.is_empty() { + name_parts.push(result.clone()); + } + let name = discovery + .instances + .add(key, &instance_name(&generic.name, &name_parts), ordinal); + let annotation = if result.contains("'_") || reflect::is_unknown(ctx, ret) { + String::new() + } else { + format!(": {result}") + }; + discovery.add_instance(format!( + "{name} = ({}){annotation} => {body}", + params.join(", ") + )); + name + } + }; + + if has_values { + // The compile-time arguments are part of the instance: the call + // keeps the others. + match &generic.call { + Some(call) => discovery.edits.push(Edit::replace( + call.range.0, + call.range.1, + format!("{name}({})", call_args.join(", ")), + )), + None => discovery.error( + generic.callee, + format!("`{full_name}` takes compile-time values, so it has to be called directly."), + ), + } + } else { + discovery + .edits + .push(Edit::replace(generic.callee.0, generic.callee.1, name)); + } +} + +/// Whether a failed top-level item is skipped: in a discovery pass, at the +/// top level of the file. +pub(crate) fn skips_failed_item(tctx: &TypeCheckContext<'_>) -> bool { + matches!(&tctx.macro_mode, MacroMode::Discover(discovery) if discovery.depth == 0) +} + +/// An extension where a type is expected: `type t = %Partial.t(user)`. +pub(crate) fn type_extension( + tctx: &mut TypeCheckContext<'_>, + env: &Env, + loc: LocIdx, + extension: &Extension, +) -> Option { + let name = tctx.arena.get_string(extension.0.txt).to_string(); + if name == HOLE_EXTENSION { + return Some(if discovering(tctx) { + error_at(loc, "A hole `${...}` can only be used inside a quote: %code(...), %type(...) or %pat(...).") + } else { + required(tctx, loc) + }); + } + if !is_macro_name(&name) { + return None; + } + let desc = match find_macro(tctx, env, loc, &name) { + Ok(desc) => desc, + Err(error) => return Some(error), + }; + if !discovering(tctx) { + return Some(required(tctx, loc)); + } + let ctx = tctx.type_ctx; + let (signature, _, _) = signature(ctx, crate::types::instance(ctx, desc.val_type)); + if signature.result != ResultKind::Typ { + return Some(error_at( + loc, + format!("The macro `{name}` does not return a type, so it cannot be used as one."), + )); + } + let arena = tctx.arena; + let types: Vec = match &extension.1 { + Payload::PTyp(idx) => match &arena.get_core_type(*idx).ptyp_desc { + crate::parser::ast::CoreTypeDesc::Ptyp_tuple(elements) if signature.params.len() != 1 => { + arena.type_list(*elements).to_vec() + } + _ => vec![*idx], + }, + _ => Vec::new(), + }; + let at = range(arena, loc); + let mut table = TypeTable::default(); + let mut args: Result, String> = if types.len() == signature.params.len() { + Ok(Vec::new()) + } else { + Err(format!( + "The macro `{name}` takes {} argument(s), and {} are given.", + signature.params.len(), + types.len() + )) + }; + if let Ok(values) = &mut args { + for (idx, kind) in types.iter().zip(&signature.params) { + let styp = arena.get_core_type(*idx); + let type_range = range(arena, styp.ptyp_loc); + if *kind != ParamKind::Typ { + args = Err(format!("The macro `{name}` takes arguments that are not types.")); + break; + } + match crate::types::typecore::transl_type(tctx, env, styp) { + Ok((_, ty)) => { + let mut value = reflect::type_ref(ctx, &mut table, ty); + with_discovery(tctx, |_, discovery| { + value["c"] = Value::String(discovery.text.slice(type_range.0, type_range.1).to_string()); + }); + values.push(value); + } + Err(error) => return Some(error), + } + } + } + with_discovery(tctx, |tctx, discovery| { + if let Some(code) = run_call(tctx, env, discovery, &mut table, at, &name, args, None) { + discovery.edits.push(Edit::replace(at.0, at.1, format!("({code})"))); + } + }); + Some(pending(tctx, loc)) +} + +/// A structure item or module expression that is a macro call: +/// `%M.f(...)` on its own, or `module X = %M.f(...)`. +pub(crate) fn declarations_extension( + tctx: &mut TypeCheckContext<'_>, + env: &Env, + loc: LocIdx, + extension: &Extension, + as_module: bool, +) -> Option { + let name = tctx.arena.get_string(extension.0.txt).to_string(); + if !is_macro_name(&name) { + return None; + } + let desc = match find_macro(tctx, env, loc, &name) { + Ok(desc) => desc, + Err(error) => return Some(error), + }; + if !discovering(tctx) { + return Some(required(tctx, loc)); + } + let ctx = tctx.type_ctx; + let (signature, _, _) = signature(ctx, crate::types::instance(ctx, desc.val_type)); + if signature.result != ResultKind::Decls { + return Some(error_at( + loc, + format!("The macro `{name}` does not return declarations (`decls`), so it cannot be used here."), + )); + } + let at = range(tctx.arena, loc); + let mut table = TypeTable::default(); + with_discovery(tctx, |tctx, discovery| { + let args = call_arguments(tctx, env, discovery, &mut table, &name, &signature, &extension.1); + if let Some(code) = run_call(tctx, env, discovery, &mut table, at, &name, args, None) { + let text = if as_module { + format!("{{\n{code}\n}}") + } else { + code + }; + discovery.edits.push(Edit::replace(at.0, at.1, text)); + } + }); + Some(pending(tctx, loc)) +} + +/// The macros attached to something: `@Json.codec`. +fn macro_attributes( + arena: &ParseArena, + attributes: &crate::parser::ast::Attributes, +) -> Vec<(String, LocIdx)> { + attributes + .iter() + .filter_map(|attr| { + let name = arena.get_string(attr.0.txt); + is_macro_name(name).then(|| (name.to_string(), attr.0.loc)) + }) + .collect() +} + +/// Whether a `let` or a type declaration carries a macro attribute. +pub(crate) fn has_macro_attribute( + arena: &ParseArena, + attributes: &crate::parser::ast::Attributes, +) -> bool { + attributes + .iter() + .any(|attr| is_macro_name(arena.get_string(attr.0.txt))) +} + +/// Mark an attribute as done: `@Json.codec` becomes `@expanded.Json.codec`, +/// which is inert. +fn retire_attribute(discovery: &mut Discovery, arena: &ParseArena, name: &str, loc: LocIdx) { + let at = range(arena, loc); + let text = discovery.text.slice(at.0, at.1).to_string(); + discovery + .edits + .push(Edit::replace(at.0, at.1, text.replacen(name, &format!("expanded.{name}"), 1))); +} + +/// `@M.f let x = ...`: the macro gets the binding as syntax and its result +/// replaces the item. `None`: no macro attribute. +pub(crate) fn value_item( + tctx: &mut TypeCheckContext<'_>, + env: &Env, + item: &ParsedStructureItem, +) -> Option { + let arena = tctx.arena; + let ParsedStructureItemDesc::Pstr_value((_, bindings)) = &item.pstr_desc else { + return None; + }; + let bindings = arena.vb_list(*bindings); + let (binding, (name, attr_loc)) = bindings.iter().find_map(|binding| { + macro_attributes(arena, &binding.pvb_attributes) + .into_iter() + .next() + .map(|found| (binding, found)) + })?; + let loc = item.pstr_loc; + let desc = match find_macro(tctx, env, attr_loc, &name) { + Ok(desc) => desc, + Err(error) => return Some(error), + }; + if !discovering(tctx) { + return Some(required(tctx, loc)); + } + if bindings.len() != 1 { + return Some(error_at(attr_loc, format!("`@{name}` works on a `let` with one binding."))); + } + let ctx = tctx.type_ctx; + let (signature, _, _) = signature(ctx, crate::types::instance(ctx, desc.val_type)); + if signature.params != [ParamKind::Binding] || signature.result != ResultKind::Decls { + return Some(error_at( + attr_loc, + format!("A macro on a `let` has the type `Decl.value => decls`, and `{name}` does not."), + )); + } + let pat = arena.get_pat(binding.pvb_pat); + let pat_range = range(arena, pat.ppat_loc); + let expr_range = range(arena, arena.get_expr(binding.pvb_expr).pexp_loc); + let bound = match &pat.ppat_desc { + PatternDesc::Ppat_var(name) => arena.get_string(name.txt).to_string(), + _ => String::new(), + }; + let at = range(arena, loc); + let mut table = TypeTable::default(); + with_discovery(tctx, |tctx, discovery| { + let args = Ok(vec![json!({ + "name": bound, + "pat": { "c": discovery.text.slice(pat_range.0, pat_range.1) }, + "expr": { "c": discovery.text.slice(expr_range.0, expr_range.1) }, + })]); + if let Some(code) = run_call(tctx, env, discovery, &mut table, at, &name, args, None) { + discovery.edits.push(Edit::replace(at.0, at.1, code)); + } + }); + Some(pending(tctx, loc)) +} + +/// Whether a type item carries a macro, for an ordinary compilation to +/// stop at. +pub(crate) fn type_item_requires_expansion( + tctx: &mut TypeCheckContext<'_>, + item: &ParsedStructureItem, +) -> Option { + if discovering(tctx) { + return None; + } + let ParsedStructureItemDesc::Pstr_type(inner) = &item.pstr_desc else { + return None; + }; + let arena = tctx.arena; + inner + .1 + .iter() + .any(|decl| has_macro_attribute(arena, &decl.ptype_attributes)) + .then(|| required(tctx, item.pstr_loc)) +} + +/// `@M.f type t = ...`, after the declaration is type checked in `env`: the +/// macro gets the declaration and its result is added after the item. +pub(crate) fn type_item(tctx: &mut TypeCheckContext<'_>, env: &Env, item: &ParsedStructureItem) { + if !discovering(tctx) { + return; + } + let ParsedStructureItemDesc::Pstr_type(inner) = &item.pstr_desc else { + return; + }; + let arena = tctx.arena; + let item_range = range(arena, item.pstr_loc); + for decl in inner.1.iter() { + for (name, attr_loc) in macro_attributes(arena, &decl.ptype_attributes) { + let at = range(arena, attr_loc); + let desc = match find_macro(tctx, env, attr_loc, &name) { + Ok(desc) => desc, + Err(error) => { + let message = match error { + TypeCoreError::ExtensionError(error) => error.message, + _ => format!("The macro `{name}` cannot be used here."), + }; + with_discovery(tctx, |_, discovery| discovery.error(at, message)); + continue; + } + }; + let ctx = tctx.type_ctx; + let (signature, _, _) = signature(ctx, crate::types::instance(ctx, desc.val_type)); + if signature.params != [ParamKind::Decl] || signature.result != ResultKind::Decls { + with_discovery(tctx, |_, discovery| { + discovery.error( + at, + format!("A macro on a type has the type `Type.decl => decls`, and `{name}` does not."), + ) + }); + continue; + } + let type_name = arena.get_string(decl.ptype_name.txt).to_string(); + let Some((path, type_decl)) = lookup_type(tctx, env, &type_name) else { + continue; + }; + let ty = ctx.new_constr(path, type_decl.type_params.clone()); + let mut table = TypeTable::default(); + let mut type_value = reflect::type_ref(ctx, &mut table, ty); + if type_decl.type_params.is_empty() { + type_value["c"] = Value::String(type_name.clone()); + } + let attrs: Vec = decl + .ptype_attributes + .iter() + .filter(|attr| !is_macro_name(arena.get_string(attr.0.txt))) + .map(|attr| json!({ "name": arena.get_string(attr.0.txt) })) + .collect(); + with_discovery(tctx, |tctx, discovery| { + let args = Ok(vec![json!({ "name": type_name, "typ": type_value, "attrs": attrs })]); + if let Some(code) = run_call(tctx, env, discovery, &mut table, at, &name, args, None) { + discovery + .edits + .push(Edit::insert(item_range.1, format!("\n{code}"))); + retire_attribute(discovery, arena, &name, attr_loc); + } + }); + } + } +} + +fn lookup_type( + tctx: &mut TypeCheckContext<'_>, + env: &Env, + name: &str, +) -> Option<(Path, crate::types::TypeDeclaration)> { + let _ = tctx; + let (path, decl) = env.find_type_with_path(name).ok()?; + Some((path, decl.clone())) +} diff --git a/compiler-rust/src/macros/edit.rs b/compiler-rust/src/macros/edit.rs new file mode 100644 index 0000000000..787927bb50 --- /dev/null +++ b/compiler-rust/src/macros/edit.rs @@ -0,0 +1,235 @@ +//! Source text with edits applied and a map back to the original. +//! +//! Macro expansion edits the source text of a file: a macro call is replaced +//! by the code the macro returned, a generated function is inserted before +//! the item that needs it. Every character of the edited text remembers the +//! offset it has in the file as written, so that diagnostics, source maps and +//! editor tooling keep pointing at what the person wrote. Generated text +//! takes the offset of the place it was generated for. +//! +//! Offsets are in characters, like `Position::cnum`. + +/// One part of an edit's replacement. +#[derive(Debug, Clone)] +pub enum Segment { + /// Generated text. + Text(String), + /// The characters `start..end` of the text being edited, kept with their + /// origins. + Copy(u32, u32), +} + +/// Replace the characters `start..end` by `segments`. An insertion has +/// `start == end`. +#[derive(Debug, Clone)] +pub struct Edit { + pub start: u32, + pub end: u32, + pub segments: Vec, +} + +impl Edit { + pub fn replace(start: u32, end: u32, text: impl Into) -> Self { + Edit { + start, + end, + segments: vec![Segment::Text(text.into())], + } + } + + pub fn insert(at: u32, text: impl Into) -> Self { + Edit::replace(at, at, text) + } +} + +/// A file's text during macro expansion. +#[derive(Debug, Clone)] +pub struct SourceText { + text: String, + /// Byte offset of each character, and of the end of the text. + char_to_byte: Vec, + /// Offset in the original text of each character, and of the end. + origin: Vec, + /// Whether any edit was applied. + edited: bool, +} + +impl SourceText { + pub fn new(text: &str) -> Self { + let char_to_byte = char_offsets(text); + let chars = char_to_byte.len() as u32 - 1; + SourceText { + text: text.to_string(), + char_to_byte, + origin: (0..=chars).collect(), + edited: false, + } + } + + pub fn text(&self) -> &str { + &self.text + } + + pub fn is_edited(&self) -> bool { + self.edited + } + + pub fn len(&self) -> u32 { + self.char_to_byte.len() as u32 - 1 + } + + /// The characters `start..end`. + pub fn slice(&self, start: u32, end: u32) -> &str { + let len = self.len(); + let start = start.min(len); + let end = end.clamp(start, len); + &self.text[self.char_to_byte[start as usize] as usize..self.char_to_byte[end as usize] as usize] + } + + /// The offset in the original text of the character at `offset`. + pub fn origin(&self, offset: u32) -> u32 { + self.origin[(offset as usize).min(self.origin.len() - 1)] + } + + /// Apply `edits`. Of two edits that overlap, the one that starts first + /// wins (the outer of two nested macro calls); the next pass finds what + /// the other covered again. Insertions at one offset keep their order. + pub fn apply(&self, mut edits: Vec) -> SourceText { + edits.sort_by_key(|edit| (edit.start, edit.end != edit.start, std::cmp::Reverse(edit.end))); + let len = self.len(); + let mut text = String::with_capacity(self.text.len() + 256); + let mut origin = Vec::with_capacity(self.origin.len() + 256); + let mut cursor = 0u32; + for edit in &edits { + if edit.start < cursor || edit.end > len || edit.end < edit.start { + continue; + } + self.copy_into(cursor, edit.start, &mut text, &mut origin); + let generated_origin = self.origin(edit.start); + for segment in &edit.segments { + match segment { + Segment::Text(generated) => { + text.push_str(generated); + origin.extend(generated.chars().map(|_| generated_origin)); + } + Segment::Copy(start, end) => self.copy_into(*start, *end, &mut text, &mut origin), + } + } + cursor = edit.end; + } + self.copy_into(cursor, len, &mut text, &mut origin); + origin.push(self.origin(len)); + let char_to_byte = char_offsets(&text); + debug_assert_eq!(char_to_byte.len(), origin.len()); + SourceText { + text, + char_to_byte, + origin, + edited: true, + } + } + + fn copy_into(&self, start: u32, end: u32, text: &mut String, origin: &mut Vec) { + if start >= end { + return; + } + text.push_str(self.slice(start, end)); + origin.extend_from_slice(&self.origin[start as usize..end as usize]); + } +} + +fn char_offsets(text: &str) -> Vec { + let mut offsets: Vec = text.char_indices().map(|(byte, _)| byte as u32).collect(); + offsets.push(text.len() as u32); + offsets +} + +/// Line starts of a text, for turning an offset into a line and column. +pub struct LineTable { + /// Character offset of the first character of each line. + starts: Vec, +} + +impl LineTable { + pub fn new(text: &str) -> Self { + let mut starts = vec![0u32]; + for (index, ch) in text.chars().enumerate() { + if ch == '\n' { + starts.push(index as u32 + 1); + } + } + LineTable { starts } + } + + /// The 1-based line of `offset` and the offset of that line's start. + pub fn line_of(&self, offset: u32) -> (i32, u32) { + let line = match self.starts.binary_search(&offset) { + Ok(index) => index, + Err(index) => index - 1, + }; + (line as i32 + 1, self.starts[line]) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn replacement_keeps_origins_of_the_rest() { + let source = SourceText::new("let a = %M.f(x)\nlet b = 2\n"); + let edited = source.apply(vec![Edit::replace(8, 15, "(x + 1)")]); + assert_eq!(edited.text(), "let a = (x + 1)\nlet b = 2\n"); + // Generated characters point at the call. + assert_eq!(edited.origin(8), 8); + assert_eq!(edited.origin(12), 8); + // What follows keeps its place in the original. + assert_eq!(edited.origin(15), 15); + assert_eq!(edited.slice(16, 21), "let b"); + assert_eq!(edited.origin(16), 16); + } + + #[test] + fn outer_edit_wins_and_insertions_keep_order() { + let source = SourceText::new("abcdef"); + let edited = source.apply(vec![ + Edit::replace(2, 3, "X"), + Edit::replace(1, 4, "Y"), + Edit::insert(0, "1"), + Edit::insert(0, "2"), + ]); + assert_eq!(edited.text(), "12aYef"); + } + + #[test] + fn copies_keep_their_origin_inside_generated_text() { + let source = SourceText::new("%code(a + ${b})"); + let edited = source.apply(vec![Edit { + start: 0, + end: 15, + segments: vec![ + Segment::Text("q([".into()), + Segment::Copy(12, 13), + Segment::Text("])".into()), + ], + }]); + assert_eq!(edited.text(), "q([b])"); + assert_eq!(edited.origin(3), 12); + assert_eq!(edited.origin(0), 0); + } + + #[test] + fn offsets_are_characters() { + let source = SourceText::new("let s = \"é\" + %M.f(x)"); + let edited = source.apply(vec![Edit::replace(14, 21, "y")]); + assert_eq!(edited.text(), "let s = \"é\" + y"); + } + + #[test] + fn line_table() { + let lines = LineTable::new("ab\ncd\n"); + assert_eq!(lines.line_of(0), (1, 0)); + assert_eq!(lines.line_of(3), (2, 3)); + assert_eq!(lines.line_of(4), (2, 3)); + } +} diff --git a/compiler-rust/src/macros/expand.rs b/compiler-rust/src/macros/expand.rs new file mode 100644 index 0000000000..3c0ba054b9 --- /dev/null +++ b/compiler-rust/src/macros/expand.rs @@ -0,0 +1,330 @@ +//! Macro expansion of one file. +//! +//! Expansion works on the file's source text. A pass parses the text, lowers +//! the quotes it finds, type checks, and collects the edits the type checker +//! recorded at each macro use ([`super::discover`]). The edits are applied +//! and the next pass starts from the new text; a pass that records nothing +//! ends the expansion. The result is ordinary ReScript, which the compiler +//! then compiles like any file, with every position mapped back to the +//! source as written ([`SourceText::origin`]). +//! +//! Type checking again from the start after each round of edits is the +//! simple way to give generated code everything hand-written code gets +//! (inference, the frontend passes, later macro uses inside it). Its cost is +//! one type check per level of nesting, and only for files that use macros. + +use std::sync::Arc; + +use anyhow::Result; +use serde_json::{Value, json}; + +use crate::cmi::persistent_env::ModuleRegistry; +use crate::driver::{self, CompilerOptions, UserDiagnostic}; +use crate::location::Position; +use crate::parser::ast::StructureItemDesc; +use crate::parser::{Parser, code_frame, module}; +use crate::types::typemod::type_structure; + +use super::MacroHost; +use super::discover::{ComptimeSite, Discovery, InstanceTable, MacroDiagnostic, MacroMode}; +use super::edit::{Edit, LineTable, SourceText}; +use super::quote; + +/// More passes than any real nesting of macros and types needs. +const MAX_PASSES: usize = 64; + +/// A diagnostic at characters `start..end` of `text`, reported against the +/// source as written. +fn diagnostic( + original: &str, + text: &SourceText, + filename: &str, + start: u32, + end: u32, + message: &str, +) -> anyhow::Error { + let lines = LineTable::new(original); + let start = text.origin(start); + let end = text.origin(end).max(start + 1); + let position = |offset: u32| { + let (line, bol) = lines.line_of(offset); + Position::new(crate::intern::StrIdx::from_raw(0), line, bol as i32, offset as i32) + }; + UserDiagnostic::new( + code_frame::format_error(filename, original, &position(start), &position(end), message), + 2, + ) + .into() +} + +/// Expand the macros of a file. Returns the expanded text; it is the source +/// unchanged ([`SourceText::is_edited`] false) when the file has a problem +/// the ordinary compilation reports better (a syntax error, a type error +/// before the first macro). +pub fn expand_source( + source: &str, + filename: &str, + module_name: &str, + options: &CompilerOptions, + registry: &ModuleRegistry, + host: Arc, +) -> Result { + let mut text = Arc::new(SourceText::new(source)); + let mut instances = InstanceTable::default(); + let base_dir = std::path::Path::new(filename) + .parent() + .map(|dir| dir.to_path_buf()) + .unwrap_or_default(); + + for _pass in 0..MAX_PASSES { + let mut parser = Parser::for_expanded_source(filename, text.text()); + let structure = module::parse_structure(&mut parser); + if parser.has_errors() { + if !text.is_edited() { + return Ok(SourceText::new(source)); + } + return Err(generated_syntax_error(&parser, &text, filename)); + } + + let quote_edits = quote::lowering_edits(parser.arena(), &structure, &text, module_name); + if !quote_edits.is_empty() { + text = Arc::new(text.apply(quote_edits)); + continue; + } + + let opens = top_level_opens(&parser, &structure, &text); + let mut frontend_output = String::new(); + let frontend = match driver::run_implementation_frontend( + &mut parser, + structure, + text.text(), + filename, + options, + &mut frontend_output, + ) { + Ok(frontend) => frontend, + Err(error) => { + if !text.is_edited() { + return Ok(SourceText::new(source)); + } + return Err(error.context("in the macro-expanded source of this file")); + } + }; + let structure = frontend.structure; + parser.arena_mut().reserve_typecheck_synthetic_capacity(); + crate::types::typecore::prepare_typecheck_arena(parser.arena_mut()); + let arena = parser.arena(); + + let mut pass_options = options.clone(); + pass_options.experimental_let_unwrap = frontend.experimental_let_unwrap; + let type_ctx = driver::fresh_type_context(); + let pass = { + let (mut tctx, env) = driver::in_process_type_check_context( + &type_ctx, + arena, + &pass_options, + registry, + module_name, + &frontend.file_config, + &frontend.frontend_warning_specs, + ); + tctx.macro_mode = MacroMode::Discover(Box::new(Discovery::new( + host.clone(), + text.clone(), + base_dir.clone(), + std::mem::take(&mut instances), + ))); + // The result is not used: what counts is what the pass found. + let _ = type_structure(&mut tctx, &env, arena, &structure); + match std::mem::replace(&mut tctx.macro_mode, MacroMode::Off) { + MacroMode::Discover(discovery) => discovery.finish(), + MacroMode::Off => unreachable!("the discovery pass state was taken"), + } + }; + drop(parser); + instances = pass.instances; + let mut edits = pass.edits; + let mut errors = pass.errors; + + for site in &pass.comptime { + match evaluate_comptime(site, &opens, filename, module_name, options, registry, &host) { + Ok(literal) => edits.push(Edit::replace(site.start, site.end, format!("({literal})"))), + Err(message) => errors.push(MacroDiagnostic { + start: site.start, + end: site.end, + message, + }), + } + } + + if edits.is_empty() { + let first_error = errors.iter().min_by_key(|error| error.start); + let first_failed_item = pass.failed_items.iter().min().copied(); + return match (first_error, first_failed_item) { + // A type error comes first: the ordinary compilation reports it. + (Some(error), Some(failed)) if failed < error.start => Ok(unwrap_text(text)), + (Some(error), _) => Err(diagnostic( + source, + &text, + filename, + error.start, + error.end, + &error.message, + )), + (None, _) => Ok(unwrap_text(text)), + }; + } + text = Arc::new(text.apply(edits)); + } + Err(UserDiagnostic::new( + format!( + "{filename}: macro expansion did not finish after {MAX_PASSES} passes. A macro probably generates a call to itself.\n" + ), + 2, + ) + .into()) +} + +/// Move every position of a parse of the expanded text to where it is in +/// the source as written. Generated code takes the position of the macro +/// use it was generated for. +pub fn remap_positions(arena: &mut crate::parse_arena::ParseArena, text: &SourceText, original: &str) { + let lines = LineTable::new(original); + // An ordinary parse counts a column in UTF-16 code units; only text + // with characters outside the BMP makes that differ from characters. + let wide: Option> = original + .chars() + .any(|ch| ch.len_utf16() > 1) + .then(|| original.chars().collect()); + arena.remap_positions(|position| { + if position.cnum < 0 { + return; + } + let offset = text.origin(position.cnum as u32); + let (line, bol) = lines.line_of(offset); + let column = match &wide { + Some(chars) => chars[bol as usize..offset as usize] + .iter() + .map(|ch| ch.len_utf16() as u32) + .sum(), + None => offset - bol, + }; + position.line = line; + position.bol = bol as i32; + position.cnum = (bol + column) as i32; + }); +} + +fn unwrap_text(text: Arc) -> SourceText { + Arc::try_unwrap(text).unwrap_or_else(|shared| (*shared).clone()) +} + +fn generated_syntax_error(parser: &Parser<'_>, text: &SourceText, filename: &str) -> anyhow::Error { + let mut output = String::from( + "A macro generated code with a syntax error. The frame shows the expanded source.\n\n", + ); + for diagnostic in parser.diagnostics().iter().take(1) { + output.push_str(&code_frame::format_error( + filename, + text.text(), + &diagnostic.start_pos, + &diagnostic.end_pos, + &diagnostic.explain_with_source(Some(text.text())), + )); + } + UserDiagnostic::new(output, 2).into() +} + +/// The `open` statements at the top level of the file, as source text: +/// `%comptime` expressions are compiled in their scope. +fn top_level_opens( + parser: &Parser<'_>, + structure: &[crate::parser::ast::StructureItem], + text: &SourceText, +) -> Vec { + structure + .iter() + .filter(|item| matches!(item.pstr_desc, StructureItemDesc::Pstr_open(_))) + .map(|item| { + let location = parser.arena().to_location(item.pstr_loc); + text.slice(location.loc_start.cnum.max(0) as u32, location.loc_end.cnum.max(0) as u32) + .to_string() + }) + .collect() +} + +/// `%comptime(expr)`: compile `let value = expr` as a module of its own, +/// run it, and write the value back as a literal. +fn evaluate_comptime( + site: &ComptimeSite, + opens: &[String], + filename: &str, + module_name: &str, + options: &CompilerOptions, + registry: &ModuleRegistry, + host: &Arc, +) -> Result { + if site.shape.get("k") == Some(&json!("other")) { + return Err(format!( + "%comptime: a value of type {} cannot be written as a literal. Supported: int, float, string, bool, unit, arrays, tuples, options, dicts and records of those.", + site.shape.get("name").and_then(Value::as_str).unwrap_or("this type"), + )); + } + let source = format!("{}\nlet value = {}\n", opens.join("\n"), site.expression); + let comptime_module = format!("{module_name}__comptime"); + let comptime_file = std::path::Path::new(filename) + .with_file_name(format!("{comptime_module}.res")) + .to_string_lossy() + .into_owned(); + let mut comptime_options = options.clone(); + comptime_options.source_filename = Some(comptime_file.clone()); + comptime_options.module_name = Some(comptime_module.clone()); + comptime_options.capture_intermediates = false; + comptime_options.skip_js_render = false; + comptime_options.js_output_targets = Vec::new(); + let compiled = driver::compile_source_in_process( + &source, + &comptime_file, + &comptime_module, + &comptime_options, + registry, + false, + ) + .map_err(|error| { + format!( + "%comptime: the expression is compiled on its own, before this file, so it can only use other modules.\n{error:#}" + ) + })?; + + let base_dir = std::path::Path::new(filename) + .parent() + .map(|dir| dir.to_path_buf()) + .unwrap_or_default(); + let mut answers = serde_json::Map::new(); + for _ in 0..1024 { + let request = json!({ + "kind": "eval", + "source": compiled.js_output, + "shape": site.shape, + "answers": answers, + }); + let response = host + .call(&request.to_string()) + .map_err(|message| format!("%comptime: the macro engine failed: {message}"))?; + let response: Value = serde_json::from_str(&response) + .map_err(|error| format!("%comptime: the macro engine returned invalid JSON: {error}"))?; + if let Some(literal) = response.get("ok").and_then(Value::as_str) { + return Ok(literal.to_string()); + } + if let Some(message) = response.get("error").and_then(Value::as_str) { + return Err(format!("%comptime: {message}")); + } + let Some(question) = response.get("need").and_then(Value::as_str) else { + return Err("%comptime: the macro engine returned an unknown response.".into()); + }; + let answer = super::discover::answer_input(&base_dir, question) + .unwrap_or_else(|| json!({ "__error": format!("`{question}` cannot be answered in %comptime.") })); + answers.insert(question.to_string(), answer); + } + Err("%comptime: the expression asked more than 1024 questions.".into()) +} diff --git a/compiler-rust/src/macros/host.js b/compiler-rust/src/macros/host.js new file mode 100644 index 0000000000..05a449af9e --- /dev/null +++ b/compiler-rust/src/macros/host.js @@ -0,0 +1,178 @@ +// The part of the macro engine that runs inside the JavaScript engine: a +// CommonJS-style loader for compiled ReScript modules and the entry point the +// compiler calls. It is the same script in the embedded QuickJS and in a +// browser. The embedder provides `__rescript_macro_source(moduleName)`, which +// returns the compiled JavaScript of a module or undefined. +// +// A macro cannot call back into the compiler. When it needs an answer the +// compiler has not given yet (the shape of a type, the text of a file), `ask` +// throws, the call returns `{need: question}`, and the compiler runs the macro +// again with the answer added. Macros are deterministic, so the second run +// takes the same path. +(function () { + "use strict"; + var modules = Object.create(null); + var state = { answers: Object.create(null), expected: null }; + + globalThis.__rescript_macro = { + ask: function (question) { + if (Object.prototype.hasOwnProperty.call(state.answers, question)) { + var answer = state.answers[question]; + if (answer !== null && typeof answer === "object" && typeof answer.__error === "string") { + throw { __macro_error: answer.__error }; + } + return answer === null ? undefined : answer; + } + throw { __macro_need: question }; + }, + fail: function (message, offset) { + throw { __macro_error: String(message), offset: offset }; + }, + expected: function () { + return state.expected; + }, + }; + + function moduleName(specifier) { + var base = specifier.slice(specifier.lastIndexOf("/") + 1); + var dot = base.indexOf("."); + return dot < 0 ? base : base.slice(0, dot); + } + + // The ES module output of the ReScript compiler has a fixed shape: imports + // first, one export list last. + function toCommonJs(source) { + if (!/^\s*(import|export)\s/m.test(source)) return source; + return source + .replace(/^import \* as (\S+) from (["'][^"']+["']);?$/gm, "const $1 = require($2);") + .replace(/^import (\{[^}]*\}) from (["'][^"']+["']);?$/gm, function (_, names, from) { + return "const " + names.replace(/ as /g, ": ") + " = require(" + from + ");"; + }) + .replace(/^import (\S+) from (["'][^"']+["']);?$/gm, "const $1 = require($2).default;") + .replace(/^export default (\S+?);?$/gm, "exports.default = $1;") + .replace(/^export \{([^}]*)\};?$/gm, function (_, names) { + return names + .split(",") + .map(function (entry) { + var parts = entry.trim().split(/\s+as\s+/); + if (parts[0] === "") return ""; + return "exports." + (parts[1] || parts[0]) + " = " + parts[0] + ";"; + }) + .join("\n"); + }); + } + + function load(name) { + var loaded = modules[name]; + if (loaded) return loaded.exports; + var source = __rescript_macro_source(name); + if (source === undefined || source === null) { + throw { __macro_error: "Macro code needs the module `" + name + "`, which is not available at compile time." }; + } + var module = { exports: {} }; + modules[name] = module; + try { + new Function("require", "exports", "module", toCommonJs(source))( + function (specifier) { + return load(moduleName(specifier)); + }, + module.exports, + module, + ); + } catch (error) { + delete modules[name]; + throw error; + } + return module.exports; + } + + // The source text of a compile-time value, read by its type. + function reify(value, shape) { + switch (shape.k) { + case "int": + return String(value | 0); + case "float": + if (!isFinite(value)) throw { __macro_error: "%comptime: the value is not a finite number." }; + return /[.e]/.test(String(value)) ? String(value) : String(value) + "."; + case "string": + return JSON.stringify(String(value)); + case "bool": + return value ? "true" : "false"; + case "unit": + return "()"; + case "array": + return "[" + value.map(function (item) { return reify(item, shape.of); }).join(", ") + "]"; + case "tuple": + return "(" + shape.of.map(function (item, index) { return reify(value[index], item); }).join(", ") + ")"; + case "option": + if (value === undefined) return "None"; + if (value !== null && typeof value === "object" && value.BS_PRIVATE_NESTED_SOME_NONE !== undefined) { + throw { __macro_error: "%comptime: a nested option cannot be written as a literal." }; + } + return "Some(" + reify(value, shape.of) + ")"; + case "dict": + return "dict{" + Object.keys(value).map(function (key) { + return JSON.stringify(key) + ": " + reify(value[key], shape.of); + }).join(", ") + "}"; + case "record": + return "{" + shape.fields.map(function (field) { + var item = value[field.js]; + if (field.optional) return item === undefined ? null : field.name + ": " + reify(item, field.of); + return field.name + ": " + reify(item, field.of); + }).filter(function (item) { return item !== null; }).join(", ") + "}"; + default: + throw { __macro_error: "%comptime: a value of type " + shape.name + " cannot be written as a literal." }; + } + } + + function describe(error) { + if (error && typeof error === "object") { + if (error.RE_EXN_ID !== undefined) { + var parts = [String(error.RE_EXN_ID)]; + if (error._1 !== undefined) parts.push(typeof error._1 === "string" ? error._1 : JSON.stringify(error._1)); + if (error.Error && error.Error.message) parts.push(error.Error.message); + return parts.join(": "); + } + if (error.message !== undefined) return String(error.message); + } + return String(error); + } + + globalThis.__rescript_macro_call = function (requestJson) { + var request = JSON.parse(requestJson); + state.answers = request.answers || Object.create(null); + state.expected = request.expected || null; + try { + if (request.kind === "reset") { + modules = Object.create(null); + return JSON.stringify({ ok: "" }); + } + if (request.kind === "eval") { + // %comptime: `source` is a compiled module that exports `value`. + var module = { exports: {} }; + new Function("require", "exports", "module", toCommonJs(request.source))( + function (specifier) { return load(moduleName(specifier)); }, + module.exports, + module, + ); + return JSON.stringify({ ok: reify(module.exports.value, request.shape) }); + } + var exports = load(request.module); + var macro = exports[request.name]; + if (typeof macro !== "function") { + throw { __macro_error: "`" + request.module + "." + request.name + "` is not a function, so it cannot run as a macro." }; + } + var result = macro.apply(null, request.args); + if (result === null || typeof result !== "object" || typeof result.c !== "string") { + throw { __macro_error: "The macro `" + request.module + "." + request.name + "` did not return code." }; + } + return JSON.stringify({ ok: result.c }); + } catch (error) { + if (error && error.__macro_need !== undefined) return JSON.stringify({ need: error.__macro_need }); + if (error && error.__macro_error !== undefined) { + return JSON.stringify({ error: error.__macro_error, offset: error.offset === undefined ? null : error.offset }); + } + return JSON.stringify({ error: "The macro raised an exception: " + describe(error) }); + } + }; +})(); diff --git a/compiler-rust/src/macros/mod.rs b/compiler-rust/src/macros/mod.rs new file mode 100644 index 0000000000..d801915f13 --- /dev/null +++ b/compiler-rust/src/macros/mod.rs @@ -0,0 +1,69 @@ +//! Compile-time macros. +//! +//! A macro is a ReScript function the compiler runs while compiling another +//! file; it returns code. The design is in `docs/comptime/README.md`. This +//! module holds the compiler's half: +//! +//! - [`quote`] rewrites the quotes of a macro's own file (`%code(...)`, +//! `%type(...)`, `%pat(...)`) into calls that build the quoted source text. +//! - [`discover`] is the type checker's side: it recognizes the places a +//! macro is used, asks the engine to run it, and records the result as an +//! edit of the source text. +//! - [`reflect`] answers a macro's questions about types. +//! - [`expand`] drives it: parse, type check, apply the edits, repeat until a +//! pass finds nothing to expand. The compiler then compiles the expanded +//! source like any other file, so a file without macros takes the path it +//! always took. +//! - [`MacroHost`] is the JavaScript engine that runs macro code. The native +//! build embeds QuickJS ([`quickjs`]); the browser build uses the page's +//! own engine. + +pub mod discover; +pub mod edit; +pub mod expand; +#[cfg(feature = "macro-quickjs")] +pub mod quickjs; +pub mod quote; +pub mod reflect; + +/// The engine-side script: module loader and call entry point. +pub const HOST_JS: &str = include_str!("host.js"); + +/// The runtime module the macro API lives in. +pub const MACRO_MODULE: &str = "Macro"; + +/// A JavaScript engine that runs macro code. +/// +/// `call` takes one JSON request and returns the JSON response of +/// `__rescript_macro_call` in `host.js`. The engine finds the compiled +/// JavaScript of a module by name; how is up to the embedder. +pub trait MacroHost: Send + Sync { + fn call(&self, request: &str) -> Result; +} + +impl std::fmt::Debug for dyn MacroHost { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("MacroHost") + } +} + +/// Marker error of a compilation that met a macro while macro expansion was +/// off. The caller expands the source with [`expand::expand_source`] and +/// compiles the result. +#[derive(Debug)] +pub struct MacroExpansionRequired; + +impl std::fmt::Display for MacroExpansionRequired { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("this file uses macros and must be expanded before it is compiled") + } +} + +impl std::error::Error for MacroExpansionRequired {} + +/// Whether an extension or attribute name is a module path (`Json.encode`), +/// which is how a macro is named. PPX extensions and built-in attributes +/// start with a lowercase letter. +pub fn is_macro_name(name: &str) -> bool { + name.starts_with(|c: char| c.is_ascii_uppercase()) +} diff --git a/compiler-rust/src/macros/quickjs.rs b/compiler-rust/src/macros/quickjs.rs new file mode 100644 index 0000000000..8a9ad1b57f --- /dev/null +++ b/compiler-rust/src/macros/quickjs.rs @@ -0,0 +1,158 @@ +//! The macro engine of native builds: QuickJS, linked into the compiler. +//! +//! One engine per thread that expands macros, created on first use. It has +//! no file system, no network, no clock and no random numbers: a macro gets +//! its inputs from the compiler (`readFile`, `env`, `Type.info`), which is +//! what makes an expansion a function of recorded inputs. + +use std::cell::RefCell; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{Duration, Instant}; + +use rquickjs::{Context, Function, Runtime}; + +use super::{HOST_JS, MacroHost}; + +/// The compiled JavaScript of a module, by module name. +pub type ModuleSources = Arc Option + Send + Sync>; + +/// Memory one engine may use. +const MEMORY_LIMIT: usize = 512 * 1024 * 1024; +/// Time one macro call may take. +const TIME_LIMIT: Duration = Duration::from_secs(20); + +const SANDBOX_JS: &str = r#" +(function () { + function refuse(what) { + return function () { + throw { __macro_error: what + " is not available at compile time: a macro has to give the same result every time." }; + }; + } + Math.random = refuse("Math.random"); + var RealDate = Date; + function FixedDate() { + if (arguments.length === 0) refuse("The current time")(); + return new (Function.prototype.bind.apply(RealDate, [null].concat(Array.prototype.slice.call(arguments))))(); + } + FixedDate.prototype = RealDate.prototype; + FixedDate.UTC = RealDate.UTC; + FixedDate.parse = RealDate.parse; + FixedDate.now = refuse("Date.now"); + globalThis.Date = FixedDate; +})(); +"#; + +static NEXT_HOST: AtomicU64 = AtomicU64::new(1); + +/// A [`MacroHost`] that runs macros in QuickJS. +pub struct QuickJsHost { + id: u64, + /// Bumped when compiled modules change, so engines drop what they loaded. + generation: AtomicU64, + sources: ModuleSources, +} + +struct Engine { + host: u64, + generation: u64, + deadline: Arc, + started: Instant, + context: Context, + // Dropped after the context. + _runtime: Runtime, +} + +thread_local! { + static ENGINE: RefCell> = const { RefCell::new(None) }; +} + +impl QuickJsHost { + pub fn new(sources: ModuleSources) -> Self { + QuickJsHost { + id: NEXT_HOST.fetch_add(1, Ordering::Relaxed), + generation: AtomicU64::new(0), + sources, + } + } + + /// Forget the modules engines have loaded: their JavaScript changed. + pub fn invalidate(&self) { + self.generation.fetch_add(1, Ordering::Relaxed); + } + + fn engine(&self, generation: u64) -> Result { + let runtime = Runtime::new().map_err(|error| error.to_string())?; + runtime.set_memory_limit(MEMORY_LIMIT); + runtime.set_max_stack_size(4 * 1024 * 1024); + let started = Instant::now(); + let deadline = Arc::new(AtomicU64::new(u64::MAX)); + let interrupt_deadline = deadline.clone(); + runtime.set_interrupt_handler(Some(Box::new(move || { + started.elapsed().as_millis() as u64 > interrupt_deadline.load(Ordering::Relaxed) + }))); + let context = Context::full(&runtime).map_err(|error| error.to_string())?; + let sources = self.sources.clone(); + context + .with(|ctx| -> rquickjs::Result<()> { + let source = Function::new(ctx.clone(), move |name: String| -> Option { + sources(&name) + })?; + ctx.globals().set("__rescript_macro_source", source)?; + ctx.eval::<(), _>(SANDBOX_JS)?; + ctx.eval::<(), _>(HOST_JS)?; + Ok(()) + }) + .map_err(|error| format!("cannot start the macro engine: {error}"))?; + Ok(Engine { + host: self.id, + generation, + deadline, + started, + context, + _runtime: runtime, + }) + } +} + +impl MacroHost for QuickJsHost { + fn call(&self, request: &str) -> Result { + let generation = self.generation.load(Ordering::Relaxed); + ENGINE.with(|slot| { + let mut slot = slot.borrow_mut(); + let reuse = matches!(&*slot, Some(engine) if engine.host == self.id && engine.generation == generation); + if !reuse { + *slot = None; + *slot = Some(self.engine(generation)?); + } + let engine = slot.as_ref().expect("the engine was just created"); + engine.deadline.store( + (engine.started.elapsed() + TIME_LIMIT).as_millis() as u64, + Ordering::Relaxed, + ); + let result = engine.context.with(|ctx| -> Result { + let call: Function = ctx + .globals() + .get("__rescript_macro_call") + .map_err(|error| error.to_string())?; + call.call::<_, String>((request,)).map_err(|error| { + let thrown = ctx.catch(); + match thrown.as_exception().and_then(|exception| exception.message()) { + Some(message) if message.contains("interrupted") => format!( + "a macro ran for more than {} seconds and was stopped", + TIME_LIMIT.as_secs() + ), + Some(message) => message, + None => error.to_string(), + } + }) + }); + engine.deadline.store(u64::MAX, Ordering::Relaxed); + if result.is_err() { + // The engine may be out of memory or mid-call: start over. + *slot = None; + } + result + }) + } +} diff --git a/compiler-rust/src/macros/quote.rs b/compiler-rust/src/macros/quote.rs new file mode 100644 index 0000000000..2d717e7888 --- /dev/null +++ b/compiler-rust/src/macros/quote.rs @@ -0,0 +1,414 @@ +//! Lowering of quotes in a macro's own file. +//! +//! `%code(JSON.Encode.string(${value}))` becomes +//! +//! ```text +//! Macro.__quoteCode(["JSON.Encode.string(", ")"], [Macro.__holeCode(value)]) +//! ``` +//! +//! The pieces are the quote's source text between the holes, so a quote is +//! parsed and reported on where it is written and the macro's compiled +//! JavaScript carries it as string literals. The hole expressions stay +//! ordinary code of the macro: they are type checked, and a quote nested in a +//! hole is lowered by the next pass. +//! +//! Hygiene, as far as syntax decides it: a name the quote uses that the +//! macro's file defines at its top level is written with the module's name +//! (`encode` in `Json.res` becomes `Json.encode`), so it means the same where +//! the macro is used. Names the quote binds itself and all other names are +//! left as written and resolve at the use. + +use std::collections::HashSet; + +use crate::binary_ast::ast_iter::{self, AstIter}; +use crate::parse_arena::{CoreTypeIdx, ExprIdx, LocIdx, ParseArena, PatIdx}; +use crate::parser::ast::{ + CoreTypeDesc, ExpressionDesc, Extension, PatternDesc, Payload, StructureItem, StructureItemDesc, +}; +use crate::parser::longident::Longident; +use crate::parser::module::HOLE_EXTENSION; + +use super::edit::{Edit, Segment, SourceText}; + +/// The extension names that are quotes. +pub fn is_quote_name(name: &str) -> bool { + matches!(name, "code" | "type" | "pat") +} + +fn range(arena: &ParseArena, loc: LocIdx) -> (u32, u32) { + let location = arena.to_location(loc); + ( + location.loc_start.cnum.max(0) as u32, + location.loc_end.cnum.max(0) as u32, + ) +} + +/// A ReScript string literal with the value `text`. +pub fn string_literal(text: &str) -> String { + let mut out = String::with_capacity(text.len() + 2); + out.push('"'); + for ch in text.chars() { + match ch { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + ch if (ch as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", ch as u32)), + ch => out.push(ch), + } + } + out.push('"'); + out +} + +/// Names the file defines at its top level. +#[derive(Default)] +struct TopLevel { + values: HashSet, + modules: HashSet, +} + +fn pattern_names(arena: &ParseArena, pat: PatIdx, out: &mut HashSet) { + let mut collector = Binders { names: out }; + collector.pat(arena, pat); +} + +struct Binders<'a> { + names: &'a mut HashSet, +} + +impl AstIter for Binders<'_> { + fn pat(&mut self, arena: &ParseArena, idx: PatIdx) { + match &arena.get_pat(idx).ppat_desc { + PatternDesc::Ppat_var(name) => { + self.names.insert(arena.get_string(name.txt).to_string()); + } + PatternDesc::Ppat_alias(_, name) => { + self.names.insert(arena.get_string(name.txt).to_string()); + ast_iter::walk_pat(self, arena, idx); + } + // A hole in a pattern is filled when the macro runs. + PatternDesc::Ppat_extension(_) => {} + _ => ast_iter::walk_pat(self, arena, idx), + } + } + // Only binders: do not descend into expressions and types of a pattern. + fn expr(&mut self, _arena: &ParseArena, _idx: ExprIdx) {} + fn typ(&mut self, _arena: &ParseArena, _idx: CoreTypeIdx) {} +} + +fn top_level(arena: &ParseArena, structure: &[StructureItem]) -> TopLevel { + let mut names = TopLevel::default(); + for item in structure { + match &item.pstr_desc { + StructureItemDesc::Pstr_value((_, bindings)) => { + for binding in arena.vb_list(*bindings) { + pattern_names(arena, binding.pvb_pat, &mut names.values); + } + } + StructureItemDesc::Pstr_primitive(description) => { + names + .values + .insert(arena.get_string(description.pval_name.txt).to_string()); + } + StructureItemDesc::Pstr_module(binding) => { + names + .modules + .insert(arena.get_string(binding.pmb_name.txt).to_string()); + } + StructureItemDesc::Pstr_recmodule(bindings) => { + for binding in bindings.iter() { + names + .modules + .insert(arena.get_string(binding.pmb_name.txt).to_string()); + } + } + _ => {} + } + } + names +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum HoleKind { + Code, + Type, + Pat, + Item, +} + +struct Hole { + /// The hole, `${...}`. + outer: (u32, u32), + /// The expression inside it. + inner: (u32, u32), + kind: HoleKind, +} + +/// What a walk over a quote's payload finds. +struct QuoteScan<'a> { + holes: Vec, + /// Value identifiers the quote uses: range and name, for a plain name; + /// range and root module, for a path. + value_uses: Vec<((u32, u32), String)>, + module_roots: Vec<((u32, u32), String)>, + bound: HashSet, + /// Expressions that are a structure item of the quote on their own. + item_exprs: &'a HashSet, +} + +fn hole_inner(arena: &ParseArena, extension: &Extension) -> Option<(u32, u32)> { + if arena.get_string(extension.0.txt) != HOLE_EXTENSION { + return None; + } + let Payload::PStr(items) = &extension.1 else { + return None; + }; + let [item] = items.as_slice() else { + return None; + }; + let StructureItemDesc::Pstr_eval(eval) = &item.pstr_desc else { + return None; + }; + Some(range(arena, arena.get_expr(eval.0).pexp_loc)) +} + +impl AstIter for QuoteScan<'_> { + fn expr(&mut self, arena: &ParseArena, idx: ExprIdx) { + let expr = arena.get_expr(idx); + match &expr.pexp_desc { + ExpressionDesc::Pexp_extension(extension) => { + if let Some(inner) = hole_inner(arena, extension) { + let kind = if self.item_exprs.contains(&idx) { + HoleKind::Item + } else { + HoleKind::Code + }; + self.holes.push(Hole { + outer: range(arena, expr.pexp_loc), + inner, + kind, + }); + return; + } + // A quote inside a quote is the inner macro's business. + if is_quote_name(arena.get_string(extension.0.txt)) { + return; + } + ast_iter::walk_expr(self, arena, idx); + } + ExpressionDesc::Pexp_ident(lid) => match arena.get_longident(lid.txt) { + Longident::Lident(name) => { + self.value_uses.push(( + range(arena, expr.pexp_loc), + arena.get_string(*name).to_string(), + )); + } + longident => { + if let Some(root) = longident.flatten_idx().first() { + self.module_roots.push(( + range(arena, expr.pexp_loc), + arena.get_string(*root).to_string(), + )); + } + } + }, + _ => ast_iter::walk_expr(self, arena, idx), + } + } + + fn pat(&mut self, arena: &ParseArena, idx: PatIdx) { + let pat = arena.get_pat(idx); + match &pat.ppat_desc { + PatternDesc::Ppat_extension(extension) => { + if let Some(inner) = hole_inner(arena, extension) { + self.holes.push(Hole { + outer: range(arena, pat.ppat_loc), + inner, + kind: HoleKind::Pat, + }); + } + } + PatternDesc::Ppat_var(name) => { + self.bound.insert(arena.get_string(name.txt).to_string()); + } + PatternDesc::Ppat_alias(_, name) => { + self.bound.insert(arena.get_string(name.txt).to_string()); + ast_iter::walk_pat(self, arena, idx); + } + _ => ast_iter::walk_pat(self, arena, idx), + } + } + + fn typ(&mut self, arena: &ParseArena, idx: CoreTypeIdx) { + let typ = arena.get_core_type(idx); + if let CoreTypeDesc::Ptyp_extension(extension) = &typ.ptyp_desc + && let Some(inner) = hole_inner(arena, extension) + { + self.holes.push(Hole { + outer: range(arena, typ.ptyp_loc), + inner, + kind: HoleKind::Type, + }); + return; + } + ast_iter::walk_typ(self, arena, idx); + } +} + +/// Finds the quotes of a file that are not inside another quote. +struct QuoteFinder<'a> { + text: &'a SourceText, + module_name: &'a str, + top_level: &'a TopLevel, + edits: Vec, +} + +impl QuoteFinder<'_> { + fn lower(&mut self, arena: &ParseArena, loc: LocIdx, extension: &Extension) { + let name = arena.get_string(extension.0.txt); + let (start, end) = range(arena, loc); + // The payload is what is between the parentheses of `%code(...)`. + let (_, id_end) = range(arena, extension.0.loc); + if end <= id_end + 1 || self.text.slice(id_end, id_end + 1) != "(" { + // `%code` without a payload: the type checker reports it. + return; + } + let payload = (id_end + 1, end - 1); + + let mut item_exprs = HashSet::new(); + let mut single_expression = false; + if let Payload::PStr(items) = &extension.1 { + for item in items.iter() { + if let StructureItemDesc::Pstr_eval(eval) = &item.pstr_desc { + item_exprs.insert(eval.0); + } + } + single_expression = items.len() == 1 && item_exprs.len() == 1; + } + // The only item of `%code(${e})` is an expression hole, not a + // declaration hole. + let no_items = HashSet::new(); + let mut scan = QuoteScan { + holes: Vec::new(), + value_uses: Vec::new(), + module_roots: Vec::new(), + bound: HashSet::new(), + item_exprs: if single_expression { &no_items } else { &item_exprs }, + }; + scan.payload(arena, &extension.1); + + let function = match name { + "type" => "__quoteType", + "pat" => "__quotePat", + _ if single_expression => "__quoteCode", + _ => "__quoteDecls", + }; + + // Qualify the names the file defines. + let mut substitutions: Vec<((u32, u32), String)> = Vec::new(); + for (at, used) in &scan.value_uses { + if self.top_level.values.contains(used) && !scan.bound.contains(used) { + substitutions.push((*at, format!("{}.{}", self.module_name, used))); + } + } + for (at, root) in &scan.module_roots { + if self.top_level.modules.contains(root) { + substitutions.push(( + *at, + format!("{}.{}", self.module_name, self.text.slice(at.0, at.1)), + )); + } + } + + scan.holes.sort_by_key(|hole| hole.outer.0); + substitutions.sort_by_key(|(at, _)| at.0); + let in_hole = |at: (u32, u32)| { + scan.holes + .iter() + .any(|hole| at.0 >= hole.outer.0 && at.1 <= hole.outer.1) + }; + substitutions.retain(|(at, _)| at.0 >= payload.0 && at.1 <= payload.1 && !in_hole(*at)); + + // The text between two holes, with the substitutions applied. + let piece = |from: u32, to: u32| -> String { + let mut out = String::new(); + let mut cursor = from; + for (at, replacement) in &substitutions { + if at.0 < cursor || at.1 > to { + continue; + } + out.push_str(self.text.slice(cursor, at.0)); + out.push_str(replacement); + cursor = at.1; + } + out.push_str(self.text.slice(cursor, to)); + out + }; + + let mut pieces = Vec::with_capacity(scan.holes.len() + 1); + let mut cursor = payload.0; + for hole in &scan.holes { + pieces.push(string_literal(&piece(cursor, hole.outer.0))); + cursor = hole.outer.1; + } + pieces.push(string_literal(&piece(cursor, payload.1))); + + let mut segments = vec![Segment::Text(format!( + "(Macro.{function}([{}], [", + pieces.join(", ") + ))]; + for (index, hole) in scan.holes.iter().enumerate() { + let wrapper = match hole.kind { + HoleKind::Code => "__holeCode", + HoleKind::Type => "__holeType", + HoleKind::Pat => "__holePat", + HoleKind::Item => "__holeItem", + }; + segments.push(Segment::Text(format!( + "{}Macro.{wrapper}(", + if index == 0 { "" } else { ", " } + ))); + segments.push(Segment::Copy(hole.inner.0, hole.inner.1)); + segments.push(Segment::Text(")".into())); + } + segments.push(Segment::Text("]))".into())); + self.edits.push(Edit { + start, + end, + segments, + }); + } +} + +impl AstIter for QuoteFinder<'_> { + fn expr(&mut self, arena: &ParseArena, idx: ExprIdx) { + let expr = arena.get_expr(idx); + if let ExpressionDesc::Pexp_extension(extension) = &expr.pexp_desc + && is_quote_name(arena.get_string(extension.0.txt)) + { + self.lower(arena, expr.pexp_loc, extension); + return; + } + ast_iter::walk_expr(self, arena, idx); + } +} + +/// The edits that lower the outermost quotes of `structure`. +pub fn lowering_edits( + arena: &ParseArena, + structure: &[StructureItem], + text: &SourceText, + module_name: &str, +) -> Vec { + let top_level = top_level(arena, structure); + let mut finder = QuoteFinder { + text, + module_name, + top_level: &top_level, + edits: Vec::new(), + }; + ast_iter::walk_structure(&mut finder, arena, structure); + finder.edits +} diff --git a/compiler-rust/src/macros/reflect.rs b/compiler-rust/src/macros/reflect.rs new file mode 100644 index 0000000000..9032add786 --- /dev/null +++ b/compiler-rust/src/macros/reflect.rs @@ -0,0 +1,411 @@ +//! Answers to a macro's questions about types. +//! +//! A macro holds a type as source text plus a handle: an index into the +//! [`TypeTable`] of the expansion that is running. `Type.info` sends the +//! handle back and gets one level of structure; nested types are handles +//! again, so a recursive type needs no special case and nothing is described +//! that the macro does not look at. +//! +//! The JSON written here is the run-time representation of `Macro.Type.info` +//! (packages/@rescript/runtime/Macro.res): a constructor without payload is +//! its name, one with a payload is an object tagged `TAG`. + +use serde_json::{Value, json}; + +use crate::types::context::TypeContext; +use crate::types::ctype; +use crate::types::decl::{ + Attribute, AttributePayload, ConstructorArguments, LabelDeclaration, TypeKind, +}; +use crate::types::env::Env; +use crate::types::path::Path; +use crate::types::predef; +use crate::types::type_expr::{RowField, TypeDesc, TypeExprRef}; +use crate::types::variant_runtime::LiteralTag; + +/// The types a running expansion has handed to the macro. +#[derive(Default)] +pub struct TypeTable { + types: Vec, +} + +impl TypeTable { + pub fn get(&self, id: usize) -> Option { + self.types.get(id).copied() + } + + fn add(&mut self, ctx: &TypeContext, ty: TypeExprRef) -> usize { + let repr = ctx.repr(ty); + if let Some(index) = self.types.iter().position(|known| ctx.repr(*known) == repr) { + return index; + } + self.types.push(ty); + self.types.len() - 1 + } +} + +/// The source text of a type, as it is written where the macro is used. +pub fn print_type(ctx: &TypeContext, ty: TypeExprRef) -> String { + let mut printer = crate::types::printtyp::Printtyp::new(ctx); + printer.reset_and_mark_loops(ty); + printer.type_expr(ty) +} + +/// Whether inference has not settled `ty` at all. +pub fn is_unknown(ctx: &TypeContext, ty: TypeExprRef) -> bool { + matches!( + &*ctx.get_desc(ctx.repr(ty)), + TypeDesc::Tvar(_) | TypeDesc::Tunivar(_) + ) +} + +/// A type as the macro holds it: `{c: source, id: handle}`. +pub fn type_ref(ctx: &TypeContext, table: &mut TypeTable, ty: TypeExprRef) -> Value { + json!({ "c": print_type(ctx, ty), "id": table.add(ctx, ty) }) +} + +fn attributes(attrs: &[Attribute]) -> Value { + Value::Array( + attrs + .iter() + .map(|attr| { + let mut out = serde_json::Map::new(); + out.insert("name".into(), Value::String(attr.attr_name.txt.clone())); + if let AttributePayload::Str(payload) = &attr.attr_payload { + out.insert("payload".into(), Value::String(payload.clone())); + } + Value::Object(out) + }) + .collect(), + ) +} + +/// Attributes a macro reads as data: everything except the ones the +/// compiler interprets itself. +fn user_attributes(attrs: &[Attribute]) -> Value { + let user: Vec = attrs + .iter() + .filter(|attr| { + !matches!( + attr.attr_name.txt.as_str(), + "as" | "res.optional" | "ns.optional" | "res.doc" | "ocaml.doc" | "deprecated" + ) + }) + .cloned() + .collect(); + attributes(&user) +} + +fn tag_text(tag: &LiteralTag) -> String { + match tag { + LiteralTag::String(s) => s.clone(), + LiteralTag::Int(i) => i.to_string(), + LiteralTag::Float(f) | LiteralTag::BigInt(f) => f.clone(), + LiteralTag::Bool(b) => b.to_string(), + LiteralTag::Null => "null".into(), + LiteralTag::Undefined => "undefined".into(), + } +} + +/// The type of a declaration's member (a field, a constructor argument) at +/// the instance `args` of the declaration's parameters. +fn member_type( + ctx: &TypeContext, + params: &[TypeExprRef], + args: &[TypeExprRef], + member: TypeExprRef, +) -> TypeExprRef { + if params.is_empty() || params.len() != args.len() { + return member; + } + let (fresh_params, fresh_member) = ctype::instance_parameterized_type(ctx, params, member); + let mut state = ctype::UnifyState::default(); + for (param, arg) in fresh_params.iter().zip(args) { + if ctype::unify(ctx, &mut state, *param, *arg).is_err() { + return member; + } + } + fresh_member +} + +fn field( + ctx: &TypeContext, + table: &mut TypeTable, + params: &[TypeExprRef], + args: &[TypeExprRef], + label: &LabelDeclaration, +) -> Value { + let name = label.ld_id.name().to_string(); + let js_name = label.ld_runtime_name.clone().unwrap_or_else(|| name.clone()); + let ty = member_type(ctx, params, args, label.ld_type); + json!({ + "name": name, + "jsName": js_name, + "typ": type_ref(ctx, table, ty), + "optional": label.ld_optional, + "mutable_": label.ld_mutable == crate::types::asttypes::MutableFlag::Mutable, + "attrs": user_attributes(&label.ld_attributes), + }) +} + +fn tagged(tag: &str, fields: Value) -> Value { + let mut out = serde_json::Map::new(); + out.insert("TAG".into(), Value::String(tag.into())); + if let Value::Object(fields) = fields { + out.extend(fields); + } + Value::Object(out) +} + +fn unary(ctx: &TypeContext, table: &mut TypeTable, tag: &str, args: &[TypeExprRef]) -> Value { + match args.first() { + Some(arg) => tagged(tag, json!({ "_0": type_ref(ctx, table, *arg) })), + None => Value::String("Unknown".into()), + } +} + +/// `Macro.Type.info` of `ty`. +pub fn type_info(ctx: &TypeContext, env: &Env, table: &mut TypeTable, ty: TypeExprRef) -> Value { + type_info_at(ctx, env, table, ty, 0) +} + +fn type_info_at( + ctx: &TypeContext, + env: &Env, + table: &mut TypeTable, + ty: TypeExprRef, + depth: usize, +) -> Value { + let ty = ctx.repr(ctype::expand_head(ctx, env, ty)); + let desc = ctx.get_desc(ty); + match &*desc { + TypeDesc::Tconstr { path, args, .. } => { + let args: Vec = ctx.type_list(*args).iter().collect(); + constructor_info(ctx, env, table, path, &args, depth) + } + TypeDesc::Ttuple(elements) => { + let elements: Vec = ctx + .type_list(*elements) + .iter() + .map(|element| type_ref(ctx, table, element)) + .collect(); + tagged("Tuple", json!({ "_0": elements })) + } + TypeDesc::Tarrow { args, ret } => { + let params: Vec = ctx + .type_args(*args) + .iter() + .map(|arg| type_ref(ctx, table, arg.typ)) + .collect(); + tagged( + "Function", + json!({ "params": params, "result": type_ref(ctx, table, *ret) }), + ) + } + TypeDesc::Tpoly { body, .. } if depth < 8 => type_info_at(ctx, env, table, *body, depth + 1), + TypeDesc::Tvariant(row) => { + let row = ctx.row_desc(*row); + let constructors: Vec = row + .row_fields + .iter() + .filter_map(|(label, field)| { + let args = match field { + RowField::Rpresent(Some(arg)) => vec![type_ref(ctx, table, *arg)], + RowField::Rpresent(None) => vec![], + _ => return None, + }; + let name = label.to_string(); + Some(json!({ + "name": format!("#{name}"), + "jsName": name, + "args": args, + "fields": [], + "attrs": [], + })) + }) + .collect(); + tagged("PolyVariant", json!({ "constructors": constructors })) + } + _ => Value::String("Unknown".into()), + } +} + +fn constructor_info( + ctx: &TypeContext, + env: &Env, + table: &mut TypeTable, + path: &Path, + args: &[TypeExprRef], + _depth: usize, +) -> Value { + let simple = [ + (predef::path_int(), "Int"), + (predef::path_float(), "Float"), + (predef::path_string(), "String"), + (predef::path_bool(), "Bool"), + (predef::path_unit(), "Unit"), + (predef::path_bigint(), "BigInt"), + (predef::path_char(), "Char"), + ]; + for (predefined, name) in &simple { + if path.same(predefined) { + return Value::String((*name).into()); + } + } + let containers = [ + (predef::path_option(), "Option"), + (predef::path_array(), "Array"), + (predef::path_list(), "List"), + (predef::path_dict(), "Dict"), + (predef::path_promise(), "Promise"), + ]; + for (predefined, name) in &containers { + if path.same(predefined) { + return unary(ctx, table, name, args); + } + } + if path.same(&predef::path_result()) && args.len() == 2 { + return tagged( + "Result", + json!({ "_0": type_ref(ctx, table, args[0]), "_1": type_ref(ctx, table, args[1]) }), + ); + } + + let name = path.name(); + let Some(decl) = crate::types::typemod::find_type_decl_for_path(env, ctx, path) else { + return tagged("Abstract", json!({ "name": name })); + }; + let params = &decl.type_params; + match &decl.type_kind { + TypeKind::TypeRecord(labels, _) => { + let fields: Vec = labels + .iter() + .map(|label| field(ctx, table, params, args, label)) + .collect(); + tagged( + "Record", + json!({ "name": name, "fields": fields, "attrs": user_attributes(&decl.type_attributes) }), + ) + } + TypeKind::TypeVariant(constructors, _) => { + let constructors: Vec = constructors + .iter() + .map(|constructor| { + let name = constructor.cd_id.name().to_string(); + let js_name = constructor + .cd_runtime_tag + .as_ref() + .map(tag_text) + .unwrap_or_else(|| name.clone()); + let (constructor_args, fields) = match &constructor.cd_args { + ConstructorArguments::CstrTuple(types) => ( + types + .iter() + .map(|ty| { + type_ref(ctx, table, member_type(ctx, params, args, *ty)) + }) + .collect::>(), + Vec::new(), + ), + ConstructorArguments::CstrRecord(labels) => ( + Vec::new(), + labels + .iter() + .map(|label| field(ctx, table, params, args, label)) + .collect::>(), + ), + }; + json!({ + "name": name, + "jsName": js_name, + "args": constructor_args, + "fields": fields, + "attrs": user_attributes(&constructor.cd_attributes), + }) + }) + .collect(); + tagged( + "Variant", + json!({ "name": name, "constructors": constructors, "attrs": user_attributes(&decl.type_attributes) }), + ) + } + _ => tagged("Abstract", json!({ "name": name })), + } +} + +/// The shape `%comptime` needs to write a value of type `ty` as a literal +/// (read by `reify` in host.js). +pub fn value_shape(ctx: &TypeContext, env: &Env, ty: TypeExprRef, depth: usize) -> Value { + let unsupported = |ctx: &TypeContext, ty| json!({ "k": "other", "name": print_type(ctx, ty) }); + if depth > 32 { + return unsupported(ctx, ty); + } + let expanded = ctx.repr(ctype::expand_head(ctx, env, ty)); + let desc = ctx.get_desc(expanded); + match &*desc { + TypeDesc::Tconstr { path, args, .. } => { + let args: Vec = ctx.type_list(*args).iter().collect(); + let simple = [ + (predef::path_int(), "int"), + (predef::path_float(), "float"), + (predef::path_string(), "string"), + (predef::path_bool(), "bool"), + (predef::path_unit(), "unit"), + ]; + for (predefined, kind) in &simple { + if path.same(predefined) { + return json!({ "k": kind }); + } + } + let containers = [ + (predef::path_array(), "array"), + (predef::path_option(), "option"), + (predef::path_dict(), "dict"), + ]; + for (predefined, kind) in &containers { + if path.same(predefined) && args.len() == 1 { + return json!({ "k": kind, "of": value_shape(ctx, env, args[0], depth + 1) }); + } + } + let Some(decl) = crate::types::typemod::find_type_decl_for_path(env, ctx, path) else { + return unsupported(ctx, ty); + }; + match &decl.type_kind { + TypeKind::TypeRecord(labels, _) => { + let fields: Vec = labels + .iter() + .map(|label| { + let name = label.ld_id.name().to_string(); + let field_type = member_type(ctx, &decl.type_params, &args, label.ld_type); + // An optional field holds the value itself, not an option. + let shape = value_shape(ctx, env, field_type, depth + 1); + let shape = match (&shape, label.ld_optional) { + (Value::Object(object), true) if object.get("k") == Some(&json!("option")) => { + object.get("of").cloned().unwrap_or(shape.clone()) + } + _ => shape, + }; + json!({ + "name": name, + "js": label.ld_runtime_name.clone().unwrap_or(name.clone()), + "optional": label.ld_optional, + "of": shape, + }) + }) + .collect(); + json!({ "k": "record", "fields": fields }) + } + _ => unsupported(ctx, ty), + } + } + TypeDesc::Ttuple(elements) => { + let of: Vec = ctx + .type_list(*elements) + .iter() + .map(|element| value_shape(ctx, env, element, depth + 1)) + .collect(); + json!({ "k": "tuple", "of": of }) + } + _ => unsupported(ctx, ty), + } +} diff --git a/compiler-rust/src/parse_arena.rs b/compiler-rust/src/parse_arena.rs index 51c3515023..06fb550c0f 100644 --- a/compiler-rust/src/parse_arena.rs +++ b/compiler-rust/src/parse_arena.rs @@ -2700,6 +2700,15 @@ impl ParseArena { self.apply_args.get(args) } + /// Rewrite every position recorded so far. Macro expansion parses the + /// expanded text and then moves each position to where it is in the + /// source as written. + pub fn remap_positions(&mut self, mut remap: impl FnMut(&mut Position)) { + for position in self.positions.iter_mut() { + remap(position); + } + } + pub fn get_expr(&self, idx: ExprIdx) -> &Expression { let raw = idx.0; if raw < SHARED_EXPRESSION_BASE { diff --git a/compiler-rust/src/parser/scanner.rs b/compiler-rust/src/parser/scanner.rs index 68402aaa51..5986a9d5f4 100644 --- a/compiler-rust/src/parser/scanner.rs +++ b/compiler-rust/src/parser/scanner.rs @@ -46,7 +46,8 @@ pub struct ScannerSnapshot { #[derive(Debug)] pub struct Scanner<'src> { /// Macro-expanded source: identifiers may contain `$`, which source - /// written by hand cannot, so generated names never collide with it. + /// written by hand cannot, so generated names never collide with it, + /// and `Position::cnum` is the character offset. pub generated_names: bool, /// Source filename (interned string index for sharing in marshal output). pub filename: StrIdx, @@ -195,7 +196,12 @@ impl<'src> Scanner<'src> { self.filename, self.lnum, self.line_offset as i32, - (self.line_offset + self.offset16) as i32, // UTF-16 code unit position + if self.generated_names { + // Macro expansion edits the text by character offset. + self.char_pos as i32 + } else { + (self.line_offset + self.offset16) as i32 // UTF-16 code unit position + }, ) } diff --git a/compiler-rust/src/parser/state.rs b/compiler-rust/src/parser/state.rs index ee74dd7965..3a2863c900 100644 --- a/compiler-rust/src/parser/state.rs +++ b/compiler-rust/src/parser/state.rs @@ -149,6 +149,20 @@ impl<'src> Parser<'src> { filename: impl Into, src: &'src str, store_locations: bool, + ) -> Self { + Self::with_scanner_options(filename, src, store_locations, false) + } + + /// Parse macro-expanded source, in which identifiers may contain `$`. + pub fn for_expanded_source(filename: impl Into, src: &'src str) -> Self { + Self::with_scanner_options(filename, src, true, true) + } + + fn with_scanner_options( + filename: impl Into, + src: &'src str, + store_locations: bool, + generated_names: bool, ) -> Self { // Create arena first so we can intern the filename let mut arena = ParseArena::with_locations(store_locations); @@ -156,7 +170,8 @@ impl<'src> Parser<'src> { // Intern the filename - this StrIdx will be shared by all positions in this file let filename_idx = arena.intern_string(&filename.into()); arena.set_source_file(filename_idx); - let scanner = Scanner::new(filename_idx, src); + let mut scanner = Scanner::new(filename_idx, src); + scanner.generated_names = generated_names; // Push initial default positions to arena let default_pos = Position::default(); let default_pos_idx = arena.push_position(default_pos); @@ -191,12 +206,6 @@ impl<'src> Parser<'src> { parser } - /// Accept `$` inside identifiers, as macro-expanded source uses for - /// generated names. Call before the first token is consumed. - pub fn set_generated_names(&mut self, enabled: bool) { - self.scanner.generated_names = enabled; - } - /// Create a location for the current token (start_pos to end_pos). /// Uses the stored start_pos_idx and end_pos_idx directly. pub fn mk_loc_current(&mut self) -> LocIdx { diff --git a/compiler-rust/src/types/typecore.rs b/compiler-rust/src/types/typecore.rs index a234ac96b3..db9b341f02 100644 --- a/compiler-rust/src/types/typecore.rs +++ b/compiler-rust/src/types/typecore.rs @@ -1313,6 +1313,11 @@ pub struct TypeCheckContext<'a> { pub active_recursive_value_ids: Vec, /// Mirrors OCaml's Experimental_features.LetUnwrap during type checking. pub experimental_let_unwrap: bool, + /// Whether this is a macro discovery pass (`macros::expand`). + pub macro_mode: crate::macros::discover::MacroMode, + /// Set when an ordinary compilation stopped at a macro use: the file + /// has to be expanded first. + pub macro_expansion_required: bool, /// OCaml's `?deprecated_context:FunctionCall` argument (typecore.ml:2594, /// 2632): set right before typing the function of an application or the /// tag of a tagged template, and taken by the next expression typed. @@ -1462,6 +1467,8 @@ impl<'a> TypeCheckContext<'a> { active_recursive_value_ids: Vec::new(), persistent_env: None, experimental_let_unwrap: false, + macro_mode: crate::macros::discover::MacroMode::Off, + macro_expansion_required: false, deprecated_function_call: false, transparent_modules: false, module_expr_semantic_types: HashMap::new(), @@ -3888,7 +3895,12 @@ fn transl_type_inner( Ok((ctyp, package_ty)) } - CTD::Ptyp_extension(extension) => Err(builtin_extension_error(tctx.arena, extension)), + CTD::Ptyp_extension(extension) => { + if let Some(error) = crate::macros::discover::type_extension(tctx, env, loc, extension) { + return Err(error); + } + Err(builtin_extension_error(tctx.arena, extension)) + } } } @@ -7907,7 +7919,11 @@ fn type_expect_with_recarg_unscoped<'a>( } check_inlined_record_escape(ctx, loc, desc.val_type, recarg)?; - let ty = crate::types::instance(ctx, desc.val_type); + // A `@generic` of another file is called at its erased type. + let ty = match crate::macros::discover::generic_use(tctx, env, loc, &path, &desc)? { + Some(erased) => erased, + None => crate::types::instance(ctx, desc.val_type), + }; rue_unify(tctx, loc, ty, expected_ty, context)?; Ok({ @@ -8407,6 +8423,7 @@ fn type_expect_with_recarg_unscoped<'a>( let args = tctx.arena.apply_args(inner.args); // Function application let funct_expr = tctx.arena.get_expr(*funct); + crate::macros::discover::note_application(tctx, loc, funct_expr, args); let typed_apply = type_application( tctx, @@ -8791,6 +8808,15 @@ fn type_expect_with_recarg_unscoped<'a>( } ED::Pexp_extension(extension) => { + if let Some(result) = crate::macros::discover::expression_extension( + tctx, + env, + loc, + extension, + expected_ty, + ) { + return result; + } // Extension: [%id] type_extension_expr( tctx, diff --git a/compiler-rust/src/types/typemod.rs b/compiler-rust/src/types/typemod.rs index e421faaf5c..adf862ea82 100644 --- a/compiler-rust/src/types/typemod.rs +++ b/compiler-rust/src/types/typemod.rs @@ -15732,7 +15732,8 @@ fn type_module_expr_with_alias_inner<'a>( } ParsedModuleExprDesc::Pmod_extension(ext) => Err(TypeModError::CoreError( - crate::types::typecore::builtin_extension_error(arena, ext), + crate::macros::discover::declarations_extension(tctx, env, mod_expr.pmod_loc, ext, true) + .unwrap_or_else(|| crate::types::typecore::builtin_extension_error(arena, ext)), )), } } @@ -16652,7 +16653,16 @@ fn type_structure_unscoped<'a>( ctx.init_def(ctx.current_stamp()); tctx.set_unify_env(¤t_env); let warnings_before_item = tctx.warnings.len(); - let (typed_item, item_sig, new_env) = type_structure_item(tctx, ¤t_env, arena, item)?; + // In a macro discovery pass an item that fails does not end the + // pass: later items are still searched for macros. + crate::macros::discover::begin_item(tctx, item); + let typed = type_structure_item_with_macros(tctx, ¤t_env, arena, item); + crate::macros::discover::end_item(tctx, typed.is_ok()); + let (typed_item, item_sig, new_env) = match typed { + Ok(typed) => typed, + Err(_) if crate::macros::discover::skips_failed_item(tctx) => continue, + Err(error) => return Err(error), + }; if let StructureItemDesc::Tstr_include(incl) = &typed_item.str_desc { // OCaml compiler/ml/typemod.ml:1579. check_included_signature_names(&mut names, item.pstr_loc, &incl.incl_type)?; @@ -16770,6 +16780,66 @@ pub fn check_nongen_schemes( Ok(()) } +/// Type check a structure item, with the macros attached to it. +fn type_structure_item_with_macros<'a>( + tctx: &mut TypeCheckContext<'a>, + env: &Env, + arena: &'a ParseArena, + item: &ParsedStructureItem, +) -> TypeModResult<(StructureItem, Vec, Env)> { + if let Some(error) = crate::macros::discover::value_item(tctx, env, item) { + return Err(TypeModError::CoreError(error)); + } + if let Some(error) = crate::macros::discover::type_item_requires_expansion(tctx, item) { + return Err(TypeModError::CoreError(error)); + } + let mut typed = type_structure_item(tctx, env, arena, item)?; + crate::macros::discover::type_item(tctx, &typed.2, item); + mark_macro_values(tctx, arena, item, &mut typed.1, &mut typed.2); + Ok(typed) +} + +/// `@macro let f = ...` and `@generic let f = ...`: keep the mark on the +/// value's description, where the files that use `f` look for it. A `let` +/// keeps no other attribute there. +fn mark_macro_values<'a>( + tctx: &mut TypeCheckContext<'a>, + arena: &'a ParseArena, + item: &ParsedStructureItem, + signature: &mut [crate::types::decl::SignatureItem], + env: &mut Env, +) { + let ParsedStructureItemDesc::Pstr_value((_, bindings)) = &item.pstr_desc else { + return; + }; + for binding in arena.vb_list(*bindings) { + let Some(mark) = binding + .pvb_attributes + .iter() + .find(|attr| matches!(arena.get_string(attr.0.txt), "macro" | "generic")) + else { + continue; + }; + let mut pattern = arena.get_pat(binding.pvb_pat); + while let crate::parser::ast::PatternDesc::Ppat_constraint(inner) = &pattern.ppat_desc { + pattern = arena.get_pat(inner.0); + } + let crate::parser::ast::PatternDesc::Ppat_var(name) = &pattern.ppat_desc else { + continue; + }; + let name = arena.get_string(name.txt); + let attribute = parser_attr_to_decl_attr(arena, tctx.type_ctx, mark); + for sig_item in signature.iter_mut() { + if let crate::types::decl::SignatureItem::SigValue(id, desc) = sig_item + && id.name() == name + { + desc.val_attributes = vec![attribute.clone()].into(); + env.add_value(*id, desc.clone()); + } + } + } +} + /// Type check a structure item. fn type_structure_item<'a>( tctx: &mut TypeCheckContext<'a>, @@ -20193,7 +20263,8 @@ fn type_structure_item<'a>( ParsedStructureItemDesc::Pstr_extension(inner) => { let (extension, _attrs) = &**inner; Err(TypeModError::CoreError( - crate::types::typecore::builtin_extension_error(arena, extension), + crate::macros::discover::declarations_extension(tctx, env, loc, extension, false) + .unwrap_or_else(|| crate::types::typecore::builtin_extension_error(arena, extension)), )) } } diff --git a/compiler-rust/tests/macros.rs b/compiler-rust/tests/macros.rs index a498676a5c..0c11d9e6f0 100644 --- a/compiler-rust/tests/macros.rs +++ b/compiler-rust/tests/macros.rs @@ -1,17 +1,27 @@ //! End-to-end tests of compile-time macros: each test compiles a small //! project in memory, with the standard library type-checked from source. +use std::collections::HashMap; use std::path::PathBuf; +use std::sync::{Arc, Mutex}; use rescript_compiler::cmi::persistent_env::ModuleRegistry; use rescript_compiler::driver::{self, CompilerOptions}; +use rescript_compiler::macros::MacroHost; +use rescript_compiler::macros::quickjs::QuickJsHost; fn runtime_dir() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../packages/@rescript/runtime") } + struct Project { registry: ModuleRegistry, + /// Compiled JavaScript of the project's modules, for the macro engine. + javascript: Arc>>, + host: Arc, + /// The expanded source of the last compiled file, when it uses macros. + expanded: Option, } impl Project { @@ -32,14 +42,33 @@ impl Project { } } registry.set_source_fallback_paths(modules); - Project { registry } + let javascript: Arc>> = Default::default(); + let sources = javascript.clone(); + let host = Arc::new(QuickJsHost::new(Arc::new(move |name: &str| { + if let Some(source) = sources.lock().unwrap().get(name) { + return Some(source.clone()); + } + std::fs::read_to_string(runtime_dir().join(format!("lib/js/{name}.cjs"))).ok() + }))); + let mut project = Project { + registry, + javascript, + host, + expanded: None, + }; + // The macro API, compiled from source like the rest of the project. + let macro_source = std::fs::read_to_string(runtime_dir().join("Macro.res")).unwrap(); + project.compile("Macro.res", ¯o_source).unwrap(); + project } fn compile(&mut self, filename: &str, source: &str) -> Result { let module_name = driver::module_name_from_source_filename(filename); + let host: Arc = self.host.clone(); let options = CompilerOptions { source_filename: Some(filename.to_string()), module_name: Some(module_name.clone()), + macro_host: Some(host), ..Default::default() }; match driver::compile_source_in_process( @@ -63,6 +92,12 @@ impl Project { ), ); } + self.javascript + .lock() + .unwrap() + .insert(module_name, compiled.js_output.clone()); + self.host.invalidate(); + self.expanded = compiled.expanded_source; Ok(compiled.js_output) } Err(e) => Err(format!("{e:#}")), @@ -76,6 +111,30 @@ fn plain_module_compiles() { let js = project .compile("Plain.res", "let double = x => x * 2\nlet xs = [1, 2]->Array.map(double)\n") .unwrap(); - println!("{js}"); assert!(js.contains("double")); + assert!(project.expanded.is_none()); +} + +const DEBUG: &str = r#" +open Macro + +@macro +let dbg = (e: code<'a>): code<'a> => + %code({ + let v = ${e} + Console.log2(${Code.string(Code.print(e) ++ " =")}, v) + v + }) +"#; + +#[test] +fn expression_macro() { + let mut project = Project::new(); + project.compile("Debug.res", DEBUG).unwrap(); + println!("--- Debug.res expanded\n{}", project.expanded.clone().unwrap_or_default()); + let js = project + .compile("Main.res", "let age = 41\nlet next = %Debug.dbg(age + 1)\n") + .unwrap(); + println!("--- Main.res expanded\n{}\n--- js\n{js}", project.expanded.clone().unwrap_or_default()); + assert!(js.contains("\"age + 1 =\""), "{js}"); } diff --git a/packages/@rescript/runtime/Macro.res b/packages/@rescript/runtime/Macro.res new file mode 100644 index 0000000000..eff9158d86 --- /dev/null +++ b/packages/@rescript/runtime/Macro.res @@ -0,0 +1,348 @@ +/*** +Compile-time macros. + +A macro is a ReScript function the compiler runs while it compiles another +file. It returns code, written as a quote: `%code(...)` for an expression or +declarations, `%type(...)` for a type and `%pat(...)` for a pattern. Inside a +quote, `${...}` is a hole that takes a value of type `code`, `typ` or `pat`. + +See `docs/comptime/README.md` for the design. +*/ + +open Stdlib + +/** A piece of ReScript code that evaluates to a value of type `'a`. */ +type code<'a> + +/** A type. */ +type typ + +/** A pattern. */ +type pat + +type declarations + +/** Declarations: the result of a macro that adds `let`s, types or modules. */ +type decls = code + +/* The representation the compiler and the engine share: the source text, + and for a type the compiler's handle of it. */ +type rec node = {c: string, id?: int, t?: node, raw?: bool} + +external toNode: 'a => node = "%identity" +external ofNode: node => 'a = "%identity" + +let make = (source: string): 'a => ofNode({c: source}) +let source = (value: 'a): string => toNode(value).c + +type host +@val external host: host = "__rescript_macro" +@send external ask: (host, string) => 'a = "ask" +@send external fail: (host, string, option) => 'a = "fail" +@send external expectedType: host => Nullable.t = "expected" + +/** Stop compilation with `message`, reported at the macro call. */ +let error = (message: string): 'a => host->fail(message, None) + +/** Like `error`, for a mistake at `offset` characters into a string argument. */ +let errorAt = (~offset: int, message: string): 'a => host->fail(message, Some(offset)) + +/** The type of an argument of a `@generic` macro. */ +let typeOf = (value: code<'a>): typ => + switch toNode(value).t { + | Some(t) => ofNode(t) + | None => error("typeOf: the type of this code is not known. Only the arguments of a macro carry a type.") + } + +/** The type the call site of a `@generic` macro expects as result. */ +let expected = (): typ => + switch host->expectedType->Nullable.toOption { + | Some(t) => t + | None => error("expected: only a @generic macro knows the type its call site expects.") + } + +/** The text of a file. The build tracks it as an input of the macro. */ +let readFile = (path: string): string => host->ask("readFile:" ++ path) + +/** An environment variable of the build. */ +let env = (name: string): option => Nullable.toOption(host->ask("env:" ++ name)) + +/* Quotes. The compiler rewrites `%code(a + ${b})` to a call of `__quoteCode` + with the text around the holes and the hole values. */ +type hole + +external __holeCode: code<'a> => hole = "%identity" +external __holeType: typ => hole = "%identity" +external __holePat: pat => hole = "%identity" +let __holeItem = (value: code<'a>): hole => ofNode({c: source(value), raw: true}) + +let quote = (pieces: array, holes: array): node => { + let text = ref(pieces->Array.getUnsafe(0)) + holes->Array.forEachWithIndex((hole, index) => { + let hole = toNode(hole) + let filled = hole.raw == Some(true) ? hole.c : "(" ++ hole.c ++ ")" + text := text.contents ++ filled ++ pieces->Array.getUnsafe(index + 1) + }) + {c: text.contents} +} + +let __quoteCode = (pieces, holes): code<'a> => ofNode(quote(pieces, holes)) +let __quoteDecls = (pieces, holes): decls => ofNode(quote(pieces, holes)) +let __quoteType = (pieces, holes): typ => ofNode(quote(pieces, holes)) +let __quotePat = (pieces, holes): pat => ofNode(quote(pieces, holes)) + +let isSimple: string => bool = %raw(`function (text) { + return /^[A-Za-z_][A-Za-z0-9_$.]*$/.test(text) +}`) +let atom = (text: string) => isSimple(text) ? text : "(" ++ text ++ ")" + +module Attr = { + /** An attribute: `@Json.key("user_age")` has the name `Json.key` and the payload `user_age`. */ + type t = { + name: string, + /** The payload, when it is one string literal. */ + payload: option, + } + + let find = (attrs: array, name: string): option => attrs->Array.find(attr => attr.name == name) + let has = (attrs: array, name: string): bool => find(attrs, name) != None + let string = (attrs: array, name: string): option => + switch find(attrs, name) { + | Some({payload}) => payload + | None => None + } +} + +module Type = { + type field = { + name: string, + /** The name at run time: the `@as` name when there is one. */ + jsName: string, + typ: typ, + optional: bool, + mutable_: bool, + attrs: array, + } + + type constructor = { + name: string, + /** The value or tag at run time: the `@as` value when there is one. */ + jsName: string, + args: array, + /** The fields of an inline record argument, `Circle({radius: float})`. */ + fields: array, + attrs: array, + } + + /** What the type checker knows about a type, one level deep. */ + type info = + | Int + | Float + | String + | Bool + | Unit + | BigInt + | Char + | Option(typ) + | Array(typ) + | List(typ) + | Dict(typ) + | Promise(typ) + | Result(typ, typ) + | Tuple(array) + | Record({name: string, fields: array, attrs: array}) + | Variant({name: string, constructors: array, attrs: array}) + | PolyVariant({constructors: array}) + | Function({params: array, result: typ}) + /** A type whose definition is hidden by an interface, or an external type. */ + | Abstract({name: string}) + /** A type that inference has not settled. */ + | Unknown + + /** A type declaration, as a macro on a type receives it. */ + type decl = { + name: string, + typ: typ, + attrs: array, + } + + let handle = (t: typ, what: string): int => + switch toNode(t).id { + | Some(id) => id + | None => error(what ++ ": this type was built by a macro, so the compiler has no information on it.") + } + + let info = (t: typ): info => host->ask("info:" ++ Int.toString(handle(t, "Type.info"))) + + /** The type as source text, such as `array`. */ + let name = (t: typ): string => source(t) + + /** The value `name` of the module that defines the type: `Date.toJson` for `Date.t`. */ + let companion = (t: typ, name: string): option> => + Nullable.toOption(host->ask("companion:" ++ Int.toString(handle(t, "Type.companion")) ++ ":" ++ name)) + + let attrText = (attrs: array): string => + attrs + ->Array.map(attr => + switch attr.payload { + | Some(payload) => "@" ++ attr.name ++ "(" ++ JSON.stringify(JSON.Encode.string(payload)) ++ ") " + | None => "@" ++ attr.name ++ " " + } + ) + ->Array.join("") + + let fieldText = (field: field): string => + attrText(field.attrs) ++ + (field.jsName != field.name ? "@as(" ++ JSON.stringify(JSON.Encode.string(field.jsName)) ++ ") " : "") ++ + (field.mutable_ ? "mutable " : "") ++ + field.name ++ + (field.optional ? "?: " : ": ") ++ + source(field.typ) + + /** A record type with these fields. */ + let record = (fields: array): typ => make("{" ++ fields->Array.map(fieldText)->Array.join(", ") ++ "}") + + /** A variant type with these constructors. Use it as the body of a type declaration. */ + let variant = (constructors: array): typ => + make( + constructors + ->Array.map(c => + "| " ++ + attrText(c.attrs) ++ + (c.jsName != c.name ? "@as(" ++ JSON.stringify(JSON.Encode.string(c.jsName)) ++ ") " : "") ++ + c.name ++ ( + c.fields->Array.length > 0 + ? "({" ++ c.fields->Array.map(fieldText)->Array.join(", ") ++ "})" + : c.args->Array.length > 0 + ? "(" ++ c.args->Array.map(source)->Array.join(", ") ++ ")" + : "" + ) + ) + ->Array.join(" "), + ) + + /** A field for `record`. */ + let field = (name: string, typ: typ): field => { + name, + jsName: name, + typ, + optional: false, + mutable_: false, + attrs: [], + } + + /** A constructor without arguments for `variant`. */ + let constructor = (name: string): constructor => { + name, + jsName: name, + args: [], + fields: [], + attrs: [], + } +} + +module Code = { + /** A string literal. */ + let string = (value: string): code => make(JSON.stringify(JSON.Encode.string(value))) + let int = (value: int): code => make(Int.toString(value)) + let float = (value: float): code => { + let text = Float.toString(value) + make(text->String.includes(".") || text->String.includes("e") ? text : text ++ ".") + } + let bool = (value: bool): code => make(value ? "true" : "false") + let unit: code = make("()") + + /** The source text of a piece of code. */ + let print = (value: code<'a>): string => source(value) + + /** Code from source text. Nothing checks it until the macro's result is compiled. */ + let raw = (text: string): code<'a> => make(text) + + /** A name that is resolved where the macro is used, not where it is defined. */ + let ident = (name: string): code<'a> => make(name) + + /** `value.name` */ + let field = (value: code<'a>, name: string): code<'b> => make(atom(source(value)) ++ "." ++ name) + + /** `[a, b, c]` */ + let array = (items: array>): code> => + make("[" ++ items->Array.map(source)->Array.join(", ") ++ "]") + + /** `(a, b, c)` */ + let tuple = (items: array>): code<'b> => make("(" ++ items->Array.map(source)->Array.join(", ") ++ ")") + + /** `{name: value, ...}` */ + let record = (fields: array<(string, code<'a>)>): code<'b> => + make("{" ++ fields->Array.map(((name, value)) => name ++ ": " ++ source(value))->Array.join(", ") ++ "}") + + /** `f(a, b)` */ + let call = (f: code<'a>, args: array>): code<'c> => + make(atom(source(f)) ++ "(" ++ args->Array.map(source)->Array.join(", ") ++ ")") + + /** `switch value { | pattern => body ... }` */ + let switch_ = (value: code<'a>, arms: array<(pat, code<'b>)>): code<'b> => + make( + "switch " ++ + atom(source(value)) ++ + " {\n" ++ + arms->Array.map(((pattern, body)) => "| " ++ source(pattern) ++ " => " ++ source(body))->Array.join("\n") ++ "\n}", + ) + + /** A parameter of `fn`. */ + type param = string + + /** `name: typ` */ + let param = (name: string, typ: typ): param => name ++ ": " ++ source(typ) + + /** `~name: typ` */ + let labelled = (name: string, typ: typ): param => "~" ++ name ++ ": " ++ source(typ) + + /** `(params) => body` */ + let fn = (params: array, body: code<'a>): code<'f> => + make("(" ++ params->Array.join(", ") ++ ") => " ++ source(body)) + + /** Several declarations, one after the other. */ + let decls = (items: array): decls => make(items->Array.map(source)->Array.join("\n")) +} + +module Pat = { + /** A variable pattern. */ + let var = (name: string): pat => make(name) + + /** `_` */ + let any: pat = make("_") + + /** + The pattern that matches a constructor and binds its arguments, with the + code of each bound argument: `Circle(a0, a1)` and `[a0, a1]`. + */ + let constructor = (c: Type.constructor): (pat, array>) => { + let typed = (name: string, typ: typ): code<'a> => ofNode({c: name, t: toNode(typ)}) + if c.fields->Array.length > 0 { + let names = c.fields->Array.mapWithIndex((f, i) => f.name ++ "$" ++ Int.toString(i)) + ( + make( + c.name ++ + "({" ++ + c.fields->Array.mapWithIndex((f, i) => f.name ++ ": " ++ names->Array.getUnsafe(i))->Array.join(", ") ++ "})", + ), + c.fields->Array.mapWithIndex((f, i) => typed(names->Array.getUnsafe(i), f.typ)), + ) + } else if c.args->Array.length > 0 { + let names = c.args->Array.mapWithIndex((_, i) => "arg$" ++ Int.toString(i)) + (make(c.name ++ "(" ++ names->Array.join(", ") ++ ")"), c.args->Array.mapWithIndex((typ, i) => typed(names->Array.getUnsafe(i), typ))) + } else { + (make(c.name), []) + } + } +} + +module Decl = { + /** A `let` binding, as a macro on a `let` receives it: before it is type checked. */ + type value = { + /** The bound name, or `""` when the binding is a pattern. */ + name: string, + pat: pat, + expr: code, + } +} From 2d224414b15dcdb441b182eac746146af2129f05 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:32:54 +0100 Subject: [PATCH 03/38] macros: @generic, called like a function with one instance per type A @generic of another file is typed at its erased type (code<'a> => code as 'a => JSON.t) and noted. When the top-level item it is in is fully inferred, the macro runs with the final types and its result becomes a function in a let rec group before the item; the call is pointed at it. Instance names contain a $, which hand-written source cannot, and their group is left out of the module's signature. Co-authored-by: Jaap Frolich Session: https://jakes-mac-mini.tail23a77e.ts.net:8443/session/os-01a1ca09-2757-709a-bbb1-e57ccc4d104f Signed-off-by: Jaap Frolich --- compiler-rust/src/cmi/persistent_env.rs | 19 +++++- compiler-rust/src/macros/discover.rs | 28 ++++---- compiler-rust/src/parser/core.rs | 3 +- compiler-rust/src/types/typemod.rs | 4 +- compiler-rust/tests/macros.rs | 86 ++++++++++++++++++++++++- 5 files changed, 122 insertions(+), 18 deletions(-) diff --git a/compiler-rust/src/cmi/persistent_env.rs b/compiler-rust/src/cmi/persistent_env.rs index 98a71b768d..12737fbefc 100644 --- a/compiler-rust/src/cmi/persistent_env.rs +++ b/compiler-rust/src/cmi/persistent_env.rs @@ -589,6 +589,9 @@ pub struct ModuleRegistry { /// as an implicit dependency (e.g., via `-open Pervasives`) but hasn't /// been compiled yet in the current wave. source_fallback_paths: SharedRegistryMap, + /// The source-fallback modules are the modules of `@rescript/runtime` + /// (the playground and tests, which have the runtime as source only). + source_fallback_is_runtime: bool, /// Package roots of registered modules that carry no `InMemoryModuleInfo` /// (namespace units), for load-path visibility. module_package_roots: SharedRegistryMap, @@ -1042,6 +1045,13 @@ impl ModuleRegistry { } } + /// Declare the source-fallback modules to be the modules of + /// `@rescript/runtime`: the playground and tests have the runtime as + /// source only, type check it on demand and import it from the package. + pub fn set_source_fallback_is_runtime(&mut self, is_runtime: bool) { + self.source_fallback_is_runtime = is_runtime; + } + pub fn insert_source_fallback_path(&mut self, name: String, path: PathBuf) { if self.write_to_local { self.local_source_fallback_paths.insert(name, path); @@ -1137,6 +1147,8 @@ pub struct PersistentEnv { /// has its source path, the module is type-checked from source on the fly. /// Shared through the build registry so worker snapshots do not clone it. source_fallback_paths: SharedRegistryMap, + /// See `ModuleRegistry::source_fallback_is_runtime`. + source_fallback_is_runtime: bool, /// Current depth of source-fallback recursion. Each `typecheck_source_signature` /// call increments this. Used to prevent stack overflow from deep dependency chains. source_fallback_depth: usize, @@ -1255,6 +1267,7 @@ impl PersistentEnv { in_process_mode: false, disk_modules: SharedRegistryMap::default(), source_fallback_paths: SharedRegistryMap::default(), + source_fallback_is_runtime: false, source_fallback_depth: 0, portable_cache: SharedRegistryMap::default(), module_package_roots: SharedRegistryMap::default(), @@ -1289,6 +1302,7 @@ impl PersistentEnv { in_process_mode: true, disk_modules: registry.disk_modules.clone(), source_fallback_paths: registry.source_fallback_paths.clone(), + source_fallback_is_runtime: registry.source_fallback_is_runtime, source_fallback_depth: 0, portable_cache: registry.cached_modules.clone(), module_package_roots: registry.module_package_roots.clone(), @@ -2304,6 +2318,7 @@ impl PersistentEnv { in_process_mode: self.in_process_mode, disk_modules: self.disk_modules.clone(), source_fallback_paths: self.source_fallback_paths.clone(), + source_fallback_is_runtime: self.source_fallback_is_runtime, source_fallback_depth: self.source_fallback_depth + 1, portable_cache: self.portable_cache.clone(), module_package_roots: self.module_package_roots.clone(), @@ -2989,7 +3004,9 @@ impl PersistentEnv { pub fn module_is_runtime(&self, name: &str) -> bool { self.in_memory_info_with(name, |info| info.is_runtime) - .unwrap_or(false) + .unwrap_or_else(|| { + self.source_fallback_is_runtime && self.source_fallback_path_entry(name).is_some() + }) } } diff --git a/compiler-rust/src/macros/discover.rs b/compiler-rust/src/macros/discover.rs index 4e0c218ae7..560eebc784 100644 --- a/compiler-rust/src/macros/discover.rs +++ b/compiler-rust/src/macros/discover.rs @@ -336,10 +336,7 @@ impl Discovery { for (at, functions) in std::mem::take(&mut self.new_groups) { self.edits.push(Edit::insert( at, - format!( - "%%private(@warning(\"-39\") let rec {})\n", - functions.join("\nand ") - ), + format!("@warning(\"-39\") let rec {}\n", functions.join("\nand ")), )); } PassResult { @@ -362,13 +359,7 @@ impl Discovery { fn add_instance(&mut self, function: String) { let ordinal = self.text.origin(self.item_start); if let Some(end) = self.group_ends.get(&ordinal).copied() { - // `%%private(let rec a = ... )`: stay inside the parentheses. - let at = if end > 0 && self.text.slice(end - 1, end) == ")" { - end - 1 - } else { - end - }; - self.edits.push(Edit::insert(at, format!("\nand {function}"))); + self.edits.push(Edit::insert(end, format!("\nand {function}"))); return; } match self @@ -980,14 +971,23 @@ pub(crate) fn begin_item(tctx: &mut TypeCheckContext<'_>, item: &ParsedStructure discovery.item_start = start; discovery.item_pending = false; // An instance group that an earlier pass added. + if is_instance_group(arena, item) { + let ordinal = discovery.text.origin(start); + discovery.group_ends.insert(ordinal, end); + } +} + +/// Whether a structure item is a group of generated instances: a +/// `let rec` of names with a `$`, which only generated code can contain. +/// The group is not part of the module's signature. +pub(crate) fn is_instance_group(arena: &ParseArena, item: &ParsedStructureItem) -> bool { if let ParsedStructureItemDesc::Pstr_value((RecFlag::Recursive, bindings)) = &item.pstr_desc && let Some(first) = arena.vb_list(*bindings).first() && let PatternDesc::Ppat_var(name) = &arena.get_pat(first.pvb_pat).ppat_desc - && arena.get_string(name.txt).contains('$') { - let ordinal = discovery.text.origin(start); - discovery.group_ends.insert(ordinal, end); + return arena.get_string(name.txt).contains('$'); } + false } /// A top-level item was typed (`ok`) or failed. Resolves the generic uses diff --git a/compiler-rust/src/parser/core.rs b/compiler-rust/src/parser/core.rs index 08958c3e85..7a2ccc0e3e 100644 --- a/compiler-rust/src/parser/core.rs +++ b/compiler-rust/src/parser/core.rs @@ -665,7 +665,7 @@ pub enum ExprContext { pub fn get_closing_token(token: &Token<'_>) -> Token<'static> { match token { Token::Lparen => Token::Rparen, - Token::Lbrace => Token::Rbrace, + Token::Lbrace | Token::DollarLbrace => Token::Rbrace, Token::Lbracket => Token::Rbracket, Token::List => Token::Rbrace, Token::Dict => Token::Rbrace, @@ -703,6 +703,7 @@ pub fn go_to_closing(closing_token: &Token<'_>, p: &mut Parser<'_>) { Token::Lbracket | Token::Lparen | Token::Lbrace + | Token::DollarLbrace | Token::List | Token::Dict | Token::LessThan, diff --git a/compiler-rust/src/types/typemod.rs b/compiler-rust/src/types/typemod.rs index adf862ea82..7b9b3fb544 100644 --- a/compiler-rust/src/types/typemod.rs +++ b/compiler-rust/src/types/typemod.rs @@ -16667,7 +16667,9 @@ fn type_structure_unscoped<'a>( // OCaml compiler/ml/typemod.ml:1579. check_included_signature_names(&mut names, item.pstr_loc, &incl.incl_type)?; } - if !rescript_hide_structure_item(&typed_item.str_desc, arena) { + if !rescript_hide_structure_item(&typed_item.str_desc, arena) + && !crate::macros::discover::is_instance_group(arena, item) + { sig_items.extend(item_sig); } typed_items.push(typed_item); diff --git a/compiler-rust/tests/macros.rs b/compiler-rust/tests/macros.rs index 0c11d9e6f0..86c1d77447 100644 --- a/compiler-rust/tests/macros.rs +++ b/compiler-rust/tests/macros.rs @@ -42,6 +42,7 @@ impl Project { } } registry.set_source_fallback_paths(modules); + registry.set_source_fallback_is_runtime(true); let javascript: Arc>> = Default::default(); let sources = javascript.clone(); let host = Arc::new(QuickJsHost::new(Arc::new(move |name: &str| { @@ -88,7 +89,7 @@ impl Project { PathBuf::from(filename), false, Default::default(), - false, + module_name == "Macro", ), ); } @@ -138,3 +139,86 @@ fn expression_macro() { println!("--- Main.res expanded\n{}\n--- js\n{js}", project.expanded.clone().unwrap_or_default()); assert!(js.contains("\"age + 1 =\""), "{js}"); } + +const JSON: &str = r#" +open Macro + +@generic +let encode = (value: code<'a>): code => + switch Type.info(typeOf(value)) { + | String => %code(JSON.Encode.string(${value})) + | Int => %code(JSON.Encode.int(${value})) + | Float => %code(JSON.Encode.float(${value})) + | Bool => %code(JSON.Encode.bool(${value})) + | Option(_) => + %code( + switch ${value} { + | Some(v) => encode(v) + | None => JSON.Encode.null + } + ) + | Array(_) => %code(JSON.Encode.array(${value}->Array.map(v => encode(v)))) + | Record({fields}) => + let entries = fields->Array.map(f => { + let key = f.attrs->Attr.string("Json.key")->Option.getOr(f.jsName) + %code((${Code.string(key)}, encode(${value->Code.field(f.name)}))) + }) + %code(JSON.Encode.object(Dict.fromArray(${Code.array(entries)}))) + | Variant({constructors}) => + Code.switch_( + value, + constructors->Array.map(c => { + let (pattern, args) = Pat.constructor(c) + let encoded = args->Array.map(arg => %code(encode(${arg}))) + ( + pattern, + %code( + JSON.Encode.object( + Dict.fromArray([ + ("tag", JSON.Encode.string(${Code.string(c.name)})), + ("args", JSON.Encode.array(${Code.array(encoded)})), + ]), + ) + ), + ) + }), + ) + | Abstract({name}) => + switch Type.companion(typeOf(value), "toJson") { + | Some(toJson) => %code(${toJson}(${value})) + | None => error(`${name} is abstract and its module has no toJson`) + } + | _ => error(`unsupported type ${Type.name(typeOf(value))}`) + } + +@macro +let codec = (t: Type.decl): decls => + %code( + let ${Pat.var(t.name ++ "_encode")} = (value: ${t.typ}) => encode(value) + ) +"#; + +const USER: &str = r#" +type address = {street: string, city: string} + +type user = { + name: string, + @Json.key("user_age") age: int, + email: option, + address: address, + tags: array, +} + +let alice = {name: "Alice", age: 30, email: None, address: {street: "Main St", city: "Utrecht"}, tags: ["admin"]} +let json = Json.encode(alice) +"#; + +#[test] +fn generic_macro_makes_one_function_per_type() { + let mut project = Project::new(); + project.compile("Json.res", JSON).unwrap(); + let js = project.compile("User.res", USER).unwrap(); + println!("--- User.res expanded\n{}\n--- js\n{js}", project.expanded.clone().unwrap_or_default()); + assert!(js.contains("\"user_age\""), "{js}"); + assert!(js.contains("value.address") || js.contains("address"), "{js}"); +} From 09baa1bc9ba57902498e1d163465e0ca3b2d7287 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:37:44 +0100 Subject: [PATCH 04/38] macros: derive, type, module and item macros, %comptime - @M.f on a type runs the macro with the checked declaration and adds the declarations it returns after the type; on a let it replaces the binding. - %M.f(...) in a type position, as a structure item and as a module expression. A macro call takes several arguments. - %comptime(expr) evaluates now and writes the value back as a literal. - Generated instance groups carry @res.macroInstances and are neither in the module's signature nor exported. - The source-fallback modules can be declared to be the runtime package, for hosts that have the runtime as source only. Co-authored-by: Jaap Frolich Session: https://jakes-mac-mini.tail23a77e.ts.net:8443/session/os-01a1ca09-2757-709a-bbb1-e57ccc4d104f Signed-off-by: Jaap Frolich --- compiler-rust/src/macros/discover.rs | 28 +++- compiler-rust/src/parser/expr.rs | 4 +- compiler-rust/src/parser/module.rs | 67 +++++++- compiler-rust/src/raw_lambda/convert.rs | 15 +- compiler-rust/tests/macros.rs | 196 ++++++++++++++++++++++++ 5 files changed, 299 insertions(+), 11 deletions(-) diff --git a/compiler-rust/src/macros/discover.rs b/compiler-rust/src/macros/discover.rs index 560eebc784..ff42e37e7c 100644 --- a/compiler-rust/src/macros/discover.rs +++ b/compiler-rust/src/macros/discover.rs @@ -336,7 +336,10 @@ impl Discovery { for (at, functions) in std::mem::take(&mut self.new_groups) { self.edits.push(Edit::insert( at, - format!("@warning(\"-39\") let rec {}\n", functions.join("\nand ")), + format!( + "@{INSTANCES_ATTRIBUTE} @warning(\"-39\") let rec {}\n", + functions.join("\nand ") + ), )); } PassResult { @@ -977,15 +980,19 @@ pub(crate) fn begin_item(tctx: &mut TypeCheckContext<'_>, item: &ParsedStructure } } -/// Whether a structure item is a group of generated instances: a -/// `let rec` of names with a `$`, which only generated code can contain. -/// The group is not part of the module's signature. +/// The attribute on a group of generated instances. +pub const INSTANCES_ATTRIBUTE: &str = "res.macroInstances"; + +/// Whether a structure item is a group of generated instances. The group is +/// not part of the module's signature and is not exported. pub(crate) fn is_instance_group(arena: &ParseArena, item: &ParsedStructureItem) -> bool { if let ParsedStructureItemDesc::Pstr_value((RecFlag::Recursive, bindings)) = &item.pstr_desc && let Some(first) = arena.vb_list(*bindings).first() - && let PatternDesc::Ppat_var(name) = &arena.get_pat(first.pvb_pat).ppat_desc { - return arena.get_string(name.txt).contains('$'); + return first + .pvb_attributes + .iter() + .any(|attr| arena.get_string(attr.0.txt) == INSTANCES_ATTRIBUTE); } false } @@ -1234,7 +1241,14 @@ pub(crate) fn type_extension( } with_discovery(tctx, |tctx, discovery| { if let Some(code) = run_call(tctx, env, discovery, &mut table, at, &name, args, None) { - discovery.edits.push(Edit::replace(at.0, at.1, format!("({code})"))); + // A record or variant body is the right-hand side of a type + // declaration, which takes no parentheses. + let text = if code.trim_start().starts_with(['{', '|']) { + code + } else { + format!("({code})") + }; + discovery.edits.push(Edit::replace(at.0, at.1, text)); } }); Some(pending(tctx, loc)) diff --git a/compiler-rust/src/parser/expr.rs b/compiler-rust/src/parser/expr.rs index 404fed29bf..b421bdf312 100644 --- a/compiler-rust/src/parser/expr.rs +++ b/compiler-rust/src/parser/expr.rs @@ -1503,7 +1503,9 @@ pub fn parse_atomic_expr(p: &mut Parser<'_>) -> Expression { p.next(); let name = super::module::parse_extension_id(p, id_start_idx); - let payload = match super::module::parse_quote_payload(p, &name) { + let payload = match super::module::parse_quote_payload(p, &name) + .or_else(|| super::module::parse_macro_arguments(p, &name)) + { Some(payload) => payload, None => { let payload = super::module::parse_payload_region(p); diff --git a/compiler-rust/src/parser/module.rs b/compiler-rust/src/parser/module.rs index 69ab0c6785..051118a2f1 100644 --- a/compiler-rust/src/parser/module.rs +++ b/compiler-rust/src/parser/module.rs @@ -351,8 +351,13 @@ pub fn parse_structure_item(p: &mut Parser<'_>) -> Option { let ext_start_idx = p.start_pos_idx(); p.next(); let id = parse_extension_id(p, ext_start_idx); - let payload = parse_payload_region(p); - let payload = raw_source_extension_payload(p, &id, payload); + let payload = match parse_macro_arguments(p, &id) { + Some(payload) => payload, + None => { + let payload = parse_payload_region(p); + raw_source_extension_payload(p, &id, payload) + } + }; parse_newline_or_semicolon_structure(p); Some(StructureItemDesc::Pstr_extension(Box::new(( (id, payload), @@ -4151,6 +4156,61 @@ pub(super) fn parse_quote_payload(p: &mut Parser<'_>, id: &StringLoc) -> Option< Some(payload) } +/// The arguments of a macro where expressions are written, +/// `%Route.make("/users/:id", 3)`: the name is a module path, which no PPX +/// extension is. One argument is kept as that expression, several as a +/// tuple of them. +pub(super) fn parse_macro_arguments(p: &mut Parser<'_>, id: &StringLoc) -> Option { + if !(p.token == Token::Lparen && p.start_pos.cnum == p.prev_end_pos.cnum) { + return None; + } + if !p + .arena() + .get_string(id.txt) + .starts_with(|c: char| c.is_ascii_uppercase()) + { + return None; + } + p.leave_breadcrumb(Grammar::AttributePayload); + let start_pos_idx = p.start_pos_idx(); + p.next(); + let mut exprs = Vec::new(); + while p.token != Token::Rparen && p.token != Token::Eof { + let expr = super::expr::parse_expr(p); + exprs.push(expr); + if p.token == Token::Comma { + p.next(); + } else { + break; + } + } + p.expect(Token::Rparen); + p.eat_breadcrumb(); + let loc = p.mk_loc_idx_to_prev_end(start_pos_idx); + let expr = match exprs.len() { + 0 => return Some(Payload::PStr(Box::default())), + 1 => exprs.pop().expect("one argument"), + _ => { + let indices: Vec<_> = exprs + .into_iter() + .map(|expr| p.arena_mut().push_expr(expr)) + .collect(); + Expression { + pexp_desc: ExpressionDesc::Pexp_tuple(p.arena_mut().push_expr_list(&indices)), + pexp_loc: loc, + pexp_attributes: Attributes::new(), + } + } + }; + let item_loc = expr.pexp_loc; + let expr_idx = p.arena_mut().push_expr(expr); + let item = StructureItem { + pstr_desc: StructureItemDesc::Pstr_eval(Box::new((expr_idx, Attributes::new()))), + pstr_loc: item_loc, + }; + Some(Payload::PStr(Box::new(vec![item]))) +} + /// The arguments of a macro in a type position, `%Partial.t(user)`: the /// name is a module path, which no PPX extension is, and the arguments are /// types. One argument is kept as that type, several as a tuple of them. @@ -4207,6 +4267,9 @@ pub(super) fn parse_extension(p: &mut Parser<'_>, module_language: bool) -> Exte } let id = parse_extension_id(p, id_start_idx); + if let Some(payload) = parse_macro_arguments(p, &id) { + return (id, payload); + } let payload = parse_payload_region(p); let payload = raw_source_extension_payload(p, &id, payload); diff --git a/compiler-rust/src/raw_lambda/convert.rs b/compiler-rust/src/raw_lambda/convert.rs index 58057f8df6..52840d3b2e 100644 --- a/compiler-rust/src/raw_lambda/convert.rs +++ b/compiler-rust/src/raw_lambda/convert.rs @@ -5225,7 +5225,20 @@ impl<'a> RawLambdaConverter<'a> { } StructureItemDesc::Tstr_value(rec_flag, bindings) => { let old_len = fields.len(); - fields.extend(let_bound_idents(self.ta, self.ta.value_bindings(*bindings))); + // The instances a macro generated are not fields of the module. + let generated = self + .ta + .value_bindings(*bindings) + .first() + .is_some_and(|binding| { + binding.vb_attributes.iter().any(|attr| { + self.arena.get_string(attr.0.txt) + == crate::macros::discover::INSTANCES_ATTRIBUTE + }) + }); + if !generated { + fields.extend(let_bound_idents(self.ta, self.ta.value_bindings(*bindings))); + } let body = self.convert_structure_items_raw(fields, rem, is_top_level, rootpath, cc, loc); fields.truncate(old_len); diff --git a/compiler-rust/tests/macros.rs b/compiler-rust/tests/macros.rs index 86c1d77447..d885e723be 100644 --- a/compiler-rust/tests/macros.rs +++ b/compiler-rust/tests/macros.rs @@ -222,3 +222,199 @@ fn generic_macro_makes_one_function_per_type() { assert!(js.contains("\"user_age\""), "{js}"); assert!(js.contains("value.address") || js.contains("address"), "{js}"); } + +fn compile_ok(project: &mut Project, filename: &str, source: &str) -> String { + match project.compile(filename, source) { + Ok(js) => { + println!( + "--- {filename} expanded\n{}\n--- {filename} js\n{js}", + project.expanded.clone().unwrap_or_default() + ); + js + } + Err(error) => panic!("{filename} failed:\n{error}"), + } +} + +#[test] +fn derive_on_a_type_adds_declarations() { + let mut project = Project::new(); + compile_ok(&mut project, "Json.res", JSON); + let js = compile_ok( + &mut project, + "Account.res", + r#" +@Json.codec +type account = {id: string, balance: float} + +let json = account_encode({id: "a1", balance: 12.5}) +"#, + ); + assert!(js.contains("account_encode"), "{js}"); + assert!(js.contains("exports.account_encode"), "{js}"); + assert!(!js.contains("exports.encode$"), "{js}"); +} + +#[test] +fn recursive_types_and_variants() { + let mut project = Project::new(); + compile_ok(&mut project, "Json.res", JSON); + let js = compile_ok( + &mut project, + "Tree.res", + r#" +type rec tree = {value: int, children: array} +type shape = Circle(float) | Rect({width: float, height: float}) | Point + +let encodeTree = (t: tree) => Json.encode(t) +let encodeShape = (s: shape) => Json.encode(s) +"#, + ); + assert!(js.contains("encode$tree"), "{js}"); + assert!(js.contains("\"Circle\""), "{js}"); +} + +#[test] +fn generic_waits_for_inference() { + let mut project = Project::new(); + compile_ok(&mut project, "Json.res", JSON); + let js = compile_ok( + &mut project, + "Save.res", + r#" +type user = {name: string} +let store = (_user: user, _body: JSON.t) => () +let save = user => { + let body = Json.encode(user) + store(user, body) +} +"#, + ); + assert!(js.contains("encode$user"), "{js}"); +} + +#[test] +fn generic_with_compile_time_argument() { + let mut project = Project::new(); + compile_ok( + &mut project, + "Power.res", + r#" +open Macro + +@generic +let rec pow = (base: code, n: int): code => + n == 0 ? %code(1.0) : %code(${base} *. ${pow(base, n - 1)}) +"#, + ); + let js = compile_ok(&mut project, "Cube.res", "let cube = x => Power.pow(x, 3)\n"); + assert!(js.contains("* 1.0"), "{js}"); +} + +#[test] +fn type_macro() { + let mut project = Project::new(); + compile_ok( + &mut project, + "Partial.res", + r#" +open Macro + +@macro +let t = (source: typ): typ => + switch Type.info(source) { + | Record({fields}) => Type.record(fields->Array.map(f => {...f, optional: true})) + | _ => error("Partial.t needs a record type") + } +"#, + ); + let js = compile_ok( + &mut project, + "Patch.res", + r#" +type user = {name: string, age: int} +type userPatch = %Partial.t(user) +let patch: userPatch = {age: 3} +"#, + ); + assert!(js.contains("age: 3"), "{js}"); +} + +#[test] +fn module_and_item_macros() { + let mut project = Project::new(); + compile_ok( + &mut project, + "Gen.res", + r#" +open Macro + +@macro +let constants = (prefix: string, count: int): decls => + Code.decls( + Array.fromInitializer(~length=count, i => + %code(let ${Pat.var(prefix ++ Int.toString(i))} = ${Code.int(i * 10)}) + ), + ) + +@macro +let span = (b: Decl.value): decls => + %code(let ${b.pat} = Gen.wrap(${Code.string(b.name)}, ${b.expr})) + +let wrap = (name: string, f: 'a => 'b): ('a => 'b) => x => { + Console.log(name) + f(x) +} +"#, + ); + let js = compile_ok( + &mut project, + "UseGen.res", + r#" +module K = %Gen.constants("k", 3) +%%Gen.constants("top", 2) +let sum = K.k1 + K.k2 + top1 + +@Gen.span +let double = x => x * 2 +"#, + ); + assert!(js.contains("\"double\""), "{js}"); + assert!(js.contains("30") || js.contains("k2"), "{js}"); +} + +#[test] +fn comptime_evaluates_now() { + let mut project = Project::new(); + compile_ok( + &mut project, + "Table.res", + "let squares = n => Array.fromInitializer(~length=n, i => i * i)\nlet config = () => {\"name\": \"x\"}\n", + ); + let js = compile_ok( + &mut project, + "UseTable.res", + "let table = %comptime(Table.squares(5))\nlet label = %comptime(String.toUpperCase(\"abc\") ++ \"!\")\n", + ); + assert!(js.contains("16"), "{js}"); + assert!(js.contains("\"ABC!\""), "{js}"); + assert!(!js.contains("Table"), "{js}"); +} + +#[test] +fn macro_errors_point_at_the_use() { + let mut project = Project::new(); + compile_ok(&mut project, "Json.res", JSON); + let error = project + .compile("Bad.res", "let f = (g: int => int) => Json.encode(g)\n") + .unwrap_err(); + println!("{error}"); + assert!(error.contains("Bad.res:1:"), "{error}"); + assert!(error.contains("unsupported type"), "{error}"); + + let error = project + .compile("Unknown.res", "let f = x => Json.encode(x)\n") + .unwrap_err(); + println!("{error}"); + assert!(error.contains("generated per type"), "{error}"); +} From 84cd20660282883ea1d5b349cc475d3fbd6c34bc Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:43:44 +0100 Subject: [PATCH 05/38] macros: text outside ASCII, and the sandbox in the engine script The compiler keeps source text as one char per byte; the engine works with the text those bytes encode. Requests and responses are converted where they cross, and readFile and env answers are read like a source file. host.js now hides the clock, random numbers and the page's input and output from macro modules itself, so the browser engine gets the same rules as the embedded one. Co-authored-by: Jaap Frolich Session: https://jakes-mac-mini.tail23a77e.ts.net:8443/session/os-01a1ca09-2757-709a-bbb1-e57ccc4d104f Signed-off-by: Jaap Frolich --- compiler-rust/src/driver.rs | 6 +++ compiler-rust/src/macros/discover.rs | 22 ++++++---- compiler-rust/src/macros/expand.rs | 3 +- compiler-rust/src/macros/host.js | 64 ++++++++++++++++++++++------ compiler-rust/src/macros/mod.rs | 11 +++++ compiler-rust/src/macros/quickjs.rs | 29 ++----------- compiler-rust/tests/macros.rs | 53 ++++++++++++++++++++--- 7 files changed, 133 insertions(+), 55 deletions(-) diff --git a/compiler-rust/src/driver.rs b/compiler-rust/src/driver.rs index 838bbed1f4..a51350df4d 100644 --- a/compiler-rust/src/driver.rs +++ b/compiler-rust/src/driver.rs @@ -5588,6 +5588,12 @@ fn format_type_warnings( /// The source text an in-process compile reports diagnostics against. Like /// OCaml's code frames (location.ml), it is read back from the source file. fn read_in_process_source(filename: &str) -> String { + #[cfg(target_arch = "wasm32")] + { + if let Some(content) = crate::wasm_vfs::read_file(filename) { + return content; + } + } std::fs::read(filename) .map(crate::source_text::latin1_bytes_to_string) .unwrap_or_default() diff --git a/compiler-rust/src/macros/discover.rs b/compiler-rust/src/macros/discover.rs index ff42e37e7c..087117c4ff 100644 --- a/compiler-rust/src/macros/discover.rs +++ b/compiler-rust/src/macros/discover.rs @@ -386,9 +386,7 @@ impl Discovery { let mut answers = serde_json::Map::new(); for _ in 0..4096 { request["answers"] = Value::Object(answers.clone()); - let response = self - .host - .call(&request.to_string()) + let response = super::call_host(&*self.host, &request.to_string()) .map_err(|message| (format!("The macro engine failed: {message}"), None))?; let response: Value = serde_json::from_str(&response) .map_err(|error| (format!("The macro engine returned invalid JSON: {error}"), None))?; @@ -458,14 +456,17 @@ pub(crate) fn answer_input(base_dir: &std::path::Path, question: &str) -> Option None => json!({ "__error": format!("readFile: cannot read `{rest}`.") }), }), "env" => Some(match std::env::var(rest) { - Ok(value) => Value::String(value), + Ok(value) => { + Value::String(crate::source_text::latin1_bytes_to_string(value.into_bytes())) + } Err(_) => Value::Null, }), _ => None, } } -/// Read `path` relative to `base` or one of its ancestors. +/// Read `path` relative to `base` or one of its ancestors, as the compiler +/// reads a source file: one `char` per byte. fn read_file(base: &std::path::Path, path: &str) -> Option { #[cfg(feature = "wasm")] { @@ -479,18 +480,23 @@ fn read_file(base: &std::path::Path, path: &str) -> Option { } #[cfg(not(feature = "wasm"))] { + let read = |path: &std::path::Path| { + std::fs::read(path) + .ok() + .map(crate::source_text::latin1_bytes_to_string) + }; let relative = std::path::Path::new(path); if relative.is_absolute() { - return std::fs::read_to_string(relative).ok(); + return read(relative); } let mut dir = Some(base); while let Some(current) = dir { - if let Ok(text) = std::fs::read_to_string(current.join(relative)) { + if let Some(text) = read(¤t.join(relative)) { return Some(text); } dir = current.parent(); } - std::fs::read_to_string(relative).ok() + read(relative) } } diff --git a/compiler-rust/src/macros/expand.rs b/compiler-rust/src/macros/expand.rs index 3c0ba054b9..91d2c54afd 100644 --- a/compiler-rust/src/macros/expand.rs +++ b/compiler-rust/src/macros/expand.rs @@ -308,8 +308,7 @@ fn evaluate_comptime( "shape": site.shape, "answers": answers, }); - let response = host - .call(&request.to_string()) + let response = super::call_host(&**host, &request.to_string()) .map_err(|message| format!("%comptime: the macro engine failed: {message}"))?; let response: Value = serde_json::from_str(&response) .map_err(|error| format!("%comptime: the macro engine returned invalid JSON: {error}"))?; diff --git a/compiler-rust/src/macros/host.js b/compiler-rust/src/macros/host.js index 05a449af9e..5e00937518 100644 --- a/compiler-rust/src/macros/host.js +++ b/compiler-rust/src/macros/host.js @@ -4,6 +4,10 @@ // browser. The embedder provides `__rescript_macro_source(moduleName)`, which // returns the compiled JavaScript of a module or undefined. // +// Macro code sees no clock, no random numbers and no network: a macro gets +// its inputs from the compiler (`readFile`, `env`, `Type.info`), which is +// what makes an expansion a function of recorded inputs. +// // A macro cannot call back into the compiler. When it needs an answer the // compiler has not given yet (the shape of a type, the text of a file), `ask` // throws, the call returns `{need: question}`, and the compiler runs the macro @@ -31,6 +35,10 @@ expected: function () { return state.expected; }, + // For embedders that also run compiled modules themselves. + toCommonJs: function (source) { + return toCommonJs(source); + }, }; function moduleName(specifier) { @@ -62,6 +70,48 @@ }); } + function refuse(what) { + return function () { + throw { __macro_error: what + " is not available at compile time: a macro has to give the same result every time." }; + }; + } + + // What a module of macro code sees in place of the globals of the same + // name. The names of the browser's and Node's input and output are + // undefined. + var hidden = [ + "fetch", "XMLHttpRequest", "WebSocket", "importScripts", "postMessage", "navigator", "location", + "indexedDB", "caches", "localStorage", "sessionStorage", "document", "window", "self", "process", + "setTimeout", "setInterval", "setImmediate", "queueMicrotask", "performance", "crypto", + ]; + var sandbox = (function () { + var math = Object.create(Math); + math.random = refuse("Math.random"); + var RealDate = Date; + function FixedDate() { + if (arguments.length === 0) refuse("The current time")(); + return new (Function.prototype.bind.apply(RealDate, [null].concat(Array.prototype.slice.call(arguments))))(); + } + FixedDate.prototype = RealDate.prototype; + FixedDate.UTC = RealDate.UTC; + FixedDate.parse = RealDate.parse; + FixedDate.now = refuse("Date.now"); + return { Math: math, Date: FixedDate }; + })(); + + function run(source, module) { + var parameters = ["require", "exports", "module", "Math", "Date"].concat(hidden); + Function.apply(null, parameters.concat([toCommonJs(source)]))( + function (specifier) { + return load(moduleName(specifier)); + }, + module.exports, + module, + sandbox.Math, + sandbox.Date, + ); + } + function load(name) { var loaded = modules[name]; if (loaded) return loaded.exports; @@ -72,13 +122,7 @@ var module = { exports: {} }; modules[name] = module; try { - new Function("require", "exports", "module", toCommonJs(source))( - function (specifier) { - return load(moduleName(specifier)); - }, - module.exports, - module, - ); + run(source, module); } catch (error) { delete modules[name]; throw error; @@ -150,11 +194,7 @@ if (request.kind === "eval") { // %comptime: `source` is a compiled module that exports `value`. var module = { exports: {} }; - new Function("require", "exports", "module", toCommonJs(request.source))( - function (specifier) { return load(moduleName(specifier)); }, - module.exports, - module, - ); + run(request.source, module); return JSON.stringify({ ok: reify(module.exports.value, request.shape) }); } var exports = load(request.module); diff --git a/compiler-rust/src/macros/mod.rs b/compiler-rust/src/macros/mod.rs index d801915f13..971e284a0a 100644 --- a/compiler-rust/src/macros/mod.rs +++ b/compiler-rust/src/macros/mod.rs @@ -41,6 +41,17 @@ pub trait MacroHost: Send + Sync { fn call(&self, request: &str) -> Result; } +/// Call the engine with a request built from the compiler's text. +/// +/// The compiler keeps source text as one `char` per byte of the file, so +/// that every offset is a byte offset; the engine works with the text those +/// bytes encode. Everything that crosses is converted here: the request to +/// real text, the response back to one `char` per byte. +pub(crate) fn call_host(host: &dyn MacroHost, request: &str) -> Result { + let response = host.call(&crate::source_text::decode_internal_utf8(request))?; + Ok(crate::source_text::latin1_bytes_to_string(response.into_bytes())) +} + impl std::fmt::Debug for dyn MacroHost { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("MacroHost") diff --git a/compiler-rust/src/macros/quickjs.rs b/compiler-rust/src/macros/quickjs.rs index 8a9ad1b57f..8892e3f8b3 100644 --- a/compiler-rust/src/macros/quickjs.rs +++ b/compiler-rust/src/macros/quickjs.rs @@ -1,9 +1,8 @@ //! The macro engine of native builds: QuickJS, linked into the compiler. //! -//! One engine per thread that expands macros, created on first use. It has -//! no file system, no network, no clock and no random numbers: a macro gets -//! its inputs from the compiler (`readFile`, `env`, `Type.info`), which is -//! what makes an expansion a function of recorded inputs. +//! One engine per thread that expands macros, created on first use. QuickJS +//! has no file system and no network; `host.js` hides the clock and random +//! numbers from macro code. use std::cell::RefCell; use std::sync::Arc; @@ -22,27 +21,6 @@ const MEMORY_LIMIT: usize = 512 * 1024 * 1024; /// Time one macro call may take. const TIME_LIMIT: Duration = Duration::from_secs(20); -const SANDBOX_JS: &str = r#" -(function () { - function refuse(what) { - return function () { - throw { __macro_error: what + " is not available at compile time: a macro has to give the same result every time." }; - }; - } - Math.random = refuse("Math.random"); - var RealDate = Date; - function FixedDate() { - if (arguments.length === 0) refuse("The current time")(); - return new (Function.prototype.bind.apply(RealDate, [null].concat(Array.prototype.slice.call(arguments))))(); - } - FixedDate.prototype = RealDate.prototype; - FixedDate.UTC = RealDate.UTC; - FixedDate.parse = RealDate.parse; - FixedDate.now = refuse("Date.now"); - globalThis.Date = FixedDate; -})(); -"#; - static NEXT_HOST: AtomicU64 = AtomicU64::new(1); /// A [`MacroHost`] that runs macros in QuickJS. @@ -99,7 +77,6 @@ impl QuickJsHost { sources(&name) })?; ctx.globals().set("__rescript_macro_source", source)?; - ctx.eval::<(), _>(SANDBOX_JS)?; ctx.eval::<(), _>(HOST_JS)?; Ok(()) }) diff --git a/compiler-rust/tests/macros.rs b/compiler-rust/tests/macros.rs index d885e723be..3fa4d4c21f 100644 --- a/compiler-rust/tests/macros.rs +++ b/compiler-rust/tests/macros.rs @@ -72,6 +72,9 @@ impl Project { macro_host: Some(host), ..Default::default() }; + // As the compiler reads a file: one `char` per byte. + let source: String = source.bytes().map(char::from).collect(); + let source = source.as_str(); match driver::compile_source_in_process( source, filename, @@ -93,15 +96,16 @@ impl Project { ), ); } - self.javascript - .lock() - .unwrap() - .insert(module_name, compiled.js_output.clone()); + let text = |text: &str| { + rescript_compiler::source_text::decode_internal_utf8(text).into_owned() + }; + let js = text(&compiled.js_output); + self.javascript.lock().unwrap().insert(module_name, js.clone()); self.host.invalidate(); - self.expanded = compiled.expanded_source; - Ok(compiled.js_output) + self.expanded = compiled.expanded_source.as_deref().map(text); + Ok(js) } - Err(e) => Err(format!("{e:#}")), + Err(e) => Err(rescript_compiler::source_text::decode_internal_utf8(&format!("{e:#}")).into_owned()), } } } @@ -418,3 +422,38 @@ fn macro_errors_point_at_the_use() { println!("{error}"); assert!(error.contains("generated per type"), "{error}"); } + +#[test] +fn text_outside_ascii() { + let mut project = Project::new(); + compile_ok( + &mut project, + "Shout.res", + r#" +open Macro + +@macro +let label = (text: string): code => Code.string("« " ++ String.toUpperCase(text) ++ " » ✓") +"#, + ); + let js = compile_ok( + &mut project, + "Menu.res", + "let cafe = \"crème brûlée\"\nlet title = %Shout.label(\"déjà vu\")\nlet both = cafe ++ title\n", + ); + assert!(js.contains("\"« DÉJÀ VU » ✓\""), "{js}"); + assert!(js.contains("crème brûlée"), "{js}"); + + // A macro error after non-ASCII text is reported at the right column. + compile_ok( + &mut project, + "Fail.res", + "open Macro\n@macro\nlet now = (text: string): code => error(\"no \" ++ text)\n", + ); + let error = project + .compile("Late.res", "let s = \"déjà\"; let t = %Fail.now(\"été\")\n") + .unwrap_err(); + println!("{error}"); + assert!(error.contains("no été"), "{error}"); + assert!(error.contains("Late.res:1:"), "{error}"); +} From f887c1215458d5d55b0d8feee9cebb149ae6b379 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:55:43 +0100 Subject: [PATCH 06/38] macros: build Macro with the runtime, structured compile-time arguments - The runtime package now ships Macro as JavaScript (lib/js, lib/es6). - A compile-time argument can be an array, tuple or record of literals. - open Macro does not warn about shadowing Type: Macro.Type includes the standard library's Type. - Pat.string and Pat.int. - A runtime module that is type checked from source is checked with the runtime package's flags (-nopervasives -open Pervasives). With the standard library of the module that needed it, Primitive_array could not be loaded before Stdlib was. - playground/examples holds the playground's example projects; a test compiles all of them. Co-authored-by: Jaap Frolich Session: https://jakes-mac-mini.tail23a77e.ts.net:8443/session/os-01a1ca09-2757-709a-bbb1-e57ccc4d104f Signed-off-by: Jaap Frolich --- compiler-rust/src/cmi/persistent_env.rs | 44 ++- compiler-rust/src/macros/discover.rs | 22 +- compiler-rust/src/types/typecore.rs | 10 + compiler-rust/tests/macros.rs | 87 +++++ packages/@rescript/runtime/Macro.res | 10 + packages/@rescript/runtime/lib/es6/Macro.mjs | 363 +++++++++++++++++++ packages/@rescript/runtime/lib/js/Macro.cjs | 361 ++++++++++++++++++ packages/artifacts.json | 6 + playground/examples/comptime/Main.res | 8 + playground/examples/comptime/Sieve.res | 18 + playground/examples/debug/Debug.res | 20 + playground/examples/debug/Main.res | 7 + playground/examples/derive/Enum.res | 33 ++ playground/examples/derive/Main.res | 9 + playground/examples/files/I18n.res | 31 ++ playground/examples/files/Main.res | 8 + playground/examples/files/en.json | 5 + playground/examples/index.json | 85 +++++ playground/examples/items/Main.res | 7 + playground/examples/items/Trace.res | 13 + playground/examples/items/Units.res | 17 + playground/examples/json/Json.res | 51 +++ playground/examples/json/Main.res | 29 ++ playground/examples/lens/Lens.res | 26 ++ playground/examples/lens/Main.res | 8 + playground/examples/staged/Main.res | 5 + playground/examples/staged/Power.res | 17 + playground/examples/types/Main.res | 13 + playground/examples/types/Partial.res | 9 + rewatch/Cargo.lock | 28 ++ 30 files changed, 1337 insertions(+), 13 deletions(-) create mode 100644 packages/@rescript/runtime/lib/es6/Macro.mjs create mode 100644 packages/@rescript/runtime/lib/js/Macro.cjs create mode 100644 playground/examples/comptime/Main.res create mode 100644 playground/examples/comptime/Sieve.res create mode 100644 playground/examples/debug/Debug.res create mode 100644 playground/examples/debug/Main.res create mode 100644 playground/examples/derive/Enum.res create mode 100644 playground/examples/derive/Main.res create mode 100644 playground/examples/files/I18n.res create mode 100644 playground/examples/files/Main.res create mode 100644 playground/examples/files/en.json create mode 100644 playground/examples/index.json create mode 100644 playground/examples/items/Main.res create mode 100644 playground/examples/items/Trace.res create mode 100644 playground/examples/items/Units.res create mode 100644 playground/examples/json/Json.res create mode 100644 playground/examples/json/Main.res create mode 100644 playground/examples/lens/Lens.res create mode 100644 playground/examples/lens/Main.res create mode 100644 playground/examples/staged/Main.res create mode 100644 playground/examples/staged/Power.res create mode 100644 playground/examples/types/Main.res create mode 100644 playground/examples/types/Partial.res diff --git a/compiler-rust/src/cmi/persistent_env.rs b/compiler-rust/src/cmi/persistent_env.rs index 12737fbefc..ee9b532322 100644 --- a/compiler-rust/src/cmi/persistent_env.rs +++ b/compiler-rust/src/cmi/persistent_env.rs @@ -2337,17 +2337,37 @@ impl PersistentEnv { }), }; let mut env = initial_env(ctx); - let open_modules = fallback_pers.open_modules.clone(); - let nopervasives = fallback_pers.nopervasives; - let compiling_module = fallback_pers.view.compiling_module.clone(); - load_pervasives( - &mut fallback_pers, - &mut env, - ctx, - &open_modules, - nopervasives, - compiling_module.as_deref(), - ); + if self.source_fallback_is_runtime { + // A module of the runtime is compiled as the runtime package + // compiles it (`-nostdlib -nopervasives -open Pervasives` in its + // rescript.json), not with the standard library of the module + // that needs it: `Stdlib` itself is built from these modules. + let module_name = source_path + .file_stem() + .map(|stem| stem.to_string_lossy().into_owned()); + fallback_pers.nopervasives = true; + fallback_pers.open_modules = Arc::new(vec!["Pervasives".to_string()]); + load_pervasives( + &mut fallback_pers, + &mut env, + ctx, + &["Pervasives".to_string()], + true, + module_name.as_deref(), + ); + } else { + let open_modules = fallback_pers.open_modules.clone(); + let nopervasives = fallback_pers.nopervasives; + let compiling_module = fallback_pers.view.compiling_module.clone(); + load_pervasives( + &mut fallback_pers, + &mut env, + ctx, + &open_modules, + nopervasives, + compiling_module.as_deref(), + ); + } if source_path .extension() @@ -2400,7 +2420,7 @@ impl PersistentEnv { } let options = CompilerOptions { - open_modules: self.open_modules.as_ref().clone(), + open_modules: fallback_pers.open_modules.as_ref().clone(), jsx_version: self.jsx_version, jsx_module: self.jsx_module.clone(), ..CompilerOptions::default() diff --git a/compiler-rust/src/macros/discover.rs b/compiler-rust/src/macros/discover.rs index 087117c4ff..3ce3c8ef8b 100644 --- a/compiler-rust/src/macros/discover.rs +++ b/compiler-rust/src/macros/discover.rs @@ -613,6 +613,26 @@ fn literal(arena: &ParseArena, expr: ExprIdx) -> Option { _ => None, } } + // An array and a tuple are both an array at run time. + ExpressionDesc::Pexp_array(items) | ExpressionDesc::Pexp_tuple(items) => arena + .expr_list(*items) + .iter() + .map(|item| literal(arena, *item)) + .collect::>>() + .map(Value::Array), + ExpressionDesc::Pexp_record((fields, None)) => { + let mut object = serde_json::Map::new(); + for field in arena.expr_field_list(*fields) { + let Longident::Lident(name) = arena.get_longident(field.lid.txt) else { + return None; + }; + if field.opt { + return None; + } + object.insert(arena.get_string(*name).to_string(), literal(arena, field.expr)?); + } + Some(Value::Object(object)) + } _ => None, } } @@ -677,7 +697,7 @@ fn call_arguments( Some(value) => args.push(value), None => { return Err(format!( - "Argument {} of the macro `{name}` is a compile-time value, so it has to be a literal.", + "Argument {} of the macro `{name}` is a compile-time value, so it has to be a literal: a number, a string, a boolean, or an array, tuple or record of them.", index + 1 )); } diff --git a/compiler-rust/src/types/typecore.rs b/compiler-rust/src/types/typecore.rs index db9b341f02..205e9f37e7 100644 --- a/compiler-rust/src/types/typecore.rs +++ b/compiler-rust/src/types/typecore.rs @@ -1644,6 +1644,16 @@ impl<'a> TypeCheckContext<'a> { state.used = true; report }); + // `Macro.Type` takes the place of `Stdlib.Type`, which it + // includes: opening `Macro` loses nothing. + let report = report.filter(|_| { + !(event.kind == "module" + && event.name == "Type" + && self + .delayed_open_checks + .iter() + .any(|check| check.slot == event.slot && check.root == crate::macros::MACRO_MODULE)) + }); if let Some(loc) = report { let warning = match event.kind { "label" | "constructor" => Warning::OpenShadowLabelConstructor { diff --git a/compiler-rust/tests/macros.rs b/compiler-rust/tests/macros.rs index 3fa4d4c21f..aa394fd3db 100644 --- a/compiler-rust/tests/macros.rs +++ b/compiler-rust/tests/macros.rs @@ -22,6 +22,8 @@ struct Project { host: Arc, /// The expanded source of the last compiled file, when it uses macros. expanded: Option, + /// The warnings of the last compiled file. + warnings: String, } impl Project { @@ -56,6 +58,7 @@ impl Project { javascript, host, expanded: None, + warnings: String::new(), }; // The macro API, compiled from source like the rest of the project. let macro_source = std::fs::read_to_string(runtime_dir().join("Macro.res")).unwrap(); @@ -103,6 +106,7 @@ impl Project { self.javascript.lock().unwrap().insert(module_name, js.clone()); self.host.invalidate(); self.expanded = compiled.expanded_source.as_deref().map(text); + self.warnings = text(&compiled.warnings); Ok(js) } Err(e) => Err(rescript_compiler::source_text::decode_internal_utf8(&format!("{e:#}")).into_owned()), @@ -457,3 +461,86 @@ let label = (text: string): code => Code.string("« " ++ String.toUpperC assert!(error.contains("no été"), "{error}"); assert!(error.contains("Late.res:1:"), "{error}"); } + +#[test] +fn array_spread_needs_a_runtime_module_first() { + // `Primitive_array` is type checked from source here, before anything + // else needed it. + let mut project = Project::new(); + let js = compile_ok(&mut project, "Spread.res", "let f = (a, rest) => [a, ...rest]\n"); + assert!(js.contains("Primitive_array"), "{js}"); +} + +#[test] +fn compile_time_arguments_can_be_structured() { + let mut project = Project::new(); + compile_ok( + &mut project, + "Sum.res", + r#" +open Macro + +type options = {scale: int, label: string} + +@macro +let total = (items: array<(string, int)>, options: options): code => { + let sum = items->Array.reduce(0, (sum, (_, n)) => sum + n) * options.scale + Code.string(options.label ++ Int.toString(sum)) +} +"#, + ); + let js = compile_ok( + &mut project, + "UseSum.res", + "let total = %Sum.total([(\"a\", 1), (\"b\", 2)], {scale: 10, label: \"sum=\"})\n", + ); + assert!(js.contains("\"sum=30\""), "{js}"); +} + +#[test] +fn opening_macro_does_not_warn() { + let mut project = Project::new(); + project + .compile( + "Quiet.res", + "open Macro\n@macro\nlet name = (t: typ): code => Code.string(Type.name(t))\nlet kind = Type.typeof(1)\n", + ) + .unwrap(); + assert_eq!(project.warnings, ""); +} + +/// The examples of the playground compile. `playground/scripts/smoke.mjs` +/// also runs them, with the compiler built to WebAssembly. +#[test] +fn playground_examples_compile() { + // A debug build of the type checker needs more stack than a test thread + // has; the compiler's own threads have it. + std::thread::Builder::new() + .stack_size(512 * 1024 * 1024) + .spawn(compile_playground_examples) + .unwrap() + .join() + .unwrap(); +} + +fn compile_playground_examples() { + let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../playground/examples"); + let index: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(dir.join("index.json")).unwrap()).unwrap(); + for example in index.as_array().unwrap() { + let id = example["id"].as_str().unwrap(); + let mut project = Project::new(); + for file in example["files"].as_array().unwrap() { + let name = file.as_str().unwrap(); + if !name.ends_with(".res") { + continue; + } + let path = dir.join(id).join(name); + let source = std::fs::read_to_string(&path).unwrap(); + if let Err(error) = project.compile(path.to_str().unwrap(), &source) { + panic!("example {id}, {name}:\n{error}"); + } + assert_eq!(project.warnings, "", "example {id}, {name}"); + } + } +} diff --git a/packages/@rescript/runtime/Macro.res b/packages/@rescript/runtime/Macro.res index eff9158d86..b4cb45ab15 100644 --- a/packages/@rescript/runtime/Macro.res +++ b/packages/@rescript/runtime/Macro.res @@ -114,6 +114,10 @@ module Attr = { } module Type = { + // `open Macro` puts this module in the place of the standard library's + // `Type`, so it has everything that one has. + include Stdlib_Type + type field = { name: string, /** The name at run time: the `@as` name when there is one. */ @@ -312,6 +316,12 @@ module Pat = { /** `_` */ let any: pat = make("_") + /** A string literal pattern. */ + let string = (value: string): pat => make(JSON.stringify(JSON.Encode.string(value))) + + /** An integer literal pattern. */ + let int = (value: int): pat => make(Int.toString(value)) + /** The pattern that matches a constructor and binds its arguments, with the code of each bound argument: `Circle(a0, a1)` and `[a0, a1]`. diff --git a/packages/@rescript/runtime/lib/es6/Macro.mjs b/packages/@rescript/runtime/lib/es6/Macro.mjs new file mode 100644 index 0000000000..f8f932ccd2 --- /dev/null +++ b/packages/@rescript/runtime/lib/es6/Macro.mjs @@ -0,0 +1,363 @@ + + +import * as Stdlib_Type from "./Stdlib_Type.mjs"; +import * as Primitive_object from "./Primitive_object.mjs"; +import * as Primitive_option from "./Primitive_option.mjs"; + +function make(source) { + return { + c: source + }; +} + +function source(value) { + return value.c; +} + +function error(message) { + return __rescript_macro.fail(message, undefined); +} + +function errorAt(offset, message) { + return __rescript_macro.fail(message, offset); +} + +function typeOf(value) { + let t = value.t; + if (t !== undefined) { + return t; + } else { + return __rescript_macro.fail("typeOf: the type of this code is not known. Only the arguments of a macro carry a type.", undefined); + } +} + +function expected() { + let t = __rescript_macro.expected(); + if (t == null) { + return __rescript_macro.fail("expected: only a @generic macro knows the type its call site expects.", undefined); + } else { + return t; + } +} + +function readFile(path) { + return __rescript_macro.ask("readFile:" + path); +} + +function env(name) { + return Primitive_option.fromNullable(__rescript_macro.ask("env:" + name)); +} + +function __holeItem(value) { + return { + c: value.c, + raw: true + }; +} + +function quote(pieces, holes) { + let text = pieces[0]; + holes.forEach((hole, index) => { + let filled = Primitive_object.equal(hole.raw, true) ? hole.c : "(" + hole.c + ")"; + text = text + filled + pieces[index + 1 | 0]; + }); + return { + c: text + }; +} + +let __quoteCode = quote; + +let __quoteDecls = quote; + +let __quoteType = quote; + +let __quotePat = quote; + +let isSimple = (function (text) { + return /^[A-Za-z_][A-Za-z0-9_$.]*$/.test(text) +}); + +function atom(text) { + if (isSimple(text)) { + return text; + } else { + return "(" + text + ")"; + } +} + +function find(attrs, name) { + return attrs.find(attr => attr.name === name); +} + +function has(attrs, name) { + return find(attrs, name) !== undefined; +} + +function string(attrs, name) { + let match = find(attrs, name); + if (match !== undefined) { + return match.payload; + } +} + +let Attr = { + find: find, + has: has, + string: string +}; + +function handle(t, what) { + let id = t.id; + if (id !== undefined) { + return id; + } else { + return __rescript_macro.fail(what + ": this type was built by a macro, so the compiler has no information on it.", undefined); + } +} + +function info(t) { + return __rescript_macro.ask("info:" + handle(t, "Type.info").toString()); +} + +function name(t) { + return t.c; +} + +function companion(t, name) { + return Primitive_option.fromNullable(__rescript_macro.ask("companion:" + handle(t, "Type.companion").toString() + ":" + name)); +} + +function attrText(attrs) { + return attrs.map(attr => { + let payload = attr.payload; + if (payload !== undefined) { + return "@" + attr.name + "(" + JSON.stringify(payload) + ") "; + } else { + return "@" + attr.name + " "; + } + }).join(""); +} + +function fieldText(field) { + return attrText(field.attrs) + ( + field.jsName !== field.name ? "@as(" + JSON.stringify(field.jsName) + ") " : "" + ) + ( + field.mutable_ ? "mutable " : "" + ) + field.name + ( + field.optional ? "?: " : ": " + ) + field.typ.c; +} + +function record(fields) { + return make("{" + fields.map(fieldText).join(", ") + "}"); +} + +function variant(constructors) { + return make(constructors.map(c => "| " + attrText(c.attrs) + ( + c.jsName !== c.name ? "@as(" + JSON.stringify(c.jsName) + ") " : "" + ) + c.name + ( + c.fields.length !== 0 ? "({" + c.fields.map(fieldText).join(", ") + "})" : ( + c.args.length !== 0 ? "(" + c.args.map(source).join(", ") + ")" : "" + ) + )).join(" ")); +} + +function field(name, typ) { + return { + name: name, + jsName: name, + typ: typ, + optional: false, + mutable_: false, + attrs: [] + }; +} + +function constructor(name) { + return { + name: name, + jsName: name, + args: [], + fields: [], + attrs: [] + }; +} + +let Type = { + Classify: Stdlib_Type.Classify, + handle: handle, + info: info, + name: name, + companion: companion, + attrText: attrText, + fieldText: fieldText, + record: record, + variant: variant, + field: field, + constructor: constructor +}; + +function string$1(value) { + return make(JSON.stringify(value)); +} + +function int(value) { + return make(value.toString()); +} + +function float(value) { + let text = value.toString(); + return make(text.includes(".") || text.includes("e") ? text : text + "."); +} + +function bool(value) { + return make(value ? "true" : "false"); +} + +let unit = { + c: "()" +}; + +function print(value) { + return value.c; +} + +let raw = make; + +let ident = make; + +function field$1(value, name) { + return make(atom(value.c) + "." + name); +} + +function array(items) { + return make("[" + items.map(source).join(", ") + "]"); +} + +function tuple(items) { + return make("(" + items.map(source).join(", ") + ")"); +} + +function record$1(fields) { + return make("{" + fields.map(param => param[0] + ": " + param[1].c).join(", ") + "}"); +} + +function call(f, args) { + return make(atom(f.c) + "(" + args.map(source).join(", ") + ")"); +} + +function switch_(value, arms) { + return make("switch " + atom(value.c) + " {\n" + arms.map(param => "| " + param[0].c + " => " + param[1].c).join("\n") + "\n}"); +} + +function param(name, typ) { + return name + ": " + typ.c; +} + +function labelled(name, typ) { + return "~" + name + ": " + typ.c; +} + +function fn(params, body) { + return make("(" + params.join(", ") + ") => " + body.c); +} + +function decls(items) { + return make(items.map(source).join("\n")); +} + +let Code = { + string: string$1, + int: int, + float: float, + bool: bool, + unit: unit, + print: print, + raw: raw, + ident: ident, + field: field$1, + array: array, + tuple: tuple, + record: record$1, + call: call, + switch_: switch_, + param: param, + labelled: labelled, + fn: fn, + decls: decls +}; + +let $$var = make; + +let any = { + c: "_" +}; + +function string$2(value) { + return make(JSON.stringify(value)); +} + +function int$1(value) { + return make(value.toString()); +} + +function constructor$1(c) { + let typed = (name, typ) => ({ + c: name, + t: typ + }); + if (c.fields.length !== 0) { + let names = c.fields.map((f, i) => f.name + "$" + i.toString()); + return [ + make(c.name + "({" + c.fields.map((f, i) => f.name + ": " + names[i]).join(", ") + "})"), + c.fields.map((f, i) => typed(names[i], f.typ)) + ]; + } + if (c.args.length === 0) { + return [ + make(c.name), + [] + ]; + } + let names$1 = c.args.map((param, i) => "arg$" + i.toString()); + return [ + make(c.name + "(" + names$1.join(", ") + ")"), + c.args.map((typ, i) => typed(names$1[i], typ)) + ]; +} + +let Pat = { + $$var: $$var, + any: any, + string: string$2, + int: int$1, + constructor: constructor$1 +}; + +let Decl = {}; + +export { + make, + source, + error, + errorAt, + typeOf, + expected, + readFile, + env, + __holeItem, + quote, + __quoteCode, + __quoteDecls, + __quoteType, + __quotePat, + isSimple, + atom, + Attr, + Type, + Code, + Pat, + Decl, +} +/* No side effect */ diff --git a/packages/@rescript/runtime/lib/js/Macro.cjs b/packages/@rescript/runtime/lib/js/Macro.cjs new file mode 100644 index 0000000000..95b35608ae --- /dev/null +++ b/packages/@rescript/runtime/lib/js/Macro.cjs @@ -0,0 +1,361 @@ +'use strict'; + +let Stdlib_Type = require("./Stdlib_Type.cjs"); +let Primitive_object = require("./Primitive_object.cjs"); +let Primitive_option = require("./Primitive_option.cjs"); + +function make(source) { + return { + c: source + }; +} + +function source(value) { + return value.c; +} + +function error(message) { + return __rescript_macro.fail(message, undefined); +} + +function errorAt(offset, message) { + return __rescript_macro.fail(message, offset); +} + +function typeOf(value) { + let t = value.t; + if (t !== undefined) { + return t; + } else { + return __rescript_macro.fail("typeOf: the type of this code is not known. Only the arguments of a macro carry a type.", undefined); + } +} + +function expected() { + let t = __rescript_macro.expected(); + if (t == null) { + return __rescript_macro.fail("expected: only a @generic macro knows the type its call site expects.", undefined); + } else { + return t; + } +} + +function readFile(path) { + return __rescript_macro.ask("readFile:" + path); +} + +function env(name) { + return Primitive_option.fromNullable(__rescript_macro.ask("env:" + name)); +} + +function __holeItem(value) { + return { + c: value.c, + raw: true + }; +} + +function quote(pieces, holes) { + let text = pieces[0]; + holes.forEach((hole, index) => { + let filled = Primitive_object.equal(hole.raw, true) ? hole.c : "(" + hole.c + ")"; + text = text + filled + pieces[index + 1 | 0]; + }); + return { + c: text + }; +} + +let __quoteCode = quote; + +let __quoteDecls = quote; + +let __quoteType = quote; + +let __quotePat = quote; + +let isSimple = (function (text) { + return /^[A-Za-z_][A-Za-z0-9_$.]*$/.test(text) +}); + +function atom(text) { + if (isSimple(text)) { + return text; + } else { + return "(" + text + ")"; + } +} + +function find(attrs, name) { + return attrs.find(attr => attr.name === name); +} + +function has(attrs, name) { + return find(attrs, name) !== undefined; +} + +function string(attrs, name) { + let match = find(attrs, name); + if (match !== undefined) { + return match.payload; + } +} + +let Attr = { + find: find, + has: has, + string: string +}; + +function handle(t, what) { + let id = t.id; + if (id !== undefined) { + return id; + } else { + return __rescript_macro.fail(what + ": this type was built by a macro, so the compiler has no information on it.", undefined); + } +} + +function info(t) { + return __rescript_macro.ask("info:" + handle(t, "Type.info").toString()); +} + +function name(t) { + return t.c; +} + +function companion(t, name) { + return Primitive_option.fromNullable(__rescript_macro.ask("companion:" + handle(t, "Type.companion").toString() + ":" + name)); +} + +function attrText(attrs) { + return attrs.map(attr => { + let payload = attr.payload; + if (payload !== undefined) { + return "@" + attr.name + "(" + JSON.stringify(payload) + ") "; + } else { + return "@" + attr.name + " "; + } + }).join(""); +} + +function fieldText(field) { + return attrText(field.attrs) + ( + field.jsName !== field.name ? "@as(" + JSON.stringify(field.jsName) + ") " : "" + ) + ( + field.mutable_ ? "mutable " : "" + ) + field.name + ( + field.optional ? "?: " : ": " + ) + field.typ.c; +} + +function record(fields) { + return make("{" + fields.map(fieldText).join(", ") + "}"); +} + +function variant(constructors) { + return make(constructors.map(c => "| " + attrText(c.attrs) + ( + c.jsName !== c.name ? "@as(" + JSON.stringify(c.jsName) + ") " : "" + ) + c.name + ( + c.fields.length !== 0 ? "({" + c.fields.map(fieldText).join(", ") + "})" : ( + c.args.length !== 0 ? "(" + c.args.map(source).join(", ") + ")" : "" + ) + )).join(" ")); +} + +function field(name, typ) { + return { + name: name, + jsName: name, + typ: typ, + optional: false, + mutable_: false, + attrs: [] + }; +} + +function constructor(name) { + return { + name: name, + jsName: name, + args: [], + fields: [], + attrs: [] + }; +} + +let Type = { + Classify: Stdlib_Type.Classify, + handle: handle, + info: info, + name: name, + companion: companion, + attrText: attrText, + fieldText: fieldText, + record: record, + variant: variant, + field: field, + constructor: constructor +}; + +function string$1(value) { + return make(JSON.stringify(value)); +} + +function int(value) { + return make(value.toString()); +} + +function float(value) { + let text = value.toString(); + return make(text.includes(".") || text.includes("e") ? text : text + "."); +} + +function bool(value) { + return make(value ? "true" : "false"); +} + +let unit = { + c: "()" +}; + +function print(value) { + return value.c; +} + +let raw = make; + +let ident = make; + +function field$1(value, name) { + return make(atom(value.c) + "." + name); +} + +function array(items) { + return make("[" + items.map(source).join(", ") + "]"); +} + +function tuple(items) { + return make("(" + items.map(source).join(", ") + ")"); +} + +function record$1(fields) { + return make("{" + fields.map(param => param[0] + ": " + param[1].c).join(", ") + "}"); +} + +function call(f, args) { + return make(atom(f.c) + "(" + args.map(source).join(", ") + ")"); +} + +function switch_(value, arms) { + return make("switch " + atom(value.c) + " {\n" + arms.map(param => "| " + param[0].c + " => " + param[1].c).join("\n") + "\n}"); +} + +function param(name, typ) { + return name + ": " + typ.c; +} + +function labelled(name, typ) { + return "~" + name + ": " + typ.c; +} + +function fn(params, body) { + return make("(" + params.join(", ") + ") => " + body.c); +} + +function decls(items) { + return make(items.map(source).join("\n")); +} + +let Code = { + string: string$1, + int: int, + float: float, + bool: bool, + unit: unit, + print: print, + raw: raw, + ident: ident, + field: field$1, + array: array, + tuple: tuple, + record: record$1, + call: call, + switch_: switch_, + param: param, + labelled: labelled, + fn: fn, + decls: decls +}; + +let $$var = make; + +let any = { + c: "_" +}; + +function string$2(value) { + return make(JSON.stringify(value)); +} + +function int$1(value) { + return make(value.toString()); +} + +function constructor$1(c) { + let typed = (name, typ) => ({ + c: name, + t: typ + }); + if (c.fields.length !== 0) { + let names = c.fields.map((f, i) => f.name + "$" + i.toString()); + return [ + make(c.name + "({" + c.fields.map((f, i) => f.name + ": " + names[i]).join(", ") + "})"), + c.fields.map((f, i) => typed(names[i], f.typ)) + ]; + } + if (c.args.length === 0) { + return [ + make(c.name), + [] + ]; + } + let names$1 = c.args.map((param, i) => "arg$" + i.toString()); + return [ + make(c.name + "(" + names$1.join(", ") + ")"), + c.args.map((typ, i) => typed(names$1[i], typ)) + ]; +} + +let Pat = { + $$var: $$var, + any: any, + string: string$2, + int: int$1, + constructor: constructor$1 +}; + +let Decl = {}; + +exports.make = make; +exports.source = source; +exports.error = error; +exports.errorAt = errorAt; +exports.typeOf = typeOf; +exports.expected = expected; +exports.readFile = readFile; +exports.env = env; +exports.__holeItem = __holeItem; +exports.quote = quote; +exports.__quoteCode = __quoteCode; +exports.__quoteDecls = __quoteDecls; +exports.__quoteType = __quoteType; +exports.__quotePat = __quotePat; +exports.isSimple = isSimple; +exports.atom = atom; +exports.Attr = Attr; +exports.Type = Type; +exports.Code = Code; +exports.Pat = Pat; +exports.Decl = Decl; +/* No side effect */ diff --git a/packages/artifacts.json b/packages/artifacts.json index 27bf1b94b4..1f6f411f5c 100644 --- a/packages/artifacts.json +++ b/packages/artifacts.json @@ -22,6 +22,7 @@ "lib/es6/JsxDOM.mjs", "lib/es6/JsxDOMStyle.mjs", "lib/es6/JsxEvent.mjs", + "lib/es6/Macro.mjs", "lib/es6/Obj.mjs", "lib/es6/Pervasives.mjs", "lib/es6/Primitive_array.mjs", @@ -127,6 +128,7 @@ "lib/js/JsxDOM.cjs", "lib/js/JsxDOMStyle.cjs", "lib/js/JsxEvent.cjs", + "lib/js/Macro.cjs", "lib/js/Obj.cjs", "lib/js/Pervasives.cjs", "lib/js/Primitive_array.cjs", @@ -253,6 +255,10 @@ "lib/ocaml/JsxEvent.cmj", "lib/ocaml/JsxEvent.cmt", "lib/ocaml/JsxEvent.res", + "lib/ocaml/Macro.cmi", + "lib/ocaml/Macro.cmj", + "lib/ocaml/Macro.cmt", + "lib/ocaml/Macro.res", "lib/ocaml/Obj.cmi", "lib/ocaml/Obj.cmj", "lib/ocaml/Obj.cmt", diff --git a/playground/examples/comptime/Main.res b/playground/examples/comptime/Main.res new file mode 100644 index 0000000000..53092e30ba --- /dev/null +++ b/playground/examples/comptime/Main.res @@ -0,0 +1,8 @@ +// The JavaScript output has the numbers, and no import of Sieve. +let primes = %comptime(Sieve.primesBelow(60)) +let fib25 = %comptime(Sieve.fib(25)) +let banner = %comptime(String.repeat("=", 20) ++ " primes " ++ String.repeat("=", 20)) + +Console.log(banner) +Console.log(primes) +Console.log(fib25) diff --git a/playground/examples/comptime/Sieve.res b/playground/examples/comptime/Sieve.res new file mode 100644 index 0000000000..6e0350eb25 --- /dev/null +++ b/playground/examples/comptime/Sieve.res @@ -0,0 +1,18 @@ +// Ordinary code: nothing here is a macro. +let primesBelow = (limit: int): array => { + let composite = Array.make(~length=limit, false) + let primes = [] + for n in 2 to limit - 1 { + if !(composite->Array.getUnsafe(n)) { + primes->Array.push(n) + let multiple = ref(n * n) + while multiple.contents < limit { + composite->Array.setUnsafe(multiple.contents, true) + multiple := multiple.contents + n + } + } + } + primes +} + +let rec fib = n => n < 2 ? n : fib(n - 1) + fib(n - 2) diff --git a/playground/examples/debug/Debug.res b/playground/examples/debug/Debug.res new file mode 100644 index 0000000000..126ad80174 --- /dev/null +++ b/playground/examples/debug/Debug.res @@ -0,0 +1,20 @@ +open Macro + +// A macro is a function the compiler runs while it compiles another file. +// `e` is the code of the argument, not its value. The quote %code(...) is +// the code the macro returns; ${...} is a hole in it. +@macro +let log = (e: code<'a>): code<'a> => + %code({ + let value = ${e} + Console.log2(${Code.string(Code.print(e) ++ " =")}, value) + value + }) + +@macro +let check = (condition: code): code => + %code( + if !${condition} { + Console.error(${Code.string("Check failed: " ++ Code.print(condition))}) + } + ) diff --git a/playground/examples/debug/Main.res b/playground/examples/debug/Main.res new file mode 100644 index 0000000000..89ffe2a59b --- /dev/null +++ b/playground/examples/debug/Main.res @@ -0,0 +1,7 @@ +let price = 12.5 +let quantity = 3 + +let total = %Debug.log(price *. Int.toFloat(quantity)) +let label = %Debug.log(quantity > 2 ? "bulk" : "single") + +%Debug.check(total < 30.0) diff --git a/playground/examples/derive/Enum.res b/playground/examples/derive/Enum.res new file mode 100644 index 0000000000..dd1ca08aeb --- /dev/null +++ b/playground/examples/derive/Enum.res @@ -0,0 +1,33 @@ +open Macro + +// A macro attached to a type receives the checked declaration and returns +// declarations, which are added after the type. +@macro +let derive = (t: Type.decl): decls => + switch Type.info(t.typ) { + | Variant({constructors}) => + constructors->Array.forEach(c => + if c.args->Array.length > 0 || c.fields->Array.length > 0 { + error(`Enum.derive: the constructor ${c.name} has arguments`) + } + ) + let label = (c: Type.constructor) => c.attrs->Attr.string("Enum.label")->Option.getOr(c.jsName) + let value = (c: Type.constructor): code => Code.ident(c.name) + + let toString = Code.switch_( + %code(value), + constructors->Array.map(c => { + let (pattern, _) = Pat.constructor(c) + (pattern, Code.string(label(c))) + }), + ) + let known = constructors->Array.map(c => (Pat.string(label(c)), %code(Some(${value(c)})))) + let fromString = Code.switch_(%code(text), [...known, (Pat.any, %code(None))]) + + %code( + let ${Pat.var(t.name ++ "ToString")} = (value: ${t.typ}): string => ${toString} + let ${Pat.var(t.name ++ "FromString")} = (text: string): option<${t.typ}> => ${fromString} + let ${Pat.var(t.name ++ "Values")}: array<${t.typ}> = ${Code.array(constructors->Array.map(value))} + ) + | _ => error("Enum.derive needs a variant type") + } diff --git a/playground/examples/derive/Main.res b/playground/examples/derive/Main.res new file mode 100644 index 0000000000..512903d77c --- /dev/null +++ b/playground/examples/derive/Main.res @@ -0,0 +1,9 @@ +@Enum.derive +type color = + | Red + | Green + | @Enum.label("navy blue") Blue + +Console.log(colorValues->Array.map(colorToString)) +Console.log(colorFromString("navy blue") == Some(Blue)) +Console.log(colorFromString("purple")) diff --git a/playground/examples/files/I18n.res b/playground/examples/files/I18n.res new file mode 100644 index 0000000000..23b4c1f654 --- /dev/null +++ b/playground/examples/files/I18n.res @@ -0,0 +1,31 @@ +open Macro + +// Macro.readFile reads a file of the project while compiling. The build +// knows the macro depends on it. +let messages = () => + switch JSON.parseOrThrow(readFile("en.json")) { + | Object(messages) => messages + | _ => error("en.json has to be an object") + } + +// "Hello {name}" as ["Hello ", "name", ""]: text and placeholders in turn. +let pieces = (text: string) => text->String.splitByRegExp(/[{}]/)->Array.map(piece => piece->Option.getOr("")) + +@macro +let t = (key: string): code<'a> => + switch messages()->Dict.get(key) { + | Some(String(text)) => + let pieces = pieces(text) + let names = pieces->Array.filterWithIndex((_, i) => mod(i, 2) == 1) + let parts = + pieces->Array.mapWithIndex((piece, i) => mod(i, 2) == 1 ? Code.ident(piece) : Code.string(piece)) + let body = parts->Array.reduce(%code(""), (text, part) => %code(${text} ++ ${part})) + // A message without placeholders is a string, one with placeholders a + // function with a labelled argument for each. + names->Array.length == 0 + ? Code.string(text) + : Code.fn(names->Array.map(name => Code.labelled(name, %type(string))), body) + | _ => + let known = messages()->Dict.keysToArray->Array.join(", ") + error(`There is no message "${key}" in en.json. It has: ${known}`) + } diff --git a/playground/examples/files/Main.res b/playground/examples/files/Main.res new file mode 100644 index 0000000000..9953c89ed4 --- /dev/null +++ b/playground/examples/files/Main.res @@ -0,0 +1,8 @@ +let title: string = %I18n.t("title") +let greet = %I18n.t("greeting") + +Console.log(title) +Console.log(greet(~name="Alice", ~count="3")) + +// A key that is not in en.json does not compile: +// let oops = %I18n.t("goodbye") diff --git a/playground/examples/files/en.json b/playground/examples/files/en.json new file mode 100644 index 0000000000..5174679aaa --- /dev/null +++ b/playground/examples/files/en.json @@ -0,0 +1,5 @@ +{ + "title": "Inbox", + "greeting": "Hello {name}, you have {count} new messages.", + "empty": "Nothing to read." +} diff --git a/playground/examples/index.json b/playground/examples/index.json new file mode 100644 index 0000000000..87c28e2406 --- /dev/null +++ b/playground/examples/index.json @@ -0,0 +1,85 @@ +[ + { + "id": "debug", + "title": "Expression macro", + "summary": "%Debug.log(expr) prints the source of an expression next to its value.", + "files": [ + "Debug.res", + "Main.res" + ] + }, + { + "id": "json", + "title": "Generic function: JSON encoder", + "summary": "Json.encode is called like a function. The compiler makes one encoder per type it is used at.", + "files": [ + "Json.res", + "Main.res" + ] + }, + { + "id": "derive", + "title": "Derive: declarations from a type", + "summary": "@Enum.derive on a variant adds toString, fromString and the list of all values.", + "files": [ + "Enum.res", + "Main.res" + ] + }, + { + "id": "lens", + "title": "Derive: lenses for a record", + "summary": "@Lens.derive adds a getter and setter pair per field, with the field's type.", + "files": [ + "Lens.res", + "Main.res" + ] + }, + { + "id": "types", + "title": "Type macro", + "summary": "%Partial.t(user) is the record type user with every field optional.", + "files": [ + "Partial.res", + "Main.res" + ] + }, + { + "id": "files", + "title": "Reading a file at compile time", + "summary": "%I18n.t(key) reads en.json while compiling: a missing key is a compile error, a placeholder an argument.", + "files": [ + "I18n.res", + "en.json", + "Main.res" + ] + }, + { + "id": "comptime", + "title": "%comptime: compute now", + "summary": "%comptime(expr) runs an expression while compiling and leaves its value in the output.", + "files": [ + "Sieve.res", + "Main.res" + ] + }, + { + "id": "staged", + "title": "Compile-time arguments", + "summary": "Power.pow(x, 3): x is code, 3 is a value the macro computes with. The loop runs in the compiler.", + "files": [ + "Power.res", + "Main.res" + ] + }, + { + "id": "items", + "title": "Macros on let and module", + "summary": "@Trace.calls wraps a function; %Units.table generates the contents of a module.", + "files": [ + "Trace.res", + "Units.res", + "Main.res" + ] + } +] diff --git a/playground/examples/items/Main.res b/playground/examples/items/Main.res new file mode 100644 index 0000000000..26574a0fc5 --- /dev/null +++ b/playground/examples/items/Main.res @@ -0,0 +1,7 @@ +module Length = %Units.table("meters", [("feet", 0.3048), ("miles", 1609.344)]) + +@Trace.calls +let marathon = (miles: float) => Length.milesToMeters(miles) /. 1000.0 + +Console.log(marathon(26.219)) +Console.log(Length.metersToFeet(100.0)) diff --git a/playground/examples/items/Trace.res b/playground/examples/items/Trace.res new file mode 100644 index 0000000000..0da05b0815 --- /dev/null +++ b/playground/examples/items/Trace.res @@ -0,0 +1,13 @@ +open Macro + +let wrap = (name: string, f: 'a => 'b): ('a => 'b) => + argument => { + Console.log2("call", name) + f(argument) + } + +// A macro attached to a let receives the binding before it is type +// checked, and returns what replaces it. +@macro +let calls = (binding: Decl.value): decls => + %code(let ${binding.pat} = Trace.wrap(${Code.string(binding.name)}, ${binding.expr})) diff --git a/playground/examples/items/Units.res b/playground/examples/items/Units.res new file mode 100644 index 0000000000..07bca72e10 --- /dev/null +++ b/playground/examples/items/Units.res @@ -0,0 +1,17 @@ +open Macro + +let capitalize = (text: string) => + String.toUpperCase(String.charAt(text, 0)) ++ String.slice(text, ~start=1) + +// A macro can return any number of declarations: here two conversion +// functions per unit. Used as `module Length = %Units.table(...)`. +@macro +let table = (base: string, units: array<(string, float)>): decls => + Code.decls( + units->Array.map(((unit, factor)) => + %code( + let ${Pat.var(unit ++ "To" ++ capitalize(base))} = (value: float) => value *. ${Code.float(factor)} + let ${Pat.var(base ++ "To" ++ capitalize(unit))} = (value: float) => value /. ${Code.float(factor)} + ) + ), + ) diff --git a/playground/examples/json/Json.res b/playground/examples/json/Json.res new file mode 100644 index 0000000000..8cd823d91e --- /dev/null +++ b/playground/examples/json/Json.res @@ -0,0 +1,51 @@ +open Macro + +// A @generic is called like a function: Json.encode(user). When the type +// of the argument is known, the compiler runs it with that type and makes +// a function of the result: one per type, shared by all the calls. +@generic +let encode = (value: code<'a>): code => + switch Type.info(typeOf(value)) { + | String => %code(JSON.Encode.string(${value})) + | Int => %code(JSON.Encode.int(${value})) + | Float => %code(JSON.Encode.float(${value})) + | Bool => %code(JSON.Encode.bool(${value})) + | Option(_) => + %code( + switch ${value} { + | Some(v) => encode(v) + | None => JSON.Encode.null + } + ) + | Array(_) => %code(JSON.Encode.array(${value}->Array.map(v => encode(v)))) + | Record({fields}) => + let entries = fields->Array.map(f => { + // @Json.key("...") on a field renames it. + let key = f.attrs->Attr.string("Json.key")->Option.getOr(f.jsName) + %code((${Code.string(key)}, encode(${value->Code.field(f.name)}))) + }) + %code(JSON.Encode.object(Dict.fromArray(${Code.array(entries)}))) + | Variant({constructors}) => + Code.switch_( + value, + constructors->Array.map(c => { + let (pattern, args) = Pat.constructor(c) + let fields = args->Array.mapWithIndex((arg, i) => { + let key = switch c.fields[i] { + | Some(field) => field.name + | None => "_" ++ Int.toString(i) + } + %code((${Code.string(key)}, encode(${arg}))) + }) + let tag = %code(("tag", JSON.Encode.string(${Code.string(c.name)}))) + (pattern, %code(JSON.Encode.object(Dict.fromArray(${Code.array([tag, ...fields])})))) + }), + ) + | Abstract({name}) => + // A type from elsewhere says how it is encoded with a toJson next to it. + switch Type.companion(typeOf(value), "toJson") { + | Some(toJson) => %code(${toJson}(${value})) + | None => error(`${name} is abstract and its module has no toJson`) + } + | _ => error(`Json.encode cannot encode the type ${Type.name(typeOf(value))}`) + } diff --git a/playground/examples/json/Main.res b/playground/examples/json/Main.res new file mode 100644 index 0000000000..c7ae318b11 --- /dev/null +++ b/playground/examples/json/Main.res @@ -0,0 +1,29 @@ +type shape = + | Circle({radius: float}) + | Rect({width: float, height: float}) + | Point + +type user = { + name: string, + @Json.key("user_age") age: int, + email: option, + tags: array, + avatar: shape, +} + +let alice = { + name: "Alice", + age: 30, + email: None, + tags: ["admin", "staff"], + avatar: Circle({radius: 2.5}), +} + +Console.log(JSON.stringify(Json.encode(alice), ~space=2)) + +// The type can come from inference: nothing in the callback says `user`. +let team = [alice, {...alice, name: "Bob", avatar: Point}] +Console.log(team->Array.map(member => JSON.stringify(Json.encode(member.avatar)))) + +// A type the macro rejects is a compile error at the call: +// let bad = Json.encode((x: int) => x + 1) diff --git a/playground/examples/lens/Lens.res b/playground/examples/lens/Lens.res new file mode 100644 index 0000000000..9053b42440 --- /dev/null +++ b/playground/examples/lens/Lens.res @@ -0,0 +1,26 @@ +open Macro + +type t<'record, 'field> = { + get: 'record => 'field, + set: ('record, 'field) => 'record, +} + +let update = (record, lens, f) => lens.set(record, f(lens.get(record))) + +@macro +let derive = (t: Type.decl): decls => + switch Type.info(t.typ) { + | Record({fields}) => + Code.decls( + fields->Array.map(f => { + let name = t.name ++ "_" ++ f.name + %code( + let ${Pat.var(name)}: Lens.t<${t.typ}, ${f.typ}> = { + get: record => ${Code.field(%code(record), f.name)}, + set: (record, value) => ${Code.raw(`{...record, ${f.name}: value}`)}, + } + ) + }), + ) + | _ => error("Lens.derive needs a record type") + } diff --git a/playground/examples/lens/Main.res b/playground/examples/lens/Main.res new file mode 100644 index 0000000000..57e4a623cf --- /dev/null +++ b/playground/examples/lens/Main.res @@ -0,0 +1,8 @@ +@Lens.derive +type point = {x: int, y: int, label: string} + +let origin = {x: 0, y: 0, label: "origin"} + +let moved = origin->Lens.update(point_x, x => x + 10)->Lens.update(point_label, String.toUpperCase) + +Console.log(moved) diff --git a/playground/examples/staged/Main.res b/playground/examples/staged/Main.res new file mode 100644 index 0000000000..a37d324d55 --- /dev/null +++ b/playground/examples/staged/Main.res @@ -0,0 +1,5 @@ +let cube = x => Power.pow(x, 3) +let tenth = x => Power.pow(x, 10) + +Console.log(cube(2.0)) +Console.log(tenth(2.0)) diff --git a/playground/examples/staged/Power.res b/playground/examples/staged/Power.res new file mode 100644 index 0000000000..3192d92e82 --- /dev/null +++ b/playground/examples/staged/Power.res @@ -0,0 +1,17 @@ +open Macro + +// The type of a parameter says when it exists. `base` is code: the +// macro gets the code of the argument. `n` is an int: the macro gets the +// number, so the call has to pass a literal. +@generic +let rec pow = (base: code, n: int): code => + if n == 0 { + %code(1.0) + } else if mod(n, 2) == 0 { + %code({ + let half = ${pow(base, n / 2)} + half *. half + }) + } else { + %code(${base} *. ${pow(base, n - 1)}) + } diff --git a/playground/examples/types/Main.res b/playground/examples/types/Main.res new file mode 100644 index 0000000000..4395f13768 --- /dev/null +++ b/playground/examples/types/Main.res @@ -0,0 +1,13 @@ +type user = {name: string, age: int, email: string} + +type userPatch = %Partial.t(user) + +let apply = (user: user, patch: userPatch): user => { + name: patch.name->Option.getOr(user.name), + age: patch.age->Option.getOr(user.age), + email: patch.email->Option.getOr(user.email), +} + +let alice: user = {name: "Alice", age: 30, email: "alice@example.com"} + +Console.log(alice->apply({age: 31})) diff --git a/playground/examples/types/Partial.res b/playground/examples/types/Partial.res new file mode 100644 index 0000000000..a0722961a5 --- /dev/null +++ b/playground/examples/types/Partial.res @@ -0,0 +1,9 @@ +open Macro + +// A macro in a type position takes types and returns a type. +@macro +let t = (source: typ): typ => + switch Type.info(source) { + | Record({fields}) => Type.record(fields->Array.map(f => {...f, optional: true})) + | _ => error(`Partial.t needs a record type, and ${Type.name(source)} is not one`) + } diff --git a/rewatch/Cargo.lock b/rewatch/Cargo.lock index e798ba62e6..3643b1fd47 100644 --- a/rewatch/Cargo.lock +++ b/rewatch/Cargo.lock @@ -1887,6 +1887,7 @@ dependencies = [ "oxc_parser", "oxc_span", "rayon", + "rquickjs", "serde", "serde_json", "smallvec", @@ -1896,6 +1897,33 @@ dependencies = [ "typed-arena", ] +[[package]] +name = "rquickjs" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c5227859c4dfc83f428e58f9569bf439e628c8d139020e7faff437e6f5abaa0" +dependencies = [ + "rquickjs-core", +] + +[[package]] +name = "rquickjs-core" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e82e0ca83028ad5b533b53b96c395bbaab905a5774de4aaf1004eeacafa3d85d" +dependencies = [ + "rquickjs-sys", +] + +[[package]] +name = "rquickjs-sys" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fed0097b0b4fbb2a87f6dd3b995a7c64ca56de30007eb7e867dfdfc78324ba5" +dependencies = [ + "cc", +] + [[package]] name = "rusqlite" version = "0.32.1" From e08865fff76af16a20db7f37b261bb3e31d85c56 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:03:48 +0100 Subject: [PATCH 07/38] macros: one instance per type in a file An instance that an earlier top-level item turns out to need moves to that item's group, together with the instances it calls, instead of being generated a second time. Macro errors get the type checker's header. Co-authored-by: Jaap Frolich Session: https://jakes-mac-mini.tail23a77e.ts.net:8443/session/os-01a1ca09-2757-709a-bbb1-e57ccc4d104f Signed-off-by: Jaap Frolich --- compiler-rust/src/macros/discover.rs | 209 +++++++++++++++++++------ compiler-rust/src/macros/expand.rs | 9 +- compiler-rust/src/parser/code_frame.rs | 14 +- compiler-rust/tests/macros.rs | 51 ++++++ 4 files changed, 234 insertions(+), 49 deletions(-) diff --git a/compiler-rust/src/macros/discover.rs b/compiler-rust/src/macros/discover.rs index 3ce3c8ef8b..b4cc4a193f 100644 --- a/compiler-rust/src/macros/discover.rs +++ b/compiler-rust/src/macros/discover.rs @@ -12,7 +12,7 @@ //! [`TypeCheckContext::macro_expansion_required`] set, which tells the driver //! to expand the file first. -use std::collections::{HashMap, HashSet}; +use std::collections::{BTreeMap, HashMap, HashSet, VecDeque}; use std::sync::Arc; use serde_json::{Value, json}; @@ -71,27 +71,19 @@ pub struct ComptimeSite { /// A generated function: `Json.encode` at the type `user`. struct Instance { name: String, - /// Original offset of the top-level item the instance was generated - /// for. Items at or after that offset can call it. + /// Original offset of the first top-level item that calls the instance: + /// the instance is defined in the group before that item. ordinal: u32, } /// The instances of a file, kept from pass to pass. #[derive(Default)] pub struct InstanceTable { - by_key: HashMap>, + by_key: HashMap, names: HashSet, } impl InstanceTable { - fn find(&self, key: &str, ordinal: u32) -> Option<&str> { - self.by_key - .get(key)? - .iter() - .find(|instance| instance.ordinal <= ordinal) - .map(|instance| instance.name.as_str()) - } - fn add(&mut self, key: String, base: &str, ordinal: u32) -> String { let mut name = base.to_string(); let mut counter = 1; @@ -100,14 +92,35 @@ impl InstanceTable { name = format!("{base}${counter}"); } self.names.insert(name.clone()); - self.by_key.entry(key).or_default().push(Instance { - name: name.clone(), - ordinal, - }); + self.by_key.insert( + key, + Instance { + name: name.clone(), + ordinal, + }, + ); name } } +/// A group of instances that is in the text: a `let rec` an earlier pass +/// added before the top-level item that needed them. +struct Group { + /// The range of the whole item. + item: (u32, u32), + /// Name and range of each function, `name = (...) => body`. + functions: Vec<(String, u32, u32)>, +} + +const GROUP_SEPARATOR: &str = "\nand "; + +fn render_group(functions: &[String]) -> String { + format!( + "@{INSTANCES_ATTRIBUTE} @warning(\"-39\") let rec {}", + functions.join(GROUP_SEPARATOR) + ) +} + #[derive(Clone, Copy, PartialEq, Eq, Debug)] enum ParamKind { /// `code<'a>`: the argument's syntax. @@ -290,11 +303,14 @@ pub struct Discovery { item_pending: bool, /// The application whose function is being typed. apply: Option<(LocIdx, PendingCall)>, - /// End of the instance group already in the text, by ordinal. - group_ends: HashMap, - /// Instances added by this pass that start a new group, by the offset of - /// the item they go before. - new_groups: Vec<(u32, Vec)>, + /// The instance groups in the text, by ordinal. + groups: BTreeMap, + /// Instances this pass generated: the ordinal of the item that needs + /// the instance, the offset of that item, and the function. + added: Vec<(u32, u32, String)>, + /// Instances an earlier item turned out to need as well: name, ordinal + /// and offset of that item. They move to its group. + moved: Vec<(String, u32, u32)>, } /// What a discovery pass found. @@ -327,20 +343,79 @@ impl Discovery { item_start: 0, item_pending: false, apply: None, - group_ends: HashMap::new(), - new_groups: Vec::new(), + groups: BTreeMap::new(), + added: Vec::new(), + moved: Vec::new(), } } pub fn finish(mut self) -> PassResult { - for (at, functions) in std::mem::take(&mut self.new_groups) { - self.edits.push(Edit::insert( - at, - format!( - "@{INSTANCES_ATTRIBUTE} @warning(\"-39\") let rec {}\n", - functions.join("\nand ") - ), - )); + // Where each instance that moves goes: the earliest item that needs + // it. What a moved function calls moves with it. + let mut targets: BTreeMap = BTreeMap::new(); + let mut queue: VecDeque<(String, u32, u32)> = std::mem::take(&mut self.moved).into(); + while let Some((name, ordinal, at)) = queue.pop_front() { + let Some((home, function)) = self.function_in_text(&name) else { + continue; + }; + if home <= ordinal || targets.get(&name).is_some_and(|(target, _)| *target <= ordinal) { + continue; + } + targets.insert(name, (ordinal, at)); + for word in function.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '$')) { + if word.contains('$') && self.instances.names.contains(word) { + queue.push_back((word.to_string(), ordinal, at)); + } + } + } + for instance in self.instances.by_key.values_mut() { + if let Some((ordinal, _)) = targets.get(&instance.name) { + instance.ordinal = instance.ordinal.min(*ordinal); + } + } + + // What each group gains, by ordinal: the offset to start a new group + // at, and the functions. + let mut gains: BTreeMap)> = BTreeMap::new(); + for (name, (ordinal, at)) in &targets { + if let Some((_, function)) = self.function_in_text(name) { + gains.entry(*ordinal).or_insert((*at, Vec::new())).1.push(function); + } + } + let removed: HashSet<&String> = targets.keys().collect(); + for (ordinal, at, function) in std::mem::take(&mut self.added) { + gains.entry(ordinal).or_insert((at, Vec::new())).1.push(function); + } + for (ordinal, group) in &self.groups { + let gained = gains.remove(ordinal).map(|(_, functions)| functions).unwrap_or_default(); + let loses = group.functions.iter().any(|(name, _, _)| removed.contains(name)); + if !loses { + if !gained.is_empty() { + let text: String = gained + .iter() + .map(|function| format!("{GROUP_SEPARATOR}{function}")) + .collect(); + self.edits.push(Edit::insert(group.item.1, text)); + } + continue; + } + let mut functions: Vec = group + .functions + .iter() + .filter(|(name, _, _)| !removed.contains(name)) + .map(|(_, start, end)| self.text.slice(*start, *end).to_string()) + .collect(); + functions.extend(gained); + let text = if functions.is_empty() { + String::new() + } else { + render_group(&functions) + }; + self.edits.push(Edit::replace(group.item.0, group.item.1, text)); + } + for (_, (at, functions)) in gains { + self.edits + .push(Edit::insert(at, format!("{}\n", render_group(&functions)))); } PassResult { edits: self.edits, @@ -359,20 +434,32 @@ impl Discovery { }); } - fn add_instance(&mut self, function: String) { + /// The group an instance is defined in, and its text. + fn function_in_text(&self, name: &str) -> Option<(u32, String)> { + self.groups.iter().find_map(|(home, group)| { + group + .functions + .iter() + .find(|(function, _, _)| function == name) + .map(|(_, start, end)| (*home, self.text.slice(*start, *end).to_string())) + }) + } + + /// The name of the instance for `key`, if there is one. When it is + /// defined for an item after the one being typed, it moves here. + fn instance(&mut self, key: &str) -> Option { let ordinal = self.text.origin(self.item_start); - if let Some(end) = self.group_ends.get(&ordinal).copied() { - self.edits.push(Edit::insert(end, format!("\nand {function}"))); - return; - } - match self - .new_groups - .iter_mut() - .find(|(at, _)| *at == self.item_start) - { - Some((_, functions)) => functions.push(function), - None => self.new_groups.push((self.item_start, vec![function])), + let instance = self.instances.by_key.get_mut(key)?; + if instance.ordinal > ordinal { + instance.ordinal = ordinal; + self.moved.push((instance.name.clone(), ordinal, self.item_start)); } + Some(instance.name.clone()) + } + + fn add_instance(&mut self, function: String) { + let ordinal = self.text.origin(self.item_start); + self.added.push((ordinal, self.item_start, function)); } /// Run a macro: ask the engine, answer its questions, ask again. @@ -1000,9 +1087,37 @@ pub(crate) fn begin_item(tctx: &mut TypeCheckContext<'_>, item: &ParsedStructure discovery.item_start = start; discovery.item_pending = false; // An instance group that an earlier pass added. - if is_instance_group(arena, item) { + if is_instance_group(arena, item) + && let ParsedStructureItemDesc::Pstr_value((_, bindings)) = &item.pstr_desc + { + let bindings = arena.vb_list(*bindings); + let starts: Vec = bindings + .iter() + .map(|binding| range(arena, arena.get_pat(binding.pvb_pat).ppat_loc).0) + .collect(); + let functions = bindings + .iter() + .enumerate() + .filter_map(|(index, binding)| { + let PatternDesc::Ppat_var(name) = &arena.get_pat(binding.pvb_pat).ppat_desc else { + return None; + }; + // A function ends where the separator before the next starts. + let function_end = match starts.get(index + 1) { + Some(next) => next.saturating_sub(GROUP_SEPARATOR.len() as u32), + None => end, + }; + Some((arena.get_string(name.txt).to_string(), starts[index], function_end)) + }) + .collect(); let ordinal = discovery.text.origin(start); - discovery.group_ends.insert(ordinal, end); + discovery.groups.insert( + ordinal, + Group { + item: (start, end), + functions, + }, + ); } } @@ -1127,8 +1242,8 @@ fn resolve_generic(tctx: &mut TypeCheckContext<'_>, discovery: &mut Discovery, g let key = format!("{full_name}({})->{result}", key_parts.join(",")); let ordinal = discovery.text.origin(discovery.item_start); - let name = match discovery.instances.find(&key, ordinal) { - Some(name) => name.to_string(), + let name = match discovery.instance(&key) { + Some(name) => name, None => { let expected = reflect::type_ref(ctx, &mut table, ret); let request = json!({ diff --git a/compiler-rust/src/macros/expand.rs b/compiler-rust/src/macros/expand.rs index 91d2c54afd..da70b0ab0c 100644 --- a/compiler-rust/src/macros/expand.rs +++ b/compiler-rust/src/macros/expand.rs @@ -51,7 +51,14 @@ fn diagnostic( Position::new(crate::intern::StrIdx::from_raw(0), line, bol as i32, offset as i32) }; UserDiagnostic::new( - code_frame::format_error(filename, original, &position(start), &position(end), message), + code_frame::format_error_with_intro( + "We've found a bug for you!", + filename, + original, + &position(start), + &position(end), + message, + ), 2, ) .into() diff --git a/compiler-rust/src/parser/code_frame.rs b/compiler-rust/src/parser/code_frame.rs index 4fdfc2c291..cb388a36da 100644 --- a/compiler-rust/src/parser/code_frame.rs +++ b/compiler-rust/src/parser/code_frame.rs @@ -571,12 +571,24 @@ pub fn format_error( start_pos: &Position, end_pos: &Position, message: &str, +) -> String { + format_error_with_intro("Syntax error!", filename, src, start_pos, end_pos, message) +} + +/// [`format_error`] with another header line than "Syntax error!". +pub fn format_error_with_intro( + intro: &str, + filename: &str, + src: &str, + start_pos: &Position, + end_pos: &Position, + message: &str, ) -> String { let mut result = String::new(); // Header (OCaml `Res_diagnostics_printing_utils` colors it like other errors). result.push_str("\n "); - result.push_str(&colorize_intro("Syntax error!", true)); + result.push_str(&colorize_intro(intro, true)); result.push('\n'); // Location diff --git a/compiler-rust/tests/macros.rs b/compiler-rust/tests/macros.rs index aa394fd3db..9084205ca8 100644 --- a/compiler-rust/tests/macros.rs +++ b/compiler-rust/tests/macros.rs @@ -544,3 +544,54 @@ fn compile_playground_examples() { } } } + +#[test] +fn an_instance_is_generated_once() { + let mut project = Project::new(); + compile_ok(&mut project, "Json.res", JSON); + let js = compile_ok( + &mut project, + "Twice.res", + r#" +type point = {x: float, y: float} +type line = {from: point, to: point} + +let a = (l: line) => Json.encode(l) +let b = (p: point) => Json.encode(p) +let c = (xs: array) => Json.encode(xs) +let d = (p: point, n: float) => (Json.encode(p), Json.encode(n)) +"#, + ); + let expanded = project.expanded.clone().unwrap(); + for name in ["encode$point", "encode$float", "encode$line", "encode$array_float"] { + assert_eq!(expanded.matches(&format!("{name} = (")).count(), 1, "{name}\n{expanded}"); + } + assert!(!expanded.contains("$2"), "{expanded}"); + assert_eq!(js.matches("function encode$point(").count(), 1, "{js}"); +} + +#[test] +fn an_instance_moves_to_the_first_item_that_needs_it() { + let mut project = Project::new(); + compile_ok(&mut project, "Json.res", JSON); + // `tree` is needed by the first item only through `forest`, which is + // found a pass after the second item made `encode$tree`. + let js = compile_ok( + &mut project, + "Forest.res", + r#" +type rec tree = {value: int, children: array} +type forest = {trees: array, name: option} + +let a = (f: forest) => Json.encode(f) +let b = (t: tree) => Json.encode(t) +"#, + ); + let expanded = project.expanded.clone().unwrap(); + for name in ["encode$tree", "encode$forest", "encode$int", "encode$array_tree"] { + assert_eq!(expanded.matches(&format!("{name} = (")).count(), 1, "{name}\n{expanded}"); + } + assert_eq!(js.matches("function encode$tree(").count(), 1, "{js}"); + // One group, before the first item. + assert_eq!(expanded.matches("@res.macroInstances").count(), 1, "{expanded}"); +} From 26d05b3bcad8c7ebb2e5f910de3e1670ada59485 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:08:27 +0100 Subject: [PATCH 08/38] macros: pattern position, submodules, and errors for misuse - %M.f(...) where a pattern is written, for a macro that returns pat. - A macro in a submodule: %Lib.Numbers.answer(). - A misuse that only expansion sees (a hole outside a quote, a macro of the wrong kind for its position) is reported at its place instead of as an unexpanded macro, and using a macro in the file that defines it says why that cannot work. Co-authored-by: Jaap Frolich Session: https://jakes-mac-mini.tail23a77e.ts.net:8443/session/os-01a1ca09-2757-709a-bbb1-e57ccc4d104f Signed-off-by: Jaap Frolich --- compiler-rust/src/macros/discover.rs | 116 +++++++++++++++++++----- compiler-rust/src/macros/host.js | 7 +- compiler-rust/src/types/typecore.rs | 7 +- compiler-rust/tests/macros.rs | 130 +++++++++++++++++++++++++++ 4 files changed, 236 insertions(+), 24 deletions(-) diff --git a/compiler-rust/src/macros/discover.rs b/compiler-rust/src/macros/discover.rs index b4cc4a193f..512554a970 100644 --- a/compiler-rust/src/macros/discover.rs +++ b/compiler-rust/src/macros/discover.rs @@ -618,6 +618,23 @@ fn pending(tctx: &mut TypeCheckContext<'_>, loc: LocIdx) -> TypeCoreError { error_at(loc, "(macro expansion pending)") } +/// Report a misuse of a macro that only a discovery pass sees: an ordinary +/// compilation stops at the macro before it gets this far. +fn fail(tctx: &mut TypeCheckContext<'_>, loc: LocIdx, message: impl Into) -> TypeCoreError { + let message = message.into(); + let at = range(tctx.arena, loc); + match &mut tctx.macro_mode { + MacroMode::Discover(discovery) => { + discovery.error(at, message); + pending(tctx, loc) + } + MacroMode::Off => error_at(loc, message), + } +} + +const HOLE_OUTSIDE_QUOTE: &str = + "A hole `${...}` can only be used inside a quote: %code(...), %type(...) or %pat(...)."; + fn discovering(tctx: &TypeCheckContext<'_>) -> bool { matches!(tctx.macro_mode, MacroMode::Discover(_)) } @@ -663,15 +680,12 @@ fn lookup_value( env.lookup_value_by_lid(&longident, tctx.arena, &mut tctx.persistent_env, tctx.type_ctx) } -/// `Json.encode` → (`Json`, `encode`): the module whose JavaScript the -/// engine loads and the export it calls. +/// `Json.encode` → (`Json`, `encode`): the file whose JavaScript the engine +/// loads, and the path of the macro in its exports (`Inner.encode` for a +/// macro in a submodule). fn split_macro_name(name: &str) -> (String, String) { - match name.rsplit_once('.') { - Some((module, value)) => (module.split('.').next().unwrap_or(module).to_string(), { - // A macro in a submodule is not reachable as an export by name. - let _ = module; - value.to_string() - }), + match name.split_once('.') { + Some((module, path)) => (module.to_string(), path.to_string()), None => (String::new(), name.to_string()), } } @@ -813,7 +827,21 @@ fn find_macro( name: &str, ) -> Result, TypeCoreError> { let Some((_, desc)) = lookup_value(tctx, env, name) else { - return Err(error_at(loc, format!("The macro `{name}` cannot be found."))); + let own_module = tctx + .persistent_env + .as_ref() + .and_then(|persistent_env| persistent_env.compiling_module_name()) + .is_some_and(|module| name.split('.').next() == Some(module)); + return Err(error_at( + loc, + if own_module { + format!( + "`{name}` is defined in this file. A macro cannot be used in the file that defines it: the compiler runs the compiled file." + ) + } else { + format!("The macro `{name}` cannot be found.") + }, + )); }; match macro_kind(&desc) { Some(_) => Ok(desc), @@ -877,12 +905,9 @@ pub(crate) fn expression_extension( return Some(Err(if !discovering(tctx) { required(tctx, loc) } else if is_hole { - error_at( - loc, - "A hole `${...}` can only be used inside a quote: %code(...), %type(...) or %pat(...).", - ) + fail(tctx, loc, HOLE_OUTSIDE_QUOTE) } else { - error_at(loc, format!("The quote `%{name}` needs a payload: `%{name}(...)`.")) + fail(tctx, loc, format!("The quote `%{name}` needs a payload: `%{name}(...)`.")) })); } if name == "comptime" { @@ -903,7 +928,8 @@ pub(crate) fn expression_extension( let (signature, _, result_type) = signature(ctx, macro_type); let at = range(tctx.arena, loc); if signature.result != ResultKind::Code { - return Some(Err(error_at( + return Some(Err(fail( + tctx, loc, format!("The macro `{name}` does not return an expression, so it cannot be used as one."), ))); @@ -945,7 +971,7 @@ fn comptime( } let expr_idx = match payload_expressions(tctx.arena, &extension.1, 1) { Ok(exprs) if exprs.len() == 1 => exprs[0], - _ => return Err(error_at(loc, "%comptime takes one expression: `%comptime(expr)`.")), + _ => return Err(fail(tctx, loc, "%comptime takes one expression: `%comptime(expr)`.")), }; let expr = tctx.arena.get_expr(expr_idx); let typed = crate::types::typecore::type_expect(tctx, env, expr, expected_ty, None)?; @@ -1306,6 +1332,51 @@ pub(crate) fn skips_failed_item(tctx: &TypeCheckContext<'_>) -> bool { matches!(&tctx.macro_mode, MacroMode::Discover(discovery) if discovery.depth == 0) } +/// An extension where a pattern is expected: `| %Http.status("ok") => ...`. +pub(crate) fn pattern_extension( + tctx: &mut TypeCheckContext<'_>, + env: &Env, + loc: LocIdx, + extension: &Extension, +) -> Option { + let name = tctx.arena.get_string(extension.0.txt).to_string(); + if name == HOLE_EXTENSION { + return Some(if discovering(tctx) { + fail(tctx, loc, HOLE_OUTSIDE_QUOTE) + } else { + required(tctx, loc) + }); + } + if !is_macro_name(&name) { + return None; + } + let desc = match find_macro(tctx, env, loc, &name) { + Ok(desc) => desc, + Err(error) => return Some(error), + }; + if !discovering(tctx) { + return Some(required(tctx, loc)); + } + let ctx = tctx.type_ctx; + let (signature, _, _) = signature(ctx, crate::types::instance(ctx, desc.val_type)); + if signature.result != ResultKind::Pat { + return Some(fail( + tctx, + loc, + format!("The macro `{name}` does not return a pattern (`pat`), so it cannot be used as one."), + )); + } + let at = range(tctx.arena, loc); + let mut table = TypeTable::default(); + with_discovery(tctx, |tctx, discovery| { + let args = call_arguments(tctx, env, discovery, &mut table, &name, &signature, &extension.1); + if let Some(code) = run_call(tctx, env, discovery, &mut table, at, &name, args, None) { + discovery.edits.push(Edit::replace(at.0, at.1, format!("({code})"))); + } + }); + Some(pending(tctx, loc)) +} + /// An extension where a type is expected: `type t = %Partial.t(user)`. pub(crate) fn type_extension( tctx: &mut TypeCheckContext<'_>, @@ -1316,7 +1387,7 @@ pub(crate) fn type_extension( let name = tctx.arena.get_string(extension.0.txt).to_string(); if name == HOLE_EXTENSION { return Some(if discovering(tctx) { - error_at(loc, "A hole `${...}` can only be used inside a quote: %code(...), %type(...) or %pat(...).") + fail(tctx, loc, HOLE_OUTSIDE_QUOTE) } else { required(tctx, loc) }); @@ -1334,7 +1405,8 @@ pub(crate) fn type_extension( let ctx = tctx.type_ctx; let (signature, _, _) = signature(ctx, crate::types::instance(ctx, desc.val_type)); if signature.result != ResultKind::Typ { - return Some(error_at( + return Some(fail( + tctx, loc, format!("The macro `{name}` does not return a type, so it cannot be used as one."), )); @@ -1418,7 +1490,8 @@ pub(crate) fn declarations_extension( let ctx = tctx.type_ctx; let (signature, _, _) = signature(ctx, crate::types::instance(ctx, desc.val_type)); if signature.result != ResultKind::Decls { - return Some(error_at( + return Some(fail( + tctx, loc, format!("The macro `{name}` does not return declarations (`decls`), so it cannot be used here."), )); @@ -1500,12 +1573,13 @@ pub(crate) fn value_item( return Some(required(tctx, loc)); } if bindings.len() != 1 { - return Some(error_at(attr_loc, format!("`@{name}` works on a `let` with one binding."))); + return Some(fail(tctx, attr_loc, format!("`@{name}` works on a `let` with one binding."))); } let ctx = tctx.type_ctx; let (signature, _, _) = signature(ctx, crate::types::instance(ctx, desc.val_type)); if signature.params != [ParamKind::Binding] || signature.result != ResultKind::Decls { - return Some(error_at( + return Some(fail( + tctx, attr_loc, format!("A macro on a `let` has the type `Decl.value => decls`, and `{name}` does not."), )); diff --git a/compiler-rust/src/macros/host.js b/compiler-rust/src/macros/host.js index 5e00937518..189acfc058 100644 --- a/compiler-rust/src/macros/host.js +++ b/compiler-rust/src/macros/host.js @@ -197,8 +197,11 @@ run(request.source, module); return JSON.stringify({ ok: reify(module.exports.value, request.shape) }); } - var exports = load(request.module); - var macro = exports[request.name]; + // `name` is a path in the module's exports: `Inner.encode` is a macro + // in a submodule. + var macro = request.name.split(".").reduce(function (value, key) { + return value === null || value === undefined ? undefined : value[key]; + }, load(request.module)); if (typeof macro !== "function") { throw { __macro_error: "`" + request.module + "." + request.name + "` is not a function, so it cannot run as a macro." }; } diff --git a/compiler-rust/src/types/typecore.rs b/compiler-rust/src/types/typecore.rs index 205e9f37e7..ed36660fd9 100644 --- a/compiler-rust/src/types/typecore.rs +++ b/compiler-rust/src/types/typecore.rs @@ -4994,7 +4994,12 @@ fn type_pattern_inner( Ok(result) } - PD::Ppat_extension(extension) => Err(builtin_extension_error(tctx.arena, extension)), + PD::Ppat_extension(extension) => { + if let Some(error) = crate::macros::discover::pattern_extension(tctx, env, loc, extension) { + return Err(error); + } + Err(builtin_extension_error(tctx.arena, extension)) + } } } diff --git a/compiler-rust/tests/macros.rs b/compiler-rust/tests/macros.rs index 9084205ca8..a0ab4ee9bc 100644 --- a/compiler-rust/tests/macros.rs +++ b/compiler-rust/tests/macros.rs @@ -595,3 +595,133 @@ let b = (t: tree) => Json.encode(t) // One group, before the first item. assert_eq!(expanded.matches("@res.macroInstances").count(), 1, "{expanded}"); } + +fn compile_err(project: &mut Project, filename: &str, source: &str) -> String { + match project.compile(filename, source) { + Ok(js) => panic!("{filename} compiled:\n{js}"), + Err(error) => { + println!("--- {filename}\n{error}"); + error + } + } +} + +#[test] +fn misuse_is_explained() { + let mut project = Project::new(); + compile_ok(&mut project, "Json.res", JSON); + compile_ok(&mut project, "Debug.res", DEBUG); + + let error = compile_err( + &mut project, + "Same.res", + "open Macro\n@macro\nlet one = (): code => %code(1)\nlet x = %Same.one()\n", + ); + assert!(error.contains("cannot be used in the file that defines it"), "{error}"); + assert!(error.contains("Same.res:4:9"), "{error}"); + + let error = compile_err(&mut project, "Unknown.res", "let x = %Nope.f(1)\n"); + assert!(error.contains("The macro `Nope.f` cannot be found."), "{error}"); + + let error = compile_err(&mut project, "Plain.res", "let x = %Stdlib.Int.toString(1)\n"); + assert!(error.contains("is not a macro"), "{error}"); + + let error = compile_err(&mut project, "Arity.res", "let x = %Debug.dbg\n"); + assert!(error.contains("takes 1 argument, and 0 are given"), "{error}"); + + let error = compile_err(&mut project, "Hole.res", "let x = ${1}\n"); + assert!(error.contains("can only be used inside a quote"), "{error}"); + assert!(error.contains("Hole.res:1:9"), "{error}"); + + let error = compile_err(&mut project, "Kind.res", "type t = %Debug.dbg(int)\n"); + assert!(error.contains("does not return a type"), "{error}"); + + // The generated code is type checked like written code. + let error = compile_err(&mut project, "TypeErr.res", "let x: string = %Debug.dbg(1 + 1)\n"); + assert!(error.contains("This has type: int"), "{error}"); +} + +#[test] +fn macro_code_has_no_clock_and_no_random_numbers() { + let mut project = Project::new(); + compile_ok( + &mut project, + "Rand.res", + "open Macro\n@macro\nlet r = (): code => Code.float(Math.random())\n@macro\nlet now = (): code => Code.float(Date.now())\n", + ); + let error = compile_err(&mut project, "UseRand.res", "let x = %Rand.r()\n"); + assert!(error.contains("Math.random is not available at compile time"), "{error}"); + let error = compile_err(&mut project, "UseNow.res", "let x = %Rand.now()\n"); + assert!(error.contains("Date.now is not available at compile time"), "{error}"); +} + +#[test] +fn generated_syntax_errors_show_the_generated_code() { + let mut project = Project::new(); + compile_ok( + &mut project, + "Bad.res", + "open Macro\n@macro\nlet bad = (): code => Code.raw(\"1 +\")\n", + ); + let error = compile_err(&mut project, "UseBad.res", "let x = %Bad.bad()\n"); + assert!(error.contains("A macro generated code with a syntax error"), "{error}"); + assert!(error.contains("let x = (1 +)"), "{error}"); +} + +#[test] +fn pattern_macro() { + let mut project = Project::new(); + compile_ok( + &mut project, + "Http.res", + r#" +open Macro + +@macro +let status = (name: string): pat => + switch name { + | "ok" => %pat(200 | 201 | 204) + | "missing" => Pat.int(404) + | _ => error(`Http.status: unknown status "${name}"`) + } +"#, + ); + let js = compile_ok( + &mut project, + "Handle.res", + r#" +let describe = code => + switch code { + | %Http.status("ok") => "fine" + | %Http.status("missing") => "not found" + | _ => "other" + } +"#, + ); + assert!(js.contains("404"), "{js}"); + assert!(js.contains("204"), "{js}"); +} + +#[test] +fn macro_in_a_submodule() { + let mut project = Project::new(); + compile_ok( + &mut project, + "Lib.res", + "open Macro\nmodule Numbers = {\n @macro\n let answer = (): code => %code(42)\n}\n", + ); + let js = compile_ok(&mut project, "UseLib.res", "let x = %Lib.Numbers.answer()\n"); + assert!(js.contains("42"), "{js}"); +} + +#[test] +fn generic_as_a_value_and_in_a_pipe() { + let mut project = Project::new(); + compile_ok(&mut project, "Json.res", JSON); + let js = compile_ok( + &mut project, + "Values.res", + "type p = {x: int}\nlet all = (ps: array

) => ps->Array.map(Json.encode)\nlet one = (p: p) => p->Json.encode\n", + ); + assert!(js.contains("ps.map(encode$p)"), "{js}"); +} From 54d451088a37f3e24036ae4244b1bafd5eba9b6f Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:14:44 +0100 Subject: [PATCH 09/38] macros: companion and expected-type tests, instance names without unit Co-authored-by: Jaap Frolich Session: https://jakes-mac-mini.tail23a77e.ts.net:8443/session/os-01a1ca09-2757-709a-bbb1-e57ccc4d104f Signed-off-by: Jaap Frolich --- compiler-rust/src/macros/discover.rs | 5 ++- compiler-rust/tests/macros.rs | 60 ++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 1 deletion(-) diff --git a/compiler-rust/src/macros/discover.rs b/compiler-rust/src/macros/discover.rs index 512554a970..06c76f0970 100644 --- a/compiler-rust/src/macros/discover.rs +++ b/compiler-rust/src/macros/discover.rs @@ -1224,7 +1224,10 @@ fn resolve_generic(tctx: &mut TypeCheckContext<'_>, discovery: &mut Discovery, g macro_args.push(code); params.push(format!("{param}: {printed}")); key_parts.push(printed.clone()); - name_parts.push(printed); + // A unit argument says nothing about the instance. + if printed != "unit" { + name_parts.push(printed); + } if let Some(call) = &generic.call && let Some((at, _)) = call.args.get(index) { diff --git a/compiler-rust/tests/macros.rs b/compiler-rust/tests/macros.rs index a0ab4ee9bc..f15d49220e 100644 --- a/compiler-rust/tests/macros.rs +++ b/compiler-rust/tests/macros.rs @@ -725,3 +725,63 @@ fn generic_as_a_value_and_in_a_pipe() { ); assert!(js.contains("ps.map(encode$p)"), "{js}"); } + +#[test] +fn companion_of_an_abstract_type() { + let mut project = Project::new(); + compile_ok(&mut project, "Json.res", JSON); + compile_ok( + &mut project, + "Money.res", + "type t\n@new external make: int => t = \"Money\"\nlet toJson = (_: t): JSON.t => JSON.Encode.string(\"money\")\n", + ); + let js = compile_ok( + &mut project, + "Invoice.res", + "type invoice = {id: string, total: Money.t}\nlet encode = (i: invoice) => Json.encode(i)\n", + ); + assert!(js.contains("Money.toJson(i.total)"), "{js}"); + assert!(project.expanded.as_deref().unwrap().contains("encode$Money_t")); + + compile_ok(&mut project, "Opaque.res", "type t\n"); + let error = compile_err( + &mut project, + "NoCompanion.res", + "let encode = (o: Opaque.t) => Json.encode(o)\n", + ); + assert!(error.contains("is abstract and its module has no toJson"), "{error}"); +} + +#[test] +fn generic_by_the_expected_type() { + let mut project = Project::new(); + compile_ok( + &mut project, + "Default.res", + r#" +open Macro + +@generic +let rec value = (_: code): code<'a> => + switch Type.info(expected()) { + | Int => %code(0) + | String => %code("") + | Bool => %code(false) + | Array(_) => %code([]) + | Option(_) => %code(None) + | Record({fields}) => Code.record(fields->Array.map(f => (f.name, %code(value())))) + | _ => error(`Default.value: no default for ${Type.name(expected())}`) + } +"#, + ); + let js = compile_ok( + &mut project, + "Settings.res", + "type settings = {name: string, retries: int, verbose: bool, tags: array}\nlet initial: settings = Default.value()\n", + ); + let expanded = project.expanded.clone().unwrap(); + assert!(expanded.contains("value$settings = "), "{expanded}"); + assert!(expanded.contains("value$array_string = "), "{expanded}"); + assert!(js.contains("retries: 0"), "{js}"); + assert!(js.contains("verbose: false"), "{js}"); +} From 445a1f39c45746e055520485fdab0dba5e8cbf3e Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:14:44 +0100 Subject: [PATCH 10/38] playground: a macros playground The playground compiles a project of several files in dependency order, expands macros with the page's JavaScript engine, and runs the result. It shows the expanded source, the JavaScript, the program's output and the compiler's trees for the selected file. - The compiler runs in a worker; a build that takes more than 20 seconds is stopped by replacing the worker. - A project can be shared as a link. - scripts/smoke.mjs builds and runs every example in Node. - The Macros playground workflow deploys the static site to GitHub Pages when started by hand. Co-authored-by: Jaap Frolich Session: https://jakes-mac-mini.tail23a77e.ts.net:8443/session/os-01a1ca09-2757-709a-bbb1-e57ccc4d104f Signed-off-by: Jaap Frolich --- .github/workflows/macros_playground.yml | 59 ++ playground/README.md | 48 ++ playground/crate/Cargo.lock | 995 +----------------------- playground/crate/src/lib.rs | 213 +++-- playground/index.html | 2 +- playground/package.json | 3 +- playground/scripts/bundle-stdlib.js | 42 +- playground/scripts/smoke.mjs | 55 ++ playground/src/App.jsx | 512 +++++++----- playground/src/compiler-client.js | 85 ++ playground/src/compiler-worker.js | 27 + playground/src/engine.js | 205 +++++ playground/src/examples.js | 16 + playground/src/share.js | 23 + playground/src/stdlib-loader.js | 48 -- playground/src/style.css | 201 +++++ playground/vite.config.js | 6 + 17 files changed, 1266 insertions(+), 1274 deletions(-) create mode 100644 .github/workflows/macros_playground.yml create mode 100644 playground/README.md create mode 100644 playground/scripts/smoke.mjs create mode 100644 playground/src/compiler-client.js create mode 100644 playground/src/compiler-worker.js create mode 100644 playground/src/engine.js create mode 100644 playground/src/examples.js create mode 100644 playground/src/share.js delete mode 100644 playground/src/stdlib-loader.js diff --git a/.github/workflows/macros_playground.yml b/.github/workflows/macros_playground.yml new file mode 100644 index 0000000000..e22529dcce --- /dev/null +++ b/.github/workflows/macros_playground.yml @@ -0,0 +1,59 @@ +name: Macros playground + +# Builds the playground in playground/ and deploys it to GitHub Pages. +# Started by hand: the repository has to have Pages enabled with +# "GitHub Actions" as its source. +on: + workflow_dispatch: + +permissions: + contents: read + pages: write + id-token: write + +concurrency: + group: macros-playground + cancel-in-progress: true + +jobs: + build: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + + # rust-toolchain.toml pins the toolchain of every Rust build here. + - name: Install the pinned Rust toolchain + run: | + rustup toolchain install + rustup target add wasm32-unknown-unknown + + - name: Install wasm-pack + run: cargo install wasm-pack --version 0.14.0 --locked + + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + cache-dependency-path: playground/package-lock.json + + - name: Build + working-directory: playground + run: | + npm ci + npm run build:wasm + npm run smoke + npm run build + + - uses: actions/upload-pages-artifact@v3 + with: + path: playground/dist + + deploy: + needs: build + runs-on: ubuntu-24.04 + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - id: deployment + uses: actions/deploy-pages@v4 diff --git a/playground/README.md b/playground/README.md new file mode 100644 index 0000000000..50ab69d3bc --- /dev/null +++ b/playground/README.md @@ -0,0 +1,48 @@ +# Macros playground + +A browser playground for the Rust compiler and its compile-time macros +([docs/comptime](../docs/comptime/README.md)). The compiler runs in +WebAssembly in a worker; macros run in the browser's JavaScript engine. A +project is a few files: they are compiled in dependency order, and the +compiled program is run. + +The right-hand side shows, for the selected file, the source after macro +expansion, the JavaScript, the program's output, and the compiler's +intermediate trees. + +## Build + +```bash +cd playground +npm ci +npm run build:wasm # compiler-rust -> crate/pkg (needs wasm-pack and the wasm32-unknown-unknown target) +npm run smoke # builds and runs every example with the wasm compiler, in Node +npm run build # static site in dist/ +``` + +`npm run dev` serves it with hot reload. + +`dist/` is a static site with relative URLs: it works from any path of any +static host. The `Macros playground` workflow builds it and deploys it to +GitHub Pages when it is started by hand. + +The standard library comes from `packages/@rescript/runtime`: its sources are +type checked on demand, and its compiled modules in `lib/es6` are what macros +and the compiled program import. `npm run build` bundles both into +`public/stdlib.json`. + +## Layout + +| Path | What | +| --- | --- | +| `crate/` | The wasm-bindgen entry points: `compile_file`, the virtual file system, and the macro host that calls into the page. | +| `src/engine.js` | The build: file order, compiling, running macros and the program. No dependency on the page; `scripts/smoke.mjs` runs it in Node. | +| `src/compiler-worker.js`, `src/compiler-client.js` | The worker the compiler runs in, and the page's side: a build that takes more than 20 seconds is stopped by replacing the worker. | +| `src/App.jsx` | The page. | +| `examples/` | The example projects, listed in `examples/index.json`. `compiler-rust/tests/macros.rs` compiles all of them. | + +## Adding an example + +Add a directory under `examples/` with the files, and an entry in +`examples/index.json`. List a file after the files it uses. A file that is +not `.res` is not compiled: macros read it with `Macro.readFile`. diff --git a/playground/crate/Cargo.lock b/playground/crate/Cargo.lock index 0251d27d9e..748c4ed6be 100644 --- a/playground/crate/Cargo.lock +++ b/playground/crate/Cargo.lock @@ -11,19 +11,11 @@ dependencies = [ "cfg-if", "getrandom", "once_cell", + "serde", "version_check", "zerocopy", ] -[[package]] -name = "aligned-vec" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc890384c8602f339876ded803c97ad529f3842aba97f6392b3dba0dd171769b" -dependencies = [ - "equator", -] - [[package]] name = "allocator-api2" version = "0.2.21" @@ -36,12 +28,6 @@ version = "1.0.102" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" -[[package]] -name = "arrayvec" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" - [[package]] name = "assert-unchecked" version = "0.1.2" @@ -69,147 +55,6 @@ dependencies = [ "typenum", ] -[[package]] -name = "boa_ast" -version = "0.21.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6339a700715bda376f5ea65c76e8fe8fc880930d8b0638cea68e7f3da6538e0a" -dependencies = [ - "bitflags", - "boa_interner", - "boa_macros", - "boa_string", - "indexmap", - "num-bigint", - "rustc-hash", -] - -[[package]] -name = "boa_engine" -version = "0.21.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1521be326f8a5c8887e95d4ce7f002917a002a23f7b93b9a6a2bf50ed4157824" -dependencies = [ - "aligned-vec", - "arrayvec", - "bitflags", - "boa_ast", - "boa_gc", - "boa_interner", - "boa_macros", - "boa_parser", - "boa_string", - "bytemuck", - "cfg-if", - "cow-utils", - "dashmap", - "dynify", - "fast-float2", - "float16", - "futures-channel", - "futures-concurrency", - "futures-lite", - "hashbrown 0.16.1", - "icu_normalizer", - "indexmap", - "intrusive-collections", - "itertools", - "num-bigint", - "num-integer", - "num-traits", - "num_enum", - "paste", - "portable-atomic", - "rand 0.9.4", - "regress", - "rustc-hash", - "ryu-js", - "serde", - "serde_json", - "small_btree", - "static_assertions", - "tag_ptr", - "tap", - "thin-vec", - "thiserror 2.0.18", - "time", - "xsum", -] - -[[package]] -name = "boa_gc" -version = "0.21.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17323a98cf2e631afacf1a6d659c1212c48a68bacfa85afab0a66ade80582e51" -dependencies = [ - "boa_macros", - "boa_string", - "hashbrown 0.16.1", - "thin-vec", -] - -[[package]] -name = "boa_interner" -version = "0.21.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20510b8b02bcde9b0a01cf34c0c308c56156503d1d91cdab4c8cfbd292b747ea" -dependencies = [ - "boa_gc", - "boa_macros", - "hashbrown 0.16.1", - "indexmap", - "once_cell", - "phf 0.13.1", - "rustc-hash", - "static_assertions", -] - -[[package]] -name = "boa_macros" -version = "0.21.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5822cb4f146d243060e588bc5a5f2e709683fdad3d7111f42c48e6b5c921d23d" -dependencies = [ - "cfg-if", - "cow-utils", - "proc-macro2", - "quote", - "syn", - "synstructure", -] - -[[package]] -name = "boa_parser" -version = "0.21.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35bd957fa9fa93e3a001a8aba5a5cd40c2bbfde486378be4c4b472fd304aaddb" -dependencies = [ - "bitflags", - "boa_ast", - "boa_interner", - "boa_macros", - "fast-float2", - "icu_properties", - "num-bigint", - "num-traits", - "regress", - "rustc-hash", -] - -[[package]] -name = "boa_string" -version = "0.21.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca2da1d7f4a76fd9040788a122f0d807910800a7b86f5952e9244848c36511de" -dependencies = [ - "fast-float2", - "itoa", - "paste", - "rustc-hash", - "ryu-js", - "static_assertions", -] - [[package]] name = "borsh" version = "1.6.1" @@ -229,26 +74,6 @@ dependencies = [ "allocator-api2", ] -[[package]] -name = "bytemuck" -version = "1.25.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8efb64bd706a16a1bdde310ae86b351e4d21550d98d056f22f8a7f7a2183fec" -dependencies = [ - "bytemuck_derive", -] - -[[package]] -name = "bytemuck_derive" -version = "1.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9abbd1bc6865053c427f7198e6af43bfdedc55ab791faed4fbd361d789575ff" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "bytes" version = "1.11.1" @@ -307,89 +132,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "417bef24afe1460300965a25ff4a24b8b45ad011948302ec221e8a0a81eb2c79" [[package]] -name = "crossbeam-utils" -version = "0.8.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" - -[[package]] -name = "dashmap" -version = "6.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5041cc499144891f3790297212f32a74fb938e5136a14943f338ef9e0ae276cf" -dependencies = [ - "cfg-if", - "crossbeam-utils", - "hashbrown 0.14.5", - "lock_api", - "once_cell", - "parking_lot_core", -] - -[[package]] -name = "deranged" -version = "0.5.8" +name = "elsa" +version = "1.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +checksum = "9abf33c656a7256451ebb7d0082c5a471820c31269e49d807c538c252352186e" dependencies = [ - "powerfmt", -] - -[[package]] -name = "displaydoc" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "dynify" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81acb15628a3e22358bf73de5e7e62360b8a777dbcb5fc9ac7dfa9ae73723747" -dependencies = [ - "dynify-macros", -] - -[[package]] -name = "dynify-macros" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ec431cd708430d5029356535259c5d645d60edd3d39c54e5eea9782d46caa7d" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "either" -version = "1.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" - -[[package]] -name = "equator" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4711b213838dfee0117e3be6ac926007d7f433d7bbe33595975d4190cb07e6fc" -dependencies = [ - "equator-macro", -] - -[[package]] -name = "equator-macro" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44f23cf4b44bfce11a86ace86f8a73ffdec849c9fd00a386a53d278bd9e81fb3" -dependencies = [ - "proc-macro2", - "quote", - "syn", + "stable_deref_trait", ] [[package]] @@ -398,87 +146,6 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" -[[package]] -name = "fast-float2" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8eb564c5c7423d25c886fb561d1e4ee69f72354d16918afa32c08811f6b6a55" - -[[package]] -name = "fastrand" -version = "2.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" - -[[package]] -name = "fixedbitset" -version = "0.5.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" - -[[package]] -name = "float16" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7bffafbd079d520191c7c2779ae9cf757601266cf4167d3f659ff09617ff8483" -dependencies = [ - "cfg-if", - "rustc_version", -] - -[[package]] -name = "foldhash" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" - -[[package]] -name = "futures-channel" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" -dependencies = [ - "futures-core", -] - -[[package]] -name = "futures-concurrency" -version = "7.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "175cd8cca9e1d45b87f18ffa75088f2099e3c4fe5e2f83e42de112560bea8ea6" -dependencies = [ - "fixedbitset", - "futures-core", - "futures-lite", - "pin-project", - "smallvec", -] - -[[package]] -name = "futures-core" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" - -[[package]] -name = "futures-io" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" - -[[package]] -name = "futures-lite" -version = "2.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" -dependencies = [ - "fastrand", - "futures-core", - "futures-io", - "parking", - "pin-project-lite", -] - [[package]] name = "getrandom" version = "0.3.4" @@ -493,12 +160,6 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "hashbrown" -version = "0.14.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" - [[package]] name = "hashbrown" version = "0.15.5" @@ -508,112 +169,12 @@ dependencies = [ "allocator-api2", ] -[[package]] -name = "hashbrown" -version = "0.16.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" -dependencies = [ - "allocator-api2", - "equivalent", - "foldhash", -] - [[package]] name = "hashbrown" version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4f467dd6dccf739c208452f8014c75c18bb8301b050ad1cfb27153803edb0f51" -[[package]] -name = "icu_collections" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "200072f5d0e3614556f94a9930d5dc3e0662a652823904c3a75dc3b0af7fee47" -dependencies = [ - "displaydoc", - "potential_utf", - "yoke", - "zerofrom", - "zerovec", -] - -[[package]] -name = "icu_locale_core" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" -dependencies = [ - "displaydoc", - "litemap", - "serde", - "tinystr", - "writeable", - "zerovec", -] - -[[package]] -name = "icu_normalizer" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b24a59706036ba941c9476a55cd57b82b77f38a3c667d637ee7cabbc85eaedc" -dependencies = [ - "displaydoc", - "icu_collections", - "icu_normalizer_data", - "icu_properties", - "icu_provider", - "smallvec", - "utf16_iter", - "write16", - "zerovec", -] - -[[package]] -name = "icu_normalizer_data" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00210d6893afc98edb752b664b8890f0ef174c8adbb8d0be9710fa66fbbf72d3" - -[[package]] -name = "icu_properties" -version = "2.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5a97b8ac6235e69506e8dacfb2adf38461d2ce6d3e9bd9c94c4cbc3cd4400a4" -dependencies = [ - "displaydoc", - "icu_collections", - "icu_locale_core", - "icu_properties_data", - "icu_provider", - "potential_utf", - "zerotrie", - "zerovec", -] - -[[package]] -name = "icu_properties_data" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "298459143998310acd25ffe6810ed544932242d3f07083eee1084d83a71bd632" - -[[package]] -name = "icu_provider" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" -dependencies = [ - "displaydoc", - "icu_locale_core", - "serde", - "stable_deref_trait", - "writeable", - "yoke", - "zerofrom", - "zerotrie", - "zerovec", -] - [[package]] name = "im-rc" version = "15.1.0" @@ -621,7 +182,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "af1955a75fa080c677d3972822ec4bad316169ab1cfc6c257a942c2265dbe5fe" dependencies = [ "bitmaps", - "rand_core 0.6.4", + "rand_core", "rand_xoshiro", "sized-chunks", "typenum", @@ -640,24 +201,6 @@ dependencies = [ "serde_core", ] -[[package]] -name = "intrusive-collections" -version = "0.9.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "189d0897e4cbe8c75efedf3502c18c887b05046e59d28404d4d8e46cbc4d1e86" -dependencies = [ - "memoffset", -] - -[[package]] -name = "itertools" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" -dependencies = [ - "either", -] - [[package]] name = "itoa" version = "1.0.18" @@ -680,21 +223,6 @@ version = "0.2.185" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "52ff2c0fe9bc6cb6b14a0592c2ff4fa9ceb83eea9db979b0487cd054946a2b8f" -[[package]] -name = "litemap" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" - -[[package]] -name = "lock_api" -version = "0.4.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" -dependencies = [ - "scopeguard", -] - [[package]] name = "log" version = "0.4.29" @@ -707,15 +235,6 @@ version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" -[[package]] -name = "memoffset" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" -dependencies = [ - "autocfg", -] - [[package]] name = "nonmax" version = "0.5.5" @@ -730,15 +249,8 @@ checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9" dependencies = [ "num-integer", "num-traits", - "serde", ] -[[package]] -name = "num-conv" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6673768db2d862beb9b39a78fdcb1a69439615d5794a1be50caa9bc92c81967" - [[package]] name = "num-integer" version = "0.1.46" @@ -752,40 +264,9 @@ dependencies = [ name = "num-traits" version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" -dependencies = [ - "autocfg", -] - -[[package]] -name = "num_enum" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" -dependencies = [ - "num_enum_derive", - "rustversion", -] - -[[package]] -name = "num_enum_derive" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" -dependencies = [ - "proc-macro-crate", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "num_threads" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c7398b9c8b70908f6371f47ed36737907c87c52af34c268fed0bf0ceb92ead9" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ - "libc", + "autocfg", ] [[package]] @@ -937,7 +418,7 @@ dependencies = [ "oxc_diagnostics", "oxc_estree", "oxc_span", - "phf 0.11.3", + "phf", "rustc-hash", "unicode-id-start", ] @@ -970,55 +451,20 @@ dependencies = [ "oxc_estree", "oxc_index", "oxc_span", - "phf 0.11.3", + "phf", "rustc-hash", "ryu-js", "unicode-id-start", ] -[[package]] -name = "parking" -version = "2.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" - -[[package]] -name = "parking_lot_core" -version = "0.9.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" -dependencies = [ - "cfg-if", - "libc", - "redox_syscall", - "smallvec", - "windows-link", -] - -[[package]] -name = "paste" -version = "1.0.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" - [[package]] name = "phf" version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" dependencies = [ - "phf_macros 0.11.3", - "phf_shared 0.11.3", -] - -[[package]] -name = "phf" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" -dependencies = [ - "phf_macros 0.13.1", - "phf_shared 0.13.1", + "phf_macros", + "phf_shared", ] [[package]] @@ -1027,18 +473,8 @@ version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" dependencies = [ - "phf_shared 0.11.3", - "rand 0.8.5", -] - -[[package]] -name = "phf_generator" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" -dependencies = [ - "fastrand", - "phf_shared 0.13.1", + "phf_shared", + "rand", ] [[package]] @@ -1047,21 +483,8 @@ version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f84ac04429c13a7ff43785d75ad27569f2951ce0ffd30a3321230db2fc727216" dependencies = [ - "phf_generator 0.11.3", - "phf_shared 0.11.3", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "phf_macros" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" -dependencies = [ - "phf_generator 0.13.1", - "phf_shared 0.13.1", + "phf_generator", + "phf_shared", "proc-macro2", "quote", "syn", @@ -1076,80 +499,12 @@ dependencies = [ "siphasher", ] -[[package]] -name = "phf_shared" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" -dependencies = [ - "siphasher", -] - -[[package]] -name = "pin-project" -version = "1.1.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1749c7ed4bcaf4c3d0a3efc28538844fb29bcdd7d2b67b2be7e20ba861ff517" -dependencies = [ - "pin-project-internal", -] - -[[package]] -name = "pin-project-internal" -version = "1.1.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9b20ed30f105399776b9c883e68e536ef602a16ae6f596d2c473591d6ad64c6" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "pin-project-lite" version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" -[[package]] -name = "portable-atomic" -version = "1.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49" - -[[package]] -name = "potential_utf" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" -dependencies = [ - "zerovec", -] - -[[package]] -name = "powerfmt" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" - -[[package]] -name = "ppv-lite86" -version = "0.2.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" -dependencies = [ - "zerocopy", -] - -[[package]] -name = "proc-macro-crate" -version = "3.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" -dependencies = [ - "toml_edit", -] - [[package]] name = "proc-macro2" version = "1.0.106" @@ -1180,27 +535,7 @@ version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" dependencies = [ - "rand_core 0.6.4", -] - -[[package]] -name = "rand" -version = "0.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea" -dependencies = [ - "rand_chacha", - "rand_core 0.9.5", -] - -[[package]] -name = "rand_chacha" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" -dependencies = [ - "ppv-lite86", - "rand_core 0.9.5", + "rand_core", ] [[package]] @@ -1209,41 +544,13 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" -[[package]] -name = "rand_core" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" -dependencies = [ - "getrandom", -] - [[package]] name = "rand_xoshiro" version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6f97cdb2a36ed4183de61b2f824cc45c9f1037f28afe0a322e9fff4c108b5aaa" dependencies = [ - "rand_core 0.6.4", -] - -[[package]] -name = "redox_syscall" -version = "0.5.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" -dependencies = [ - "bitflags", -] - -[[package]] -name = "regress" -version = "0.10.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2057b2325e68a893284d1538021ab90279adac1139957ca2a74426c6f118fb48" -dependencies = [ - "hashbrown 0.16.1", - "memchr", + "rand_core", ] [[package]] @@ -1252,7 +559,8 @@ version = "0.1.0" dependencies = [ "ahash", "anyhow", - "boa_engine", + "elsa", + "hashbrown 0.15.5", "im-rc", "indexmap", "log", @@ -1262,8 +570,10 @@ dependencies = [ "oxc_span", "serde", "serde_json", + "smallvec", "smol_str", "thiserror 2.0.18", + "tracing", "typed-arena", "wasm-bindgen", ] @@ -1286,15 +596,6 @@ version = "2.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe" -[[package]] -name = "rustc_version" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" -dependencies = [ - "semver", -] - [[package]] name = "rustversion" version = "1.0.22" @@ -1313,27 +614,6 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd29631678d6fb0903b69223673e122c32e9ae559d0960a38d574695ebc0ea15" -[[package]] -name = "scopeguard" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" - -[[package]] -name = "semver" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" -dependencies = [ - "semver-parser", -] - -[[package]] -name = "semver-parser" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" - [[package]] name = "seq-macro" version = "0.3.6" @@ -1405,15 +685,6 @@ dependencies = [ "typenum", ] -[[package]] -name = "small_btree" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ba60d2df92ba73864714808ca68c059734853e6ab722b40e1cf543ebb3a057a" -dependencies = [ - "arrayvec", -] - [[package]] name = "smallvec" version = "1.15.1" @@ -1459,29 +730,6 @@ dependencies = [ "unicode-ident", ] -[[package]] -name = "synstructure" -version = "0.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "tag_ptr" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0e973b34477b7823833469eb0f5a3a60370fef7a453e02d751b59180d0a5a05" - -[[package]] -name = "tap" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" - [[package]] name = "textwrap" version = "0.16.2" @@ -1493,12 +741,6 @@ dependencies = [ "unicode-width", ] -[[package]] -name = "thin-vec" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "259cdf8ed4e4aca6f1e9d011e10bd53f524a2d0637d7b28450f6c64ac298c4c6" - [[package]] name = "thiserror" version = "1.0.69" @@ -1540,77 +782,34 @@ dependencies = [ ] [[package]] -name = "time" -version = "0.3.47" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c" -dependencies = [ - "deranged", - "itoa", - "libc", - "num-conv", - "num_threads", - "powerfmt", - "serde_core", - "time-core", - "time-macros", -] - -[[package]] -name = "time-core" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca" - -[[package]] -name = "time-macros" -version = "0.2.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e70e4c5a0e0a8a4823ad65dfe1a6930e4f4d756dcd9dd7939022b5e8c501215" -dependencies = [ - "num-conv", - "time-core", -] - -[[package]] -name = "tinystr" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" -dependencies = [ - "displaydoc", - "serde_core", - "zerovec", -] - -[[package]] -name = "toml_datetime" -version = "1.1.1+spec-1.1.0" +name = "tracing" +version = "0.1.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" dependencies = [ - "serde_core", + "pin-project-lite", + "tracing-attributes", + "tracing-core", ] [[package]] -name = "toml_edit" -version = "0.25.11+spec-1.1.0" +name = "tracing-attributes" +version = "0.1.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b59c4d22ed448339746c59b905d24568fcbb3ab65a500494f7b8c3e97739f2b" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" dependencies = [ - "indexmap", - "toml_datetime", - "toml_parser", - "winnow", + "proc-macro2", + "quote", + "syn", ] [[package]] -name = "toml_parser" -version = "1.1.2+spec-1.1.0" +name = "tracing-core" +version = "0.1.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" dependencies = [ - "winnow", + "once_cell", ] [[package]] @@ -1649,12 +848,6 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" -[[package]] -name = "utf16_iter" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8232dd3cdaed5356e0f716d285e4b40b932ac434100fe9b7e0e8e935b9e6246" - [[package]] name = "version_check" version = "0.9.5" @@ -1715,68 +908,12 @@ dependencies = [ "unicode-ident", ] -[[package]] -name = "windows-link" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" - -[[package]] -name = "winnow" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09dac053f1cd375980747450bfc7250c264eaae0583872e845c0c7cd578872b5" -dependencies = [ - "memchr", -] - [[package]] name = "wit-bindgen" version = "0.51.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" -[[package]] -name = "write16" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1890f4022759daae28ed4fe62859b1236caebfc61ede2f63ed4e695f3f6d936" - -[[package]] -name = "writeable" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" - -[[package]] -name = "xsum" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0637d3a5566a82fa5214bae89087bc8c9fb94cd8e8a3c07feb691bb8d9c632db" - -[[package]] -name = "yoke" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca" -dependencies = [ - "stable_deref_trait", - "yoke-derive", - "zerofrom", -] - -[[package]] -name = "yoke-derive" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "synstructure", -] - [[package]] name = "zerocopy" version = "0.8.48" @@ -1797,62 +934,6 @@ dependencies = [ "syn", ] -[[package]] -name = "zerofrom" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69faa1f2a1ea75661980b013019ed6687ed0e83d069bc1114e2cc74c6c04c4df" -dependencies = [ - "zerofrom-derive", -] - -[[package]] -name = "zerofrom-derive" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "synstructure", -] - -[[package]] -name = "zerotrie" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" -dependencies = [ - "displaydoc", - "yoke", - "zerofrom", - "zerovec", -] - -[[package]] -name = "zerovec" -version = "0.11.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" -dependencies = [ - "serde", - "yoke", - "zerofrom", - "zerovec-derive", -] - -[[package]] -name = "zerovec-derive" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "zmij" version = "1.0.21" diff --git a/playground/crate/src/lib.rs b/playground/crate/src/lib.rs index 1e954dd03a..4b9f2e4c76 100644 --- a/playground/crate/src/lib.rs +++ b/playground/crate/src/lib.rs @@ -1,9 +1,13 @@ use wasm_bindgen::prelude::*; use std::cell::RefCell; +use std::path::PathBuf; +use std::sync::Arc; -use rescript_compiler::cmi::persistent_env::ModuleRegistry; +use rescript_compiler::cmi::persistent_env::{InMemoryModuleInfo, ModuleRegistry}; use rescript_compiler::driver::{self, CompilerOptions}; +use rescript_compiler::js_ir::ModuleFormat; +use rescript_compiler::macros::MacroHost; use rescript_compiler::parser::{module, Parser}; use rescript_compiler::wasm_vfs; @@ -12,17 +16,42 @@ pub fn init() { console_error_panic_hook::set_once(); } +// ── Source text ───────────────────────────────────────────────────────────── + +/// The compiler reads a source file as one character per byte (so that every +/// offset is a byte offset) and writes its output the same way. +fn to_compiler_text(text: &str) -> String { + text.bytes().map(char::from).collect() +} + +/// The inverse of [`to_compiler_text`], for text the compiler produced. +fn from_compiler_text(text: &str) -> String { + let bytes: Option> = text.chars().map(|c| u8::try_from(c as u32).ok()).collect(); + match bytes.map(String::from_utf8) { + Some(Ok(decoded)) => decoded, + _ => text.to_string(), + } +} + // ── Virtual filesystem ────────────────────────────────────────────────────── thread_local! { - static REGISTRY: RefCell = RefCell::new(ModuleRegistry::new()); + static REGISTRY: RefCell = RefCell::new(new_registry()); +} + +fn new_registry() -> ModuleRegistry { + let mut registry = ModuleRegistry::new(); + // The standard library is here as source only: it is type checked on + // demand and imported from `@rescript/runtime`. + registry.set_source_fallback_is_runtime(true); + registry } /// Write a file to the virtual filesystem. /// Call this with stdlib .res/.resi files at startup, and with user files on edit. #[wasm_bindgen] pub fn vfs_write_file(path: &str, content: &str) { - wasm_vfs::write_file(path, content.to_string()); + wasm_vfs::write_file(path, to_compiler_text(content)); } /// Delete a file from the virtual filesystem. @@ -35,7 +64,7 @@ pub fn vfs_delete_file(path: &str) { #[wasm_bindgen] pub fn vfs_clear() { wasm_vfs::clear(); - REGISTRY.with(|r| *r.borrow_mut() = ModuleRegistry::new()); + REGISTRY.with(|r| *r.borrow_mut() = new_registry()); } /// Register a module's source path for on-demand type checking. @@ -45,98 +74,119 @@ pub fn vfs_clear() { pub fn register_source_module(module_name: &str, source_path: &str) { REGISTRY.with(|r| { r.borrow_mut() - .source_fallback_paths - .insert(module_name.to_string(), source_path.into()); + .insert_source_fallback_path(module_name.to_string(), source_path.into()); }); } +/// Forget a compiled module, so that modules compiled later cannot see it. +#[wasm_bindgen] +pub fn forget_module(module_name: &str) { + REGISTRY.with(|r| r.borrow_mut().purge_module(module_name)); +} + +// ── Macros ────────────────────────────────────────────────────────────────── + +#[wasm_bindgen] +extern "C" { + /// `__rescript_macro_call` of `host.js`, which the page evaluates once + /// (see [`macro_host_js`]). + #[wasm_bindgen(catch, js_name = __rescript_macro_call)] + fn macro_call(request: &str) -> Result; +} + +/// The macro engine of the browser build: the page's own JavaScript engine. +struct PageHost; + +impl MacroHost for PageHost { + fn call(&self, request: &str) -> Result { + macro_call(request).map_err(|error| { + error + .as_string() + .or_else(|| { + js_sys_message(&error) + }) + .unwrap_or_else(|| "the macro engine failed".to_string()) + }) + } +} + +fn js_sys_message(error: &JsValue) -> Option { + let message = js_reflect_get(error, "message").ok()?; + message.as_string() +} + +#[wasm_bindgen] +extern "C" { + #[wasm_bindgen(catch, js_namespace = Reflect, js_name = get)] + fn js_reflect_get(target: &JsValue, key: &str) -> Result; +} + +/// The script the page evaluates to get `__rescript_macro_call`. Before it +/// does, it defines `__rescript_macro_source(moduleName)`, which returns the +/// compiled JavaScript of a module. +#[wasm_bindgen] +pub fn macro_host_js() -> String { + rescript_compiler::macros::HOST_JS.to_string() +} + // ── Parse only (fast, no type checking) ───────────────────────────────────── /// Parse ReScript source and return the parse tree as sexp with locations. /// Returns JSON: { type: "success", parse_tree: "..." } or { type: "error", ... } #[wasm_bindgen] pub fn parse_to_sexp(source: &str, filename: &str) -> String { + let source = to_compiler_text(source); + match parse_tree_sexp(&source, filename) { + Some(sexp) => serde_json::json!({ "type": "success", "parse_tree": sexp }).to_string(), + None => serde_json::json!({ "type": "error", "stage": "parse", "errors": [] }).to_string(), + } +} + +fn parse_tree_sexp(source: &str, filename: &str) -> Option { let mut parser = Parser::new(filename, source); let structure = module::parse_structure(&mut parser); - if parser.has_errors() { - let errors: Vec = parser - .diagnostics() - .iter() - .map(|d| format!("{:?}", d)) - .collect(); - return serde_json::json!({ - "type": "error", - "stage": "parse", - "errors": errors, - }) - .to_string(); + return None; } - let mut buf = Vec::new(); - rescript_compiler::parser::sexp_locs::print_structure( - &structure, - parser.arena(), - &mut buf, - ); - let sexp = String::from_utf8_lossy(&buf).into_owned(); - - serde_json::json!({ - "type": "success", - "parse_tree": sexp, - }) - .to_string() + rescript_compiler::parser::sexp_locs::print_structure(&structure, parser.arena(), &mut buf); + Some(String::from_utf8_lossy(&buf).into_owned()) } // ── Full compilation pipeline ─────────────────────────────────────────────── -/// Compile ReScript source through the full pipeline. -/// Returns JSON with all intermediate representations: -/// { type: "success", parse_tree, typed_tree, raw_lambda, lambda, js } -/// or { type: "error", stage, errors, ...partial results } +/// Compile one file of a project, expanding the macros it uses. +/// +/// The files it depends on were compiled before it; `is_runtime` marks a file +/// of `@rescript/runtime` itself. Returns JSON with the JavaScript, the +/// macro-expanded source when the file uses macros, the warnings and the +/// intermediate representations: +/// `{ type: "success", js, expanded, warnings, parse_tree, typed_tree, raw_lambda, lambda }` +/// or `{ type: "error", message, parse_tree }`. #[wasm_bindgen] -pub fn compile_all(source: &str, filename: &str) -> String { - // Capture parse tree for display (separate parser since we don't want to - // mutate the one compile_source_in_process uses). - let mut parse_parser = Parser::new(filename, source); - let parse_structure = module::parse_structure(&mut parse_parser); - if parse_parser.has_errors() { - let errors: Vec = parse_parser - .diagnostics() - .iter() - .map(|d| format!("{:?}", d)) - .collect(); - return serde_json::json!({ "type": "error", "stage": "parse", "errors": errors }).to_string(); - } - let mut parse_buf = Vec::new(); - rescript_compiler::parser::sexp_locs::print_structure( - &parse_structure, - parse_parser.arena(), - &mut parse_buf, - ); - let parse_tree_sexp = String::from_utf8_lossy(&parse_buf).into_owned(); - - // Derive a stable module name from the source filename. +pub fn compile_file(source: &str, filename: &str, is_runtime: bool) -> String { + let source = to_compiler_text(source); + // Diagnostics show a frame of the source file. + wasm_vfs::write_file(filename, source.clone()); + let parse_tree = parse_tree_sexp(&source, filename); let module_name = driver::module_name_from_source_filename(filename); - // Remove any stale copy of this module from the registry before compiling - // (so a previous compile's signature doesn't shadow the new source). - REGISTRY.with(|r| { - let mut reg = r.borrow_mut(); - reg.cached_modules.remove(&module_name); - reg.module_info.remove(&module_name); - }); + // A previous compile's signature must not shadow the new source. + REGISTRY.with(|r| r.borrow_mut().purge_module(&module_name)); + let host: Arc = Arc::new(PageHost); let options = CompilerOptions { source_filename: Some(filename.to_string()), module_name: Some(module_name.clone()), capture_intermediates: true, + output_module_format: Some(ModuleFormat::EsModule), + macro_host: Some(host), ..Default::default() }; let registry_snapshot = REGISTRY.with(|r| r.borrow().clone()); let result = driver::compile_source_in_process( - source, + &source, filename, &module_name, &options, @@ -146,27 +196,36 @@ pub fn compile_all(source: &str, filename: &str) -> String { match result { Ok(compiled) => { - REGISTRY.with(|r| { - let mut reg = r.borrow_mut(); - if let Some(ps) = compiled.pers_struct { - reg.cached_modules.insert(module_name.clone(), ps); - } - }); + if let Some(pers_struct) = compiled.pers_struct { + REGISTRY.with(|r| { + r.borrow_mut().register_module( + &module_name, + pers_struct, + InMemoryModuleInfo::new( + PathBuf::from(filename), + false, + Default::default(), + is_runtime, + ), + ); + }); + } serde_json::json!({ "type": "success", - "parse_tree": parse_tree_sexp, + "js": from_compiler_text(&compiled.js_output), + "expanded": compiled.expanded_source.as_deref().map(from_compiler_text), + "warnings": from_compiler_text(&compiled.warnings), + "parse_tree": parse_tree, "typed_tree": compiled.typed_tree_sexp, "raw_lambda": compiled.raw_lambda_sexp, "lambda": compiled.lambda_sexp, - "js": compiled.js_output, }) .to_string() } - Err(e) => serde_json::json!({ + Err(error) => serde_json::json!({ "type": "error", - "stage": "compile", - "errors": [format!("{e:?}")], - "parse_tree": parse_tree_sexp, + "message": from_compiler_text(&format!("{error:#}")), + "parse_tree": parse_tree, }) .to_string(), } diff --git a/playground/index.html b/playground/index.html index 72e8b94fc0..b57e6e5195 100644 --- a/playground/index.html +++ b/playground/index.html @@ -3,7 +3,7 @@ - ReScript Playground + ReScript macros playground

diff --git a/playground/package.json b/playground/package.json index 9e6ef435be..296a2aa3e8 100644 --- a/playground/package.json +++ b/playground/package.json @@ -4,10 +4,11 @@ "version": "0.1.0", "type": "module", "scripts": { - "dev": "vite", + "dev": "node scripts/bundle-stdlib.js && vite", "build": "node scripts/bundle-stdlib.js && vite build", "bundle:stdlib": "node scripts/bundle-stdlib.js", "build:wasm": "cd crate && wasm-pack build --target web --release", + "smoke": "node scripts/bundle-stdlib.js && node scripts/smoke.mjs", "preview": "vite preview" }, "devDependencies": { diff --git a/playground/scripts/bundle-stdlib.js b/playground/scripts/bundle-stdlib.js index ff95c2cde9..73f6f742bc 100644 --- a/playground/scripts/bundle-stdlib.js +++ b/playground/scripts/bundle-stdlib.js @@ -1,33 +1,45 @@ #!/usr/bin/env node /** - * Bundles all ReScript stdlib .res/.resi files into a JSON file - * for loading into the playground's virtual filesystem. + * Bundles the ReScript standard library for the playground: the .res/.resi + * sources, which the compiler type checks on demand, and the compiled ES + * modules, which the page loads to run macros and the compiled program. */ import { readdir, readFile, writeFile, mkdir } from "fs/promises"; -import { join, basename } from "path"; +import { join } from "path"; const RUNTIME_DIR = join(import.meta.dirname, "../../packages/@rescript/runtime"); const OUTPUT = join(import.meta.dirname, "../public/stdlib.json"); async function main() { - const entries = await readdir(RUNTIME_DIR); - const sourceFiles = entries.filter( - (f) => f.endsWith(".res") || f.endsWith(".resi") - ); + const sources = {}; + for (const filename of await readdir(RUNTIME_DIR)) { + if (filename.endsWith(".res") || filename.endsWith(".resi")) { + sources[`/stdlib/${filename}`] = await readFile(join(RUNTIME_DIR, filename), "utf-8"); + } + } - const files = {}; - for (const filename of sourceFiles) { - const content = await readFile(join(RUNTIME_DIR, filename), "utf-8"); - files[`/stdlib/${filename}`] = content; + const javascript = {}; + const jsDir = join(RUNTIME_DIR, "lib/es6"); + for (const filename of await readdir(jsDir)) { + if (filename.endsWith(".mjs")) { + javascript[filename.slice(0, -".mjs".length)] = await readFile(join(jsDir, filename), "utf-8"); + } + } + if (!javascript.Macro) { + throw new Error("lib/es6/Macro.mjs is missing: build packages/@rescript/runtime first"); } await mkdir(join(import.meta.dirname, "../public"), { recursive: true }); - await writeFile(OUTPUT, JSON.stringify(files)); + const json = JSON.stringify({ sources, javascript }); + await writeFile(OUTPUT, json); - const totalSize = Object.values(files).reduce((s, c) => s + c.length, 0); console.log( - `Bundled ${Object.keys(files).length} files (${(totalSize / 1024).toFixed(0)}KB) -> public/stdlib.json` + `Bundled ${Object.keys(sources).length} source files and ${Object.keys(javascript).length} modules ` + + `(${(json.length / 1024).toFixed(0)}KB) -> public/stdlib.json` ); } -main().catch(console.error); +main().catch((error) => { + console.error(error); + process.exit(1); +}); diff --git a/playground/scripts/smoke.mjs b/playground/scripts/smoke.mjs new file mode 100644 index 0000000000..b2d20968f6 --- /dev/null +++ b/playground/scripts/smoke.mjs @@ -0,0 +1,55 @@ +#!/usr/bin/env node +/** + * Builds every example of the playground with the wasm compiler, in Node, + * and prints what the page would show. Fails when an example does not + * compile or its program raises. + * + * node scripts/smoke.mjs [example-id] [--show] + */ +import { readFile } from "fs/promises"; +import { join } from "path"; +import * as wasm from "../crate/pkg/rescript_playground_wasm.js"; +import { createEngine } from "../src/engine.js"; + +const root = join(import.meta.dirname, ".."); +wasm.initSync({ module: await readFile(join(root, "crate/pkg/rescript_playground_wasm_bg.wasm")) }); +const stdlib = JSON.parse(await readFile(join(root, "public/stdlib.json"), "utf-8")); +const engine = createEngine(wasm, stdlib); + +const examples = []; +for (const example of JSON.parse(await readFile(join(root, "examples/index.json"), "utf-8"))) { + const files = []; + for (const name of example.files) { + files.push({ name, source: await readFile(join(root, "examples", example.id, name), "utf-8") }); + } + examples.push({ ...example, files }); +} + +const only = process.argv.slice(2).find((argument) => !argument.startsWith("--")); +const showAll = process.argv.includes("--show"); +let failed = false; + +for (const example of examples) { + if (only && example.id !== only) continue; + const started = performance.now(); + const { order, results, logs, crashed } = engine.build(example.files); + const ms = Math.round(performance.now() - started); + const errors = order.filter((name) => results[name]?.type !== "success"); + const raised = logs?.some((log) => log.text.startsWith("Uncaught")); + const ok = !crashed && errors.length === 0 && !raised; + console.log(`${ok ? "ok " : "FAIL"} ${example.id} (${ms} ms)`); + if (crashed) console.log(crashed); + for (const name of order) { + const result = results[name]; + if (!result) continue; + if (result.type !== "success") console.log(`--- ${name}\n${result.message}`); + else if (showAll || !ok) { + if (result.expanded) console.log(`--- ${name} expanded\n${result.expanded}`); + console.log(`--- ${name} js\n${result.js}`); + } + if (result.warnings) console.log(`--- ${name} warnings\n${result.warnings}`); + } + if (logs) console.log(logs.map((log) => ` | ${log.text}`).join("\n")); + failed ||= !ok; +} +process.exit(failed ? 1 : 0); diff --git a/playground/src/App.jsx b/playground/src/App.jsx index c2bb35fea4..7ca86d5f58 100644 --- a/playground/src/App.jsx +++ b/playground/src/App.jsx @@ -1,109 +1,159 @@ -import React, { useState, useEffect, useRef, useCallback } from "react"; +import React, { useState, useEffect, useRef, useCallback, useMemo } from "react"; import { Tabs } from "@base-ui/react/tabs"; import Editor, { loader } from "@monaco-editor/react"; -import { parseSexp, buildLocationIndex, findNodeAtCursor } from "./sexp-parser.js"; import TreeView from "./TreeView.jsx"; import { registerRescriptLanguage, languageId } from "./rescript-language.js"; -import { loadStdlib } from "./stdlib-loader.js"; +import { createCompiler } from "./compiler-client.js"; +import { isSourceFile } from "./engine.js"; +import { examples } from "./examples.js"; +import { decodeProject, encodeProject } from "./share.js"; // Register ReScript language with Monaco before any editor mounts +let monacoInstance = null; loader.init().then((monaco) => { + monacoInstance = monaco; registerRescriptLanguage(monaco); }); -const INITIAL_CODE = `type shape = - | Circle({radius: float}) - | Rect({width: float, height: float}) +const TABS = [ + ["expanded", "Expanded"], + ["js", "JavaScript"], + ["output", "Output"], + ["parse_tree", "Parse Tree"], + ["typed_tree", "Typed Tree"], + ["raw_lambda", "Raw Lambda"], + ["lambda", "Lambda"], +]; -let area = shape => - switch shape { - | Circle({radius}) => Math.Constants.pi *. radius *. radius - | Rect({width, height}) => width *. height - } +const EDITOR_OPTIONS = { + minimap: { enabled: false }, + fontSize: 14, + fontFamily: "'Cascadia Code', 'Fira Code', 'Consolas', monospace", + lineNumbers: "on", + scrollBeyondLastLine: false, + automaticLayout: true, + padding: { top: 12 }, + renderLineHighlight: "gutter", +}; -let total = [Circle({radius: 1.0}), Rect({width: 2.0, height: 3.0})] - ->Array.map(area) - ->Array.reduce(0.0, (acc, a) => acc +. a) -`; - -const TAB_LABELS = { - parse_tree: "Parse Tree", - typed_tree: "Typed Tree", - raw_lambda: "Raw Lambda", - lambda: "Lambda", - js: "JavaScript", +const READONLY_OPTIONS = { + ...EDITOR_OPTIONS, + fontSize: 13, + readOnly: true, + domReadOnly: true, + renderLineHighlight: "none", + padding: { top: 8 }, }; +function languageOf(filename) { + if (filename.endsWith(".res") || filename.endsWith(".resi")) return languageId; + if (filename.endsWith(".json")) return "json"; + return "plaintext"; +} + +function initialProject() { + const shared = decodeProject(window.location.hash); + if (shared) return { exampleId: "", files: shared }; + return { exampleId: examples[0].id, files: examples[0].files }; +} + +/** The first location of a compiler message: `Main.res:3:10-14`. */ +function locationOf(message) { + const found = /^\s*\S+?:(\d+):(\d+)(?:-(\d+)(?::(\d+))?)?\s*$/m.exec(message); + if (!found) return null; + const [, line, column, third, fourth] = found; + const startLine = Number(line); + const startColumn = Number(column); + if (fourth !== undefined) { + return { startLine, startColumn, endLine: Number(third), endColumn: Number(fourth) + 1 }; + } + return { startLine, startColumn, endLine: startLine, endColumn: (third ? Number(third) : startColumn) + 1 }; +} + export default function App() { - const [compiler, setCompiler] = useState(null); - const [status, setStatus] = useState("Loading WASM..."); - const [statusType, setStatusType] = useState("loading"); - const [result, setResult] = useState(null); - const [compileTime, setCompileTime] = useState(null); - const [activeTab, setActiveTab] = useState("parse_tree"); + const initial = useMemo(initialProject, []); + const [exampleId, setExampleId] = useState(initial.exampleId); + const [files, setFiles] = useState(initial.files); + // Monaco keeps one model per path; a new project gets new paths. + const [generation, setGeneration] = useState(0); + const [active, setActive] = useState(initial.files[initial.files.length - 1].name); + const [status, setStatus] = useState({ kind: "loading", text: "Loading the compiler…" }); + const [build, setBuild] = useState(null); + const [failure, setFailure] = useState(null); + const [buildTime, setBuildTime] = useState(null); + const [activeTab, setActiveTab] = useState("expanded"); const [cursorPosition, setCursorPosition] = useState({ line: 1, col: 0 }); const [editorWidth, setEditorWidth] = useState(50); + const [copied, setCopied] = useState(false); const editorRef = useRef(null); + const compilerRef = useRef(null); + const filesRef = useRef(files); const resizing = useRef(false); - const compileTimer = useRef(null); + const buildTimer = useRef(null); + + filesRef.current = files; - // Load WASM compiler + stdlib useEffect(() => { - async function loadCompiler() { - try { - setStatus("Loading WASM..."); - const wasm = await import("../crate/pkg/rescript_playground_wasm.js"); - await wasm.default(); - - setStatus("Loading stdlib..."); - const fileCount = await loadStdlib(wasm); - console.log(`Loaded ${fileCount} stdlib files into VFS`); - - setCompiler(wasm); - setStatus("Ready"); - setStatusType("ready"); - - // Initial compile - const t0 = performance.now(); - const output = wasm.compile_all(INITIAL_CODE, "Playground.res"); - setCompileTime(Math.round(performance.now() - t0)); - setResult(JSON.parse(output)); - } catch (err) { - console.error("Failed to load:", err); - setStatus(`Failed: ${err.message}`); - setStatusType("error"); - } - } - loadCompiler(); + const compiler = createCompiler({ + onReady: () => setStatus({ kind: "ready", text: "Ready" }), + onResult: (result, ms) => { + setBuild(result); + setFailure(null); + setBuildTime(Math.round(ms)); + setStatus({ kind: "ready", text: "Ready" }); + }, + onFailure: (message) => { + setFailure(message); + setBuild(null); + setStatus({ kind: "loading", text: "Restarting the compiler…" }); + }, + }); + compilerRef.current = compiler; + compiler.build(filesRef.current); + return () => compiler.dispose(); + }, []); + + const requestBuild = useCallback((nextFiles, delay) => { + clearTimeout(buildTimer.current); + buildTimer.current = setTimeout(() => compilerRef.current?.build(nextFiles), delay); }, []); - // Compile on editor change (debounced) + const openProject = useCallback( + (id, nextFiles) => { + setExampleId(id); + setFiles(nextFiles); + setGeneration((value) => value + 1); + setActive(nextFiles[nextFiles.length - 1].name); + requestBuild(nextFiles, 0); + }, + [requestBuild], + ); + + const handleExampleChange = (event) => { + const example = examples.find((candidate) => candidate.id === event.target.value); + if (!example) return; + window.history.replaceState(null, "", window.location.pathname + window.location.search); + openProject(example.id, example.files); + }; + const handleEditorChange = useCallback( (value) => { - if (!compiler) return; - clearTimeout(compileTimer.current); - compileTimer.current = setTimeout(() => { - const t0 = performance.now(); - const output = compiler.compile_all(value || "", "Playground.res"); - setCompileTime(Math.round(performance.now() - t0)); - setResult(JSON.parse(output)); - }, 300); + const nextFiles = filesRef.current.map((file) => + file.name === active ? { ...file, source: value ?? "" } : file, + ); + setFiles(nextFiles); + requestBuild(nextFiles, 300); }, - [compiler] + [active, requestBuild], ); - // Cursor position tracking const handleEditorMount = useCallback((editor) => { editorRef.current = editor; - editor.onDidChangeCursorPosition((e) => { - setCursorPosition({ - line: e.position.lineNumber, - col: e.position.column - 1, - }); + editor.onDidChangeCursorPosition((event) => { + setCursorPosition({ line: event.position.lineNumber, col: event.position.column - 1 }); }); }, []); - // Handle tree node click -> select in editor const handleNodeClick = useCallback((loc) => { const editor = editorRef.current; if (!editor || !loc) return; @@ -116,11 +166,48 @@ export default function App() { editor.revealLineInCenter(loc.startLine); }, []); + const addFile = () => { + const name = window.prompt("Name of the new file", "Util.res")?.trim(); + if (!name) return; + if (!/^[A-Za-z][A-Za-z0-9_.-]*$/.test(name)) { + window.alert("A file name is letters, digits, dots, dashes and underscores."); + return; + } + if (files.some((file) => file.name === name)) { + window.alert(`There is already a file ${name}.`); + return; + } + const nextFiles = [...files, { name, source: "" }]; + setFiles(nextFiles); + setActive(name); + requestBuild(nextFiles, 0); + }; + + const removeFile = (name) => { + if (files.length === 1) return; + const nextFiles = files.filter((file) => file.name !== name); + setFiles(nextFiles); + if (active === name) setActive(nextFiles[nextFiles.length - 1].name); + requestBuild(nextFiles, 0); + }; + + const share = async () => { + const hash = encodeProject(files); + window.history.replaceState(null, "", hash); + try { + await navigator.clipboard.writeText(window.location.href); + setCopied(true); + setTimeout(() => setCopied(false), 1500); + } catch { + // The link is in the address bar. + } + }; + // Resize handle useEffect(() => { - const handleMouseMove = (e) => { + const handleMouseMove = (event) => { if (!resizing.current) return; - const pct = (e.clientX / window.innerWidth) * 100; + const pct = (event.clientX / window.innerWidth) * 100; setEditorWidth(Math.max(20, Math.min(80, pct))); }; const handleMouseUp = () => { @@ -142,55 +229,134 @@ export default function App() { document.body.style.userSelect = "none"; }; - // Get current sexp content for the active tree tab - const currentSexp = result?.[activeTab] || ""; - const isTreeTab = activeTab !== "js"; + const activeFile = files.find((file) => file.name === active) ?? files[0]; + const result = build?.results?.[activeFile.name] ?? null; + const example = examples.find((candidate) => candidate.id === exampleId); + + // Errors and warnings of every file, in build order. + const problems = useMemo(() => { + if (failure) return [{ file: null, kind: "error", message: failure }]; + if (!build) return []; + const found = []; + for (const name of build.order) { + const fileResult = build.results[name]; + if (!fileResult) continue; + if (fileResult.type === "success") { + if (fileResult.warnings) found.push({ file: name, kind: "warning", message: fileResult.warnings }); + } else { + found.push({ file: name, kind: fileResult.type, message: fileResult.message }); + } + } + return found; + }, [build, failure]); + + // Show the first location of each file's messages in its editor. + useEffect(() => { + if (!monacoInstance) return; + for (const file of files) { + const model = monacoInstance.editor.getModel(monacoInstance.Uri.parse(`${generation}/${file.name}`)); + if (!model) continue; + const markers = problems + .filter((problem) => problem.file === file.name && problem.kind !== "skipped") + .map((problem) => { + const location = locationOf(problem.message); + if (!location) return null; + return { + severity: + problem.kind === "warning" + ? monacoInstance.MarkerSeverity.Warning + : monacoInstance.MarkerSeverity.Error, + message: problem.message, + startLineNumber: location.startLine, + startColumn: location.startColumn, + endLineNumber: location.endLine, + endColumn: location.endColumn, + }; + }) + .filter(Boolean); + monacoInstance.editor.setModelMarkers(model, "rescript", markers); + } + }, [problems, files, generation]); + + const errorCount = problems.filter((problem) => problem.kind !== "warning").length; return (
-

ReScript Playground

+

ReScript macros

Rust Compiler + + {example && {example.summary}}
- {status} - {compileTime !== null && ( - {compileTime}ms - )} + {status.text} + {buildTime !== null && {buildTime}ms} +
- +
+ {files.map((file) => { + const fileResult = build?.results?.[file.name]; + const state = !fileResult ? "" : fileResult.type === "success" ? "ok" : "failed"; + return ( +
setActive(file.name)} + > + {isSourceFile(file.name) && } + {file.name} + {files.length > 1 && ( + + )} +
+ ); + })} + +
+
+ +
-
+
- {Object.entries(TAB_LABELS).map(([key, label]) => ( + {TABS.map(([key, label]) => ( {label} @@ -198,95 +364,91 @@ export default function App() { - {Object.keys(TAB_LABELS).map((key) => ( + {TABS.map(([key]) => ( - {result?.type === "error" && result?.stage !== undefined && ( - - )} - {key === "js" ? ( - - ) : ( - - )} + ))} + {problems.length > 0 && ( +
+
+ {errorCount > 0 ? `${errorCount} error${errorCount === 1 ? "" : "s"}` : "Warnings"} +
+ {problems.map((problem, index) => ( +
 problem.file && setActive(problem.file)}
+                >
+                  {problem.kind === "skipped" ? `${problem.file}: ${problem.message}` : problem.message}
+                
+ ))} +
+ )}
); } -function ErrorDisplay({ result, tabKey }) { - const stages = ["parse", "ppx", "typecheck", "lambda", "js"]; - const errorStageIdx = stages.indexOf(result.stage); - const tabStageMap = { - parse_tree: 0, - typed_tree: 2, - raw_lambda: 3, - lambda: 3, - js: 4, - }; - const tabStageIdx = tabStageMap[tabKey] ?? 0; - - // Only show error on tabs at or after the failing stage - if (tabStageIdx < errorStageIdx) return null; - if (result[tabKey]) return null; // Has partial data - - return ( -
-
- {result.stage} error +function Panel({ tab, file, result, logs, cursorPosition, onNodeClick }) { + if (tab === "output") return ; + if (!isSourceFile(file.name)) { + return
{file.name} is not compiled. A macro can read it with Macro.readFile.
; + } + if (!result) return
Compiling…
; + if (tab === "expanded") { + if (result.type !== "success") return
This file did not compile.
; + if (!result.expanded) { + return ( +
+
This file uses no macro, so it is compiled as written.
+ +
+ ); + } + return ( +
+
The source after macro expansion: what the compiler compiles.
+
- {result.errors?.map((err, i) => ( -
{err}
- ))} -
- ); -} - -function TreePanel({ sexp, cursorPosition, onNodeClick }) { - if (!sexp) { - return
No data
; + ); + } + if (tab === "js") { + if (result.type !== "success") return
This file did not compile.
; + return ; } + const sexp = result[tab]; + if (!sexp) return
No data
; + return ; +} +function Output({ logs }) { + if (logs === null) return
The program runs when every file compiles.
; + if (logs.length === 0) return
The program printed nothing.
; return ( - +
+ {logs.map((log, index) => ( +
+          {log.text}
+        
+ ))} +
); } -function JsOutput({ code }) { - if (!code) { - return
No JavaScript output
; - } - +function ReadOnly({ language, value }) { return (
- +
); } diff --git a/playground/src/compiler-client.js b/playground/src/compiler-client.js new file mode 100644 index 0000000000..3c1ca8befb --- /dev/null +++ b/playground/src/compiler-client.js @@ -0,0 +1,85 @@ +/** + * The page's side of the compiler worker. Builds are requested one at a + * time; while one runs, only the latest request waits. A build that takes + * longer than `TIME_LIMIT` is stopped by replacing the worker. + */ + +const TIME_LIMIT = 20_000; + +export function createCompiler({ onReady, onResult, onFailure }) { + let worker = null; + let ready = false; + let running = null; // {id, timer} + let waiting = null; // files + let nextId = 1; + + function start() { + ready = false; + worker = new Worker(new URL("./compiler-worker.js", import.meta.url), { type: "module" }); + worker.onmessage = (event) => { + const message = event.data; + if (message.type === "ready") { + ready = true; + onReady(); + next(); + } else if (message.type === "built") { + if (!running || running.id !== message.id) return; + clearTimeout(running.timer); + running = null; + if (message.result.crashed) { + // The compiler panicked: its memory is in an unknown state. + restart(); + onFailure(message.result.crashed); + } else { + onResult(message.result, message.ms); + } + next(); + } else if (message.type === "failed") { + if (running) clearTimeout(running.timer); + running = null; + restart(); + onFailure(`The compiler failed: ${message.message}`); + } + }; + worker.onerror = (event) => { + if (running) clearTimeout(running.timer); + running = null; + onFailure(`The compiler failed: ${event.message || "unknown error"}`); + }; + worker.postMessage({ type: "init", stdlibUrl: new URL("stdlib.json", document.baseURI).href }); + } + + function restart() { + worker.terminate(); + start(); + } + + function next() { + if (!ready || running || !waiting) return; + const files = waiting; + waiting = null; + const id = nextId++; + const timer = setTimeout(() => { + running = null; + restart(); + onFailure( + `The build was stopped after ${TIME_LIMIT / 1000} seconds. A macro or the program probably does not terminate.`, + ); + }, TIME_LIMIT); + running = { id, timer }; + worker.postMessage({ type: "build", id, files }); + } + + start(); + + return { + build(files) { + waiting = files; + next(); + }, + dispose() { + if (running) clearTimeout(running.timer); + worker.terminate(); + }, + }; +} diff --git a/playground/src/compiler-worker.js b/playground/src/compiler-worker.js new file mode 100644 index 0000000000..f1599b55be --- /dev/null +++ b/playground/src/compiler-worker.js @@ -0,0 +1,27 @@ +/** + * The compiler, in a worker: a macro that does not terminate hangs this + * thread, not the page, and the page can stop it (see compiler-client.js). + */ +import init, * as wasm from "../crate/pkg/rescript_playground_wasm.js"; +import { createEngine } from "./engine.js"; + +let engine = null; + +self.onmessage = async (event) => { + const message = event.data; + try { + if (message.type === "init") { + await init(); + const response = await fetch(message.stdlibUrl); + if (!response.ok) throw new Error(`cannot load the standard library (${response.status})`); + engine = createEngine(wasm, await response.json()); + self.postMessage({ type: "ready" }); + } else if (message.type === "build") { + const started = performance.now(); + const result = engine.build(message.files); + self.postMessage({ type: "built", id: message.id, result, ms: performance.now() - started }); + } + } catch (error) { + self.postMessage({ type: "failed", id: message.id, message: String(error?.message ?? error) }); + } +}; diff --git a/playground/src/engine.js b/playground/src/engine.js new file mode 100644 index 0000000000..0b30e7e57b --- /dev/null +++ b/playground/src/engine.js @@ -0,0 +1,205 @@ +/** + * The playground's build: compiles the files of a small project in + * dependency order with the compiler in WebAssembly, runs macros in this + * JavaScript engine, and runs the compiled program. + * + * It has no dependency on the page, so the same code runs in the worker and + * in the Node smoke test (scripts/smoke.mjs). + */ + +export function moduleNameOf(filename) { + const base = filename.split("/").pop(); + const dot = base.lastIndexOf("."); + const name = dot < 0 ? base : base.slice(0, dot); + return name.charAt(0).toUpperCase() + name.slice(1); +} + +export function isSourceFile(filename) { + return filename.endsWith(".res"); +} + +/** + * The source files in the order they have to be compiled: a file after the + * files it mentions. Returns `{order, dependencies, cycle}`. + */ +export function compileOrder(files) { + const sources = files.filter((file) => isSourceFile(file.name)); + const names = sources.map((file) => moduleNameOf(file.name)); + const dependencies = new Map(); + sources.forEach((file, index) => { + const found = []; + names.forEach((name, other) => { + if (other === index) return; + // The module name where no longer name contains it: `Json.encode`, + // `%Json.codec`, `open Json`. + const mention = new RegExp(`(^|[^A-Za-z0-9_'.])${name}(?![A-Za-z0-9_'])`); + if (mention.test(file.source)) found.push(sources[other].name); + }); + dependencies.set(file.name, found); + }); + + const order = []; + const state = new Map(); + let cycle = null; + const visit = (name, path) => { + if (state.get(name) === "done") return; + if (state.get(name) === "open") { + cycle = cycle || path.slice(path.indexOf(name)).concat(name); + return; + } + state.set(name, "open"); + for (const dependency of dependencies.get(name)) visit(dependency, path.concat(name)); + state.set(name, "done"); + order.push(name); + }; + for (const file of sources) visit(file.name, []); + return { order, dependencies, cycle }; +} + +function stripAnsi(text) { + return text.replace(/\u001b\[[0-9;]*m/g, ""); +} + +function show(value, depth = 0) { + if (typeof value === "string") return depth === 0 ? value : JSON.stringify(value); + if (value === undefined) return "undefined"; + if (typeof value === "function") return "[function]"; + if (typeof value === "bigint") return `${value}n`; + if (typeof value === "symbol") return value.toString(); + if (value instanceof Error) return `${value.name}: ${value.message}`; + if (value === null || typeof value !== "object") return String(value); + if (depth > 6) return "…"; + if (Array.isArray(value)) return `[${value.map((item) => show(item, depth + 1)).join(", ")}]`; + const entries = Object.keys(value).map((key) => `${key}: ${show(value[key], depth + 1)}`); + return entries.length === 0 ? "{}" : `{${entries.join(", ")}}`; +} + +/** + * @param wasm the initialized wasm-bindgen module of playground/crate + * @param stdlib `{sources, javascript}` of public/stdlib.json + */ +export function createEngine(wasm, stdlib) { + // The standard library: sources for the type checker, an interface before + // its implementation. + const stdlibModules = new Map(); + for (const [path, content] of Object.entries(stdlib.sources)) { + wasm.vfs_write_file(path, content); + const name = path.split("/").pop().replace(/\.resi?$/, ""); + if (!stdlibModules.has(name) || path.endsWith(".resi")) stdlibModules.set(name, path); + } + const registerStdlib = (name) => wasm.register_source_module(name, stdlibModules.get(name)); + for (const name of stdlibModules.keys()) registerStdlib(name); + + // Compiled JavaScript of the project, by module name. + let projectJs = Object.create(null); + let projectFiles = []; + const javascriptOf = (name) => projectJs[name] ?? stdlib.javascript[name]; + + // The macro engine is this JavaScript engine: host.js gets the compiled + // modules from here, the compiler calls `__rescript_macro_call`. + globalThis.__rescript_macro_source = javascriptOf; + (0, eval)(wasm.macro_host_js()); + const macroCall = (request) => globalThis.__rescript_macro_call(JSON.stringify(request)); + const toCommonJs = globalThis.__rescript_macro.toCommonJs; + + function run(order) { + const logs = []; + const log = (level) => (...values) => + logs.push({ level, text: values.map((value) => show(value)).join(" ") }); + const console = { log: log("log"), info: log("log"), debug: log("log"), warn: log("warn"), error: log("error") }; + const loaded = Object.create(null); + const load = (name) => { + if (loaded[name]) return loaded[name].exports; + const source = javascriptOf(name); + if (source === undefined) throw new Error(`The module ${name} is not part of this playground.`); + const module = { exports: {} }; + loaded[name] = module; + new Function("require", "exports", "module", "console", toCommonJs(source))( + (specifier) => load(moduleNameOf(specifier)), + module.exports, + module, + console, + ); + return module.exports; + }; + try { + for (const filename of order) load(moduleNameOf(filename)); + } catch (error) { + logs.push({ level: "error", text: `Uncaught ${describeException(error)}` }); + } + return logs; + } + + function describeException(error) { + if (error && typeof error === "object" && error.RE_EXN_ID !== undefined) { + const parts = [String(error.RE_EXN_ID)]; + if (error._1 !== undefined) parts.push(show(error._1)); + return parts.join(": "); + } + return show(error); + } + + /** + * Compile `files` (`[{name, source}]`) and run the result. + * Returns `{order, results, logs}`: per source file `{type: "success", js, + * expanded, warnings, ...}`, `{type: "error", message}` or `{type: + * "skipped", message}`; `logs` is null when a file did not compile. + */ + function build(files) { + // Start from nothing: a module of the previous build must not be visible. + for (const file of projectFiles) { + const name = moduleNameOf(file.name); + if (isSourceFile(file.name)) { + wasm.forget_module(name); + if (stdlibModules.has(name)) registerStdlib(name); + } else { + wasm.vfs_delete_file(`/${file.name}`); + } + } + projectFiles = files; + projectJs = Object.create(null); + macroCall({ kind: "reset" }); + // Other files are what `Macro.readFile` reads. + for (const file of files) { + if (!isSourceFile(file.name)) wasm.vfs_write_file(`/${file.name}`, file.source); + } + + const { order, dependencies, cycle } = compileOrder(files); + const results = {}; + if (cycle) { + const message = `These files depend on each other in a cycle: ${cycle.join(" → ")}`; + for (const name of order) results[name] = { type: "error", message }; + return { order, results, logs: null }; + } + let ok = true; + for (const name of order) { + const failed = dependencies.get(name).find((dependency) => results[dependency]?.type !== "success"); + if (failed) { + results[name] = { type: "skipped", message: `Not compiled: it depends on ${failed}, which has an error.` }; + ok = false; + continue; + } + const file = files.find((candidate) => candidate.name === name); + const started = performance.now(); + let result; + try { + result = JSON.parse(wasm.compile_file(file.source, file.name, false)); + } catch (error) { + // A panic in the compiler: the wasm instance is unusable from here. + return { order, results, logs: null, crashed: `The compiler crashed on ${name}: ${show(error)}` }; + } + result.ms = performance.now() - started; + if (result.type === "success") { + projectJs[moduleNameOf(name)] = result.js; + result.warnings = stripAnsi(result.warnings || "").trim(); + } else { + result.message = stripAnsi(result.message || "").trim(); + ok = false; + } + results[name] = result; + } + return { order, results, logs: ok ? run(order) : null }; + } + + return { build }; +} diff --git a/playground/src/examples.js b/playground/src/examples.js new file mode 100644 index 0000000000..45825933f0 --- /dev/null +++ b/playground/src/examples.js @@ -0,0 +1,16 @@ +/** + * The examples of the playground: the projects under `examples/`, listed in + * `examples/index.json`. Each is a few files that are compiled in dependency + * order and run. + */ +import index from "../examples/index.json"; + +const sources = import.meta.glob("../examples/*/*", { query: "?raw", import: "default", eager: true }); + +export const examples = index.map((example) => ({ + ...example, + files: example.files.map((name) => ({ + name, + source: sources[`../examples/${example.id}/${name}`], + })), +})); diff --git a/playground/src/share.js b/playground/src/share.js new file mode 100644 index 0000000000..db3092b7ea --- /dev/null +++ b/playground/src/share.js @@ -0,0 +1,23 @@ +/** A project in the URL: `#project=`. */ + +const KEY = "#project="; + +export function encodeProject(files) { + const bytes = new TextEncoder().encode(JSON.stringify(files.map((file) => [file.name, file.source]))); + let binary = ""; + for (const byte of bytes) binary += String.fromCharCode(byte); + return KEY + btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); +} + +export function decodeProject(hash) { + if (!hash.startsWith(KEY)) return null; + try { + const binary = atob(hash.slice(KEY.length).replace(/-/g, "+").replace(/_/g, "/")); + const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0)); + const entries = JSON.parse(new TextDecoder().decode(bytes)); + if (!Array.isArray(entries) || entries.length === 0) return null; + return entries.map(([name, source]) => ({ name: String(name), source: String(source) })); + } catch { + return null; + } +} diff --git a/playground/src/stdlib-loader.js b/playground/src/stdlib-loader.js deleted file mode 100644 index edd27cfd4e..0000000000 --- a/playground/src/stdlib-loader.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Loads ReScript stdlib files into the WASM compiler's virtual filesystem. - */ - -/** - * Derive a module name from a filename. - * e.g., "Js.res" -> "Js", "Belt_Array.resi" -> "Belt_Array" - */ -function moduleNameFromPath(vfsPath) { - const filename = vfsPath.split("/").pop(); - return filename.replace(/\.(res|resi)$/, ""); -} - -/** - * Load all stdlib files into the WASM VFS and register modules. - * @param {Object} compiler - The WASM compiler module - * @returns {Promise} Number of files loaded - */ -export async function loadStdlib(compiler) { - const response = await fetch("/stdlib.json"); - if (!response.ok) { - throw new Error(`Failed to fetch stdlib.json: ${response.status}`); - } - const files = await response.json(); - - // Write all files to VFS - for (const [path, content] of Object.entries(files)) { - compiler.vfs_write_file(path, content); - } - - // Register modules for on-demand type checking. - // For each module, prefer .resi (interface) over .res (implementation). - const modules = new Map(); - for (const path of Object.keys(files)) { - const moduleName = moduleNameFromPath(path); - const isInterface = path.endsWith(".resi"); - // .resi takes priority - if (!modules.has(moduleName) || isInterface) { - modules.set(moduleName, path); - } - } - - for (const [moduleName, path] of modules) { - compiler.register_source_module(moduleName, path); - } - - return Object.keys(files).length; -} diff --git a/playground/src/style.css b/playground/src/style.css index af5192d413..5740811a58 100644 --- a/playground/src/style.css +++ b/playground/src/style.css @@ -324,3 +324,204 @@ h1 { .tree-root::-webkit-scrollbar-thumb:hover { background: var(--border); } + +/* Example chooser */ +.example-select, +.share-button { + height: 26px; + padding: 0 8px; + border: 1px solid var(--border); + border-radius: 4px; + background: var(--bg-lightest); + color: var(--text); + font-size: 12px; + font-family: inherit; +} + +.share-button { + cursor: pointer; +} + +.share-button:hover { + border-color: var(--accent); +} + +.example-summary { + font-size: 12px; + color: var(--text-muted); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.header-left { + min-width: 0; + flex: 1; +} + +.header-right { + flex-shrink: 0; + padding-left: 12px; +} + +.header-left > h1, +.header-left > .badge, +.header-left > .example-select { + flex-shrink: 0; +} + +/* File tabs */ +.editor-pane { + display: flex; + flex-direction: column; +} + +.editor-body { + flex: 1; + min-height: 0; +} + +.file-tabs { + display: flex; + align-items: stretch; + height: 36px; + background: var(--bg-lightest); + border-bottom: 1px solid var(--border); + flex-shrink: 0; + overflow-x: auto; +} + +.file-tab { + display: flex; + align-items: center; + gap: 6px; + padding: 0 10px 0 12px; + font-size: 12px; + color: var(--text-muted); + cursor: pointer; + white-space: nowrap; + border-right: 1px solid var(--border); +} + +.file-tab:hover { + color: var(--text); +} + +.file-tab.active { + color: var(--text); + background: var(--bg); +} + +.file-state { + width: 6px; + height: 6px; + border-radius: 50%; + background: var(--text-muted); +} + +.file-state.ok { + background: var(--success); +} + +.file-state.failed { + background: var(--error); +} + +.file-close, +.file-add { + border: none; + background: transparent; + color: var(--text-muted); + font-size: 14px; + line-height: 1; + cursor: pointer; + padding: 2px 4px; + border-radius: 3px; +} + +.file-add { + padding: 0 12px; +} + +.file-close:hover, +.file-add:hover { + color: var(--text); + background: var(--highlight); +} + +/* Panels */ +.panel-with-note { + display: flex; + flex-direction: column; +} + +.panel-note { + flex-shrink: 0; + padding: 6px 12px; + font-family: 'Segoe UI', system-ui, -apple-system, sans-serif; + font-size: 12px; + color: var(--text-muted); + border-bottom: 1px solid var(--border); +} + +.panel-with-note > .js-output { + flex: 1; + min-height: 0; +} + +.console { + padding: 8px 12px; +} + +.console-line { + font: inherit; + white-space: pre-wrap; + word-break: break-word; + padding: 1px 0; +} + +.console-line.warn { + color: #dcdcaa; +} + +.console-line.error { + color: var(--error); +} + +/* Problems */ +.output-pane > .problems { + flex: 0 1 auto; + max-height: 45%; + overflow: auto; + border-top: 1px solid var(--border); + background: var(--bg-lighter); + padding: 8px 12px; +} + +.problems-title { + font-size: 11px; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.5px; + color: var(--text-muted); + margin-bottom: 6px; +} + +.problem { + font-family: 'Cascadia Code', 'Fira Code', 'Consolas', monospace; + font-size: 12px; + line-height: 1.5; + white-space: pre-wrap; + word-break: break-word; + color: var(--error); + cursor: pointer; + margin-bottom: 8px; +} + +.problem.warning { + color: #dcdcaa; +} + +.problem.skipped { + color: var(--text-muted); +} diff --git a/playground/vite.config.js b/playground/vite.config.js index b53eeaae75..739ecb704c 100644 --- a/playground/vite.config.js +++ b/playground/vite.config.js @@ -3,7 +3,13 @@ import react from "@vitejs/plugin-react"; import wasm from "vite-plugin-wasm"; export default defineConfig({ + // Relative URLs: the built site works from any path of any static host. + base: "./", plugins: [react(), wasm()], + worker: { + format: "es", + plugins: () => [wasm()], + }, build: { target: "esnext", }, From b28509ec5f8f019daeed67395399641f9ce617e5 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:14:44 +0100 Subject: [PATCH 11/38] docs: RFC for compile-time macros Replaces the first comptime proposal, which followed Zig's partial evaluation, with the design that is implemented: macros are functions that return quoted code. README.md is the RFC; IMPLEMENTATION.md describes the compiler side. Co-authored-by: Jaap Frolich Session: https://jakes-mac-mini.tail23a77e.ts.net:8443/session/os-01a1ca09-2757-709a-bbb1-e57ccc4d104f Signed-off-by: Jaap Frolich --- docs/comptime/BUILDERS.md | 273 ----- docs/comptime/DESIGN.md | 1870 ------------------------------ docs/comptime/EXAMPLES.md | 641 ---------- docs/comptime/IMPLEMENTATION.md | 253 ++++ docs/comptime/PROTOTYPE_NOTES.md | 179 --- docs/comptime/README.md | 609 +++++++++- 6 files changed, 846 insertions(+), 2979 deletions(-) delete mode 100644 docs/comptime/BUILDERS.md delete mode 100644 docs/comptime/DESIGN.md delete mode 100644 docs/comptime/EXAMPLES.md create mode 100644 docs/comptime/IMPLEMENTATION.md delete mode 100644 docs/comptime/PROTOTYPE_NOTES.md diff --git a/docs/comptime/BUILDERS.md b/docs/comptime/BUILDERS.md deleted file mode 100644 index b77f38ff08..0000000000 --- a/docs/comptime/BUILDERS.md +++ /dev/null @@ -1,273 +0,0 @@ -# Comptime Builder Design - -## TypeInfo Types (using optional fields) - -```rescript -type rec typeInfo = - | Int - | Float - | String - | Bool - | Unit - | Record({ - name: string, - fields: array, - unboxed?: bool, - }) - | Variant({ - name: string, - constructors: array, - unboxed?: bool, - }) - | Array({element: typeInfo}) - | Option({inner: typeInfo}) - | Tuple({elements: array}) - | Function({args: array, returnType: typeInfo}) - | External({name: string}) - | Opaque({name: string}) - | Unknown - -and fieldInfo = { - name: string, - typ: typeInfo, - optional?: bool, - mutable_?: bool, -} - -and constructorInfo = { - name: string, - payload?: constructorPayload, -} - -and constructorPayload = - | Single(typeInfo) - | Tuple(array) - | InlineRecord(array) -``` - -Optional fields use `?` so construction is clean: -```rescript -// Most fields are not optional/mutable, so defaults reduce noise: -{name: "age", typ: Int} -// vs without optionals: -{name: "age", typ: Int, optional: false, mutable_: false} -``` - -## Builders - -### `@record(fields)` — Build a record from comptime field specifications - -```rescript -// In a decoder: -let obj = JSON.Decode.object(json) -@record( - inline for field in fields { - {name: field.name, value: decode(Dict.getExn(obj, field.name))} - } -) -``` - -The `@record` builtin takes an array of `{name: string, value: 'a}` where `name` is comptime-known. The compiler: -1. Validates all required record fields are present -2. Type-checks each value against the corresponding field type -3. Produces a `Texp_record` node in the typed tree - -This generates: -```javascript -{ - name: JSON.Decode.string(obj["name"]), - age: JSON.Decode.int(obj["age"]), - // ... -} -``` - -### `@variant(name, payload?)` — Build a variant constructor - -```rescript -@variant("Circle", {radius: decodedRadius}) // → Circle({radius: decodedRadius}) -@variant("Point") // → Point -@variant("Some", decodedValue) // → Some(decodedValue) -``` - -The compiler: -1. Validates the constructor name exists on the target type -2. Type-checks the payload against the constructor's expected arguments -3. Produces a `Texp_construct` node - -### `@matchVariant(value, constructors)` — Pattern match a variant by comptime constructor list - -```rescript -// In an encoder: -@matchVariant(value, constructors, (ctor, payload) => { - let dict = Dict.make() - Dict.set(dict, "tag", JSON.Encode.string(ctor.name)) - switch ctor.payload { - | None => () - | Some(Single(_)) => - Dict.set(dict, "value", encode(payload)) - | Some(InlineRecord(fields)) => - inline for field in fields { - Dict.set(dict, field.name, encode(@field(payload, field.name))) - } - | Some(Tuple(types)) => - inline for (i, typ) in types { - Dict.set(dict, "_" ++ Int.toString(i), encode(@tupleField(payload, i))) - } - } - JSON.Encode.object(dict) -}) -``` - -This generates a switch expression with one arm per constructor: -```javascript -switch (value.TAG) { - case "Circle": - let dict = {}; - dict["tag"] = "Circle"; - dict["radius"] = JSON.Encode.float(value.radius); - return JSON.Encode.object(dict); - case "Point": - let dict = {}; - dict["tag"] = "Point"; - return JSON.Encode.object(dict); - // ... -} -``` - -## Realistic Encoder Example - -```rescript -@comptime -let rec encode = (value) => { - switch @typeInfo(value) { - | String => JSON.Encode.string(value) - | Int => JSON.Encode.int(value) - | Float => JSON.Encode.float(value) - | Bool => JSON.Encode.bool(value) - | Option({inner}) => - switch value { - | Some(v) => encode(v) - | None => JSON.Encode.null - } - | Array({element}) => - JSON.Encode.array(value, item => encode(item)) - | Record({fields}) => { - let dict = Dict.make() - inline for field in fields { - if field.optional { - switch @field(value, field.name) { - | Some(v) => Dict.set(dict, field.name, encode(v)) - | None => () - } - } else { - Dict.set(dict, field.name, encode(@field(value, field.name))) - } - } - JSON.Encode.object(dict) - } - | Variant({constructors}) => - @matchVariant(value, constructors, (ctor, payload) => { - let dict = Dict.make() - Dict.set(dict, "tag", JSON.Encode.string(ctor.name)) - switch ctor.payload { - | None => () - | Some(Single(_)) => Dict.set(dict, "value", encode(payload)) - | Some(InlineRecord(fields)) => - inline for field in fields { - Dict.set(dict, field.name, encode(@field(payload, field.name))) - } - } - JSON.Encode.object(dict) - }) - | _ => @compileError("Cannot encode this type") - } -} -``` - -## Realistic Decoder Example - -```rescript -@comptime -let rec decode = (json) => { - switch @typeInfo(json) { - | String => JSON.Decode.string(json) - | Int => JSON.Decode.int(json) - | Float => JSON.Decode.float(json) - | Bool => JSON.Decode.bool(json) - | Option({inner}) => - switch JSON.Decode.nullable(json) { - | Some(v) => Some(decode(v)) - | None => None - } - | Array({element}) => - JSON.Decode.array(json, item => decode(item)) - | Record({fields}) => { - let obj = JSON.Decode.object(json) - @record( - inline for field in fields { - if field.optional { - {name: field.name, value: switch Dict.get(obj, field.name) { - | Some(v) => Some(decode(v)) - | None => None - }} - } else { - {name: field.name, value: decode(Dict.getExn(obj, field.name))} - } - } - ) - } - | Variant({constructors}) => { - let obj = JSON.Decode.object(json) - let tag = JSON.Decode.string(Dict.getExn(obj, "tag")) - switch tag { - inline for ctor in constructors { - | ctor.name => - switch ctor.payload { - | None => @variant(ctor.name) - | Some(Single(_)) => @variant(ctor.name, decode(Dict.getExn(obj, "value"))) - | Some(InlineRecord(fields)) => - @variant(ctor.name, @record( - inline for field in fields { - {name: field.name, value: decode(Dict.getExn(obj, field.name))} - } - )) - } - } - } - } - | _ => @compileError("Cannot decode this type") - } -} -``` - -## What's Implemented vs TODO - -### Implemented ✅ -- `typeInfo` as predefined type with constructors -- `@typeInfo(typeName)` resolves to literal value -- `switch @typeInfo(T)` branch elimination in type checker -- `Record({name, fields})` destructuring with comptime bindings -- `inline for field in fields` unrolling -- `field.name` comptime field access -- `@field(value, comptimeName)` validated field access → Texp_field -- `@comptime` function inlining with parameter binding -- `@compileError("msg")` compile-time error -- Lambda switch constant folding for variants - -### TODO for encoder -- `@typeInfo(value)` on expressions (infer type from static type) -- Recursive `@comptime` calls (`encode(@field(value, field.name))`) -- `field.optional` comptime boolean access (for conditional encoding) -- `@matchVariant` for variant encoding -- `Variant({constructors})` in typeInfo - -### TODO for decoder -- `@record(fields)` record builder -- `@variant(name, payload?)` variant builder -- Recursive `@comptime` calls for nested decoding - -### TODO for both -- `@comptime.inline` + Boa for user helper functions -- `constructorPayload` type for variant arg inspection -- Poly variant support in typeInfo -- Tuple support in typeInfo diff --git a/docs/comptime/DESIGN.md b/docs/comptime/DESIGN.md deleted file mode 100644 index 6052c48cc0..0000000000 --- a/docs/comptime/DESIGN.md +++ /dev/null @@ -1,1870 +0,0 @@ -# ReScript Comptime: Compile-Time Metaprogramming - -This document describes a proposed compile-time execution system for ReScript, inspired by Zig's comptime feature. The goal is to enable powerful metaprogramming capabilities that can replace all current PPX use cases while being simpler to use and maintain. - -## Table of Contents - -1. [Overview](#overview) -2. [Design Goals](#design-goals) -3. [Core Concepts](#core-concepts) -4. [Type Introspection](#type-introspection) -5. [Execution Model: QuickJS](#execution-model-quickjs) -6. [Why an Integrated In-Process Compiler](#why-an-integrated-in-process-compiler) -7. [Derive Attributes](#derive-attributes) -8. [Replacing PPXs](#replacing-ppxs) -9. [Implementation Plan](#implementation-plan) -10. [Appendix: Zig Comptime Reference](#appendix-zig-comptime-reference) - ---- - -## Overview - -### What is Comptime? - -Comptime (compile-time execution) allows regular ReScript code to execute during compilation. Unlike PPXs, which require writing OCaml code that manipulates the AST, comptime lets you write ReScript code that: - -1. **Runs at compile time** when all inputs are known -2. **Introspects types** via `@typeInfo` -3. **Generates specialized code** based on type structure -4. **Parses strings** (for DSLs like GraphQL, SQL, CSS) - -### Why Comptime Over PPXs? - -| Aspect | PPXs | Comptime | -|--------|------|----------| -| **Language** | OCaml | ReScript | -| **Toolchain** | Separate OCaml build | Part of compiler | -| **Debugging** | Complex AST manipulation | Regular ReScript code | -| **Testing** | Requires special setup | Standard unit tests | -| **Community** | OCaml expertise needed | Any ReScript developer | -| **Maintenance** | AST changes break PPXs | Stable interface | - -### Key Design Choice: Zig-Style Partial Evaluation - -Unlike macro systems that generate code as strings or AST, comptime uses **partial evaluation**. You write a normal function, mark compile-time-known parameters, and the compiler specializes it: - -```rescript -@comptime -let rec encode = (value): JSON.t => { - switch @typeInfo(value) { - | String => JSON.Encode.string(value) - | Int => JSON.Encode.int(value) - | Float => JSON.Encode.float(value) - | Bool => JSON.Encode.bool(value) - | Record({fields}) => - let dict = Dict.make() - inline for field in fields { - Dict.set(dict, field.name, encode(@field(value, field.name))) - } - JSON.Encode.object(dict) - | _ => @compileError("unsupported type") - } -} - -// Call site: -let json = encode(myUser) -``` - -The compiler evaluates the `switch @typeInfo(value)` at compile time using the known type at each call site, picks the matching branch, unrolls `inline for`, recursively specializes each `encode` call. What comes out is concrete code with no type dispatch: - -```javascript -// Generated output — no runtime type info, no loops, no generics -// Since JSON.Encode.* are all %identity, they compile to nothing! -let dict = {}; -dict["name"] = myUser.name; -dict["age"] = myUser.age; -let dict$1 = {}; -dict$1["street"] = myUser.address.street; -dict$1["city"] = myUser.address.city; -dict["address"] = dict$1; -let json = dict; -``` - -No code generation step. No strings, no AST builders, no quasi-quotation. The function body **is** the template. Comptime evaluation **is** specialization. - ---- - -## Design Goals - -### 1. Same Language, No Code Generation - -Unlike macro systems with separate DSLs or code-as-strings, comptime is just ReScript. You write what looks like a normal function. The compiler partially evaluates it. There is no "generate code" step — the function body contains both comptime and runtime expressions, and the compiler teases them apart. - -### 2. No Global State - -The Rust compiler is designed for concurrent compilation. Comptime must not introduce global state: - -- Each compilation unit gets its own QuickJS instance -- Type contexts are passed explicitly -- No `static mut` or `thread_local!` - -### 3. Hermetic Evaluation - -Following Zig's design, comptime has no I/O: - -- No file system access (except `@embedFile`) -- No network access -- No randomness -- Results are deterministic and cacheable - -QuickJS starts with a blank global scope by default — no `fs`, `fetch`, `process`. Only the comptime builtins are exposed. - -### 4. Explicit Opt-In - -Code must be explicitly marked for compile-time evaluation: - -```rescript -@comptime // Function can run at comptime -let helper = ... - -comptime T: type // Parameter must be comptime-known -``` - -### 5. Fuel Limits - -To prevent infinite loops from hanging the compiler: - -```rust -const DEFAULT_FUEL: usize = 100_000; -``` - -Each interpreter step decrements fuel. Exhaustion produces a compile error. - -### 6. Fully In-Memory - -Comptime code is compiled to JS and executed in-memory during compilation. No comptime artifacts are written to disk. No comptime JS appears in the compiled output. Comptime functions do their job during compilation and disappear — only the specialized runtime code remains. - ---- - -## Core Concepts - -### Comptime Functions - -Functions marked `@comptime` can execute at compile time when all comptime parameters are known: - -```rescript -@comptime -let double = (comptime x: int): int => x * 2 - -let a = double(5) // Comptime: becomes `let a = 10` -let b = double(runtime) // Error: runtime is not comptime-known -``` - -### Comptime Parameters - -Parameters marked `comptime` must be known at compile time. Non-comptime parameters become runtime code: - -```rescript -@comptime -let encode = (comptime T: type, value: T): JSON.t => { - switch @typeInfo(T) { - | String => JSON.Encode.string(value) // value is runtime - | Int => JSON.Encode.int(value) - | _ => @compileError(`Cannot encode ${@typeName(T)}`) - } -} - -let x = encode(string, myString) // T is comptime, value is runtime -let y = encode('a, something) // Error: 'a is not comptime-known -``` - -### Fully Resolved Types Required - -Comptime type parameters must be fully resolved — no unresolved type variables: - -```rescript -encode(user, myUser) // Fine: user is concrete -encode(array, myArr) // Fine: fully resolved -encode(array<'a>, myArr) // Error: 'a not comptime-known -encode(option, myOpt) // Fine: fully resolved - -// Polymorphism and comptime are opposites: -// - Polymorphism: works for any type at runtime -// - Comptime: specialized for a specific type at compile time -``` - -### Inline For - -Loops over comptime arrays are unrolled: - -```rescript -@comptime -let fields = @typeInfo(user)->getFields - -// This loop is unrolled at compile time -inline for field in fields { - Console.log(field.name) -} - -// Becomes: -Console.log("id") -Console.log("name") -Console.log("email") -``` - -### Comptime Types - -Comptime functions (value → value) use `@comptime` on `let` bindings. For type-level computation (type → type), use `@comptime` on a type declaration: - -```rescript -@comptime -type keyOf<'T> = { - switch @typeInfo('T) { - | Record({fields}) => - @buildVariant(inline for field in fields { - @variantCase({name: field.name->String.capitalize, as: field.name}) - }) - | _ => @compileError("@keyOf requires a record type") - } -} - -type user = { name: string, age: int, email: string } -type user_key = keyOf -// Produces: -// type user_key = -// | @as("name") Name -// | @as("age") Age -// | @as("email") Email -``` - -The type parameter `'T` must be fully resolved at the call site — `keyOf` works, `keyOf<'a>` is a compile error. This is consistent with comptime value functions: comptime parameters must be known at compile time. - -**Two kinds of comptime, same model:** - -| | Value-level | Type-level | -|---|---|---| -| **Syntax** | `@comptime let f = (comptime T: type, value: T) => ...` | `@comptime type f<'T> = ...` | -| **Input** | Comptime params + runtime values | Type parameters (must be concrete) | -| **Output** | Specialized runtime code | A new type declaration | -| **Usage** | `f(myType, myValue)` | `type t = f` | -| **Body** | Mix of comptime decisions + runtime expressions | Comptime only — type-building directives | - -#### Type-Building Builtins - -Comptime type bodies use these builtins to construct types: - -**`@buildVariant`** — build a variant type from `@variantCase` entries: - -```rescript -@buildVariant( - @variantCase({name: "Active", as: "active"}), - @variantCase({name: "Inactive"}), - @variantCase({name: "Suspended", deprecated: "Use Inactive instead"}), -) -``` - -**`@variantCase`** — describe a single variant constructor. Takes a record: - -```rescript -@variantCase({ - name: string, // required: constructor name - as?: string, // @as("...") JS representation - payload?: typeInfo, // constructor argument type(s) - deprecated?: string, // @deprecated("...") -}) -``` - -**`@buildRecord`** — build a record type from field descriptions: - -```rescript -@buildRecord(inline for field in fields { - @recordField({name: field.name, typ: field.typ, optional: true}) -}) -``` - -**`@recordField`** — describe a single record field: - -```rescript -@recordField({ - name: string, // required: field name - typ: typeInfo, // required: field type - optional?: bool, // x?: int - mutable_?: bool, // mutable x: int - as?: string, // @as("userName") -}) -``` - ---- - -## Type Introspection - -### The typeInfo Representation - -Types at compile time are represented as a variant. Since comptime requires fully resolved types, there are no unresolved type variables — the type info tree is always concrete. - -```rescript -type rec typeInfo = - // === Primitives === - | Int - | Float - | String - | Char - | Bool - | Unit - | Bigint - - // === Containers (always concrete element types) === - | Array({element: typeInfo}) - | Dict({value: typeInfo}) - | Option({inner: typeInfo}) - | Null({inner: typeInfo}) - | Nullable({inner: typeInfo}) - | Promise({value: typeInfo}) - | Tuple({elements: array}) - - // === Record === - | Record({ - name: string, - modulePath: string, - fields: array, - attributes: array, - unboxed: bool, - }) - - // === Variant === - | Variant({ - name: string, - modulePath: string, - constructors: array, - attributes: array, - unboxed: bool, - tag: option, // @tag("kind") → Some("kind") - }) - - // === Polymorphic Variant === - | PolyVariant({ - cases: array, - closed: bool, // [#A | #B] vs [> #A | #B] - }) - - // === Function === - | Function({ - args: array, - return: typeInfo, - }) - - // === Object type === - | Object({ - methods: array, - open_: bool, // {..} vs {.} - }) - - // === Opaque (ReScript type, definition hidden by module signature) === - | Opaque({ - name: string, - modulePath: string, - attributes: array, - }) - - // === External (JS interop type, no ReScript definition) === - | External({ - name: string, - modulePath: string, // "Js.Date", "Dom", "ReactDOM" - attributes: array, - bindings: array, - }) - - // === Alias (user-defined type alias) === - | Alias({ - name: string, - modulePath: string, - resolved: typeInfo, // what it actually is - attributes: array, - }) - - // === Recursive reference (breaks cycles in recursive types) === - | Recursive({name: string, modulePath: string}) -``` - -### Field Info - -```rescript -and fieldInfo = { - name: string, - typ: typeInfo, - mutable_: bool, - optional: bool, // x?: int - attributes: array, - jsName: string, // @as("userName") → "userName", else name -} -``` - -### Constructor Info - -```rescript -and constructorInfo = { - name: string, - args: constructorArgs, - attributes: array, - jsValue: option, -} - -and constructorArgs = - | NoArgs // | A - | TupleArgs(array) // | A(int, string) - | InlineRecord(array) // | A({x: int, y: string}) - -and constructorJsRepr = - | JsString(string) // @as("active") - | JsInt(int) // @as(0) - | JsBool(bool) // @as(true) - | JsNull // @as(null) - | JsUndefined // @as(undefined) -``` - -### Polymorphic Variant Case - -```rescript -and polyCase = { - name: string, // #A, #"some-name" - payload: option, - attributes: array, - jsValue: option, -} - -and polyPayload = - | Single(typeInfo) // #A(int) - | Multiple(array) // #A(int, string) -``` - -### Function Arg Info - -```rescript -and argInfo = { - label: argLabel, - typ: typeInfo, -} - -and argLabel = - | Positional - | Labeled(string) // ~name: string - | Optional(string) // ~name: string=? -``` - -### Object Method Info - -```rescript -and methodInfo = { - name: string, - typ: typeInfo, -} -``` - -### Attributes - -```rescript -and attribute = { - name: string, - payload: option, -} -``` - -### External Bindings (Sum Type) - -External bindings represent JS interop declarations associated with an external type. Each binding is exactly one thing: - -```rescript -and externalBinding = - | Constructor({ // @new external make: unit => t = "Date" - name: string, - jsName: string, - args: array, - return: typeInfo, - }) - | Method({ // @send external toISOString: t => string - name: string, - jsName: string, - args: array, // excluding self - return: typeInfo, - }) - | Getter({ // @get external length: t => int = "length" - name: string, - jsName: string, - typ: typeInfo, - }) - | Setter({ // @set external setName: (t, string) => unit - name: string, - jsName: string, - typ: typeInfo, - }) - | StaticMethod({ // @scope("Date") @val external now: unit => float - name: string, - jsName: string, - args: array, - return: typeInfo, - }) - | GlobalValue({ // @val external document: t = "document" - name: string, - jsName: string, - }) - | ModuleImport({ // @module("moment") external moment: string => t - name: string, - jsName: string, - from: string, - args: array, - return: typeInfo, - }) -``` - -### Opaque vs External - -These are fundamentally different: - -- **Opaque**: A ReScript type with a hidden definition. It *has* structure, you just can't see it from outside the module. If comptime runs *inside* the defining module, it sees through to the real type. -- **External**: A JS value with no ReScript definition at all. It has whatever shape JS gave it. The `bindings` field exposes what the compiler knows about its JS API. - -```rescript -@comptime -let rec encodeField = (comptime T: type, value: T): JSON.t => { - switch @typeInfo(T) { - | String => JSON.Encode.string(value) - | Int => JSON.Encode.int(value) - | Record({fields}) => ... - | Opaque(_) => - // There IS a definition, but it's hidden. - @compileError(`${@typeName(T)} is opaque. Expose the type or add @encode.`) - | External({bindings}) => - // JS type — try to find a serialization method - let hasToJSON = bindings->Array.find(b => - switch b { - | Method({jsName: "toJSON"}) => true - | _ => false - } - ) - switch hasToJSON { - | Some(Method(m)) => value->@send(m.jsName) - | _ => @compileError(`${@typeName(T)} is external with no known serialization`) - } - | ... - } -} -``` - -### Introspection Builtins - -```rescript -@typeInfo(user) // → Record({fields: [...], ...}) -@typeName(user) // → "user" -@getAttr(field, "json.key") // → option -@field(value, field.name) // → field access with comptime-known name -@compileError(msg) // → emit compile error -@embedFile(path) // → embed file contents as string -``` - -### Type Alias Resolution - -Built-in aliases are always fully resolved: - -```rescript -@typeInfo(Array.t) // → Array({element: Int}) -@typeInfo(array) // → Array({element: Int}) -// identical — Array.t is just an alias for array -``` - -User-defined aliases are resolved by default. The original alias name is available if needed but the common case is simple: - -```rescript -type userId = string -type user = { id: userId, name: string } - -@typeInfo(user).fields[0].typ // → String (fully resolved) -``` - -### Recursive Types - -```rescript -type rec tree = { value: int, children: array } - -@typeInfo(tree) -// → Record({ -// name: "tree", -// fields: [ -// {name: "value", typ: Int}, -// {name: "children", typ: Array({element: Recursive({name: "tree"})})}, -// ] -// }) -``` - -The `Recursive` case breaks the cycle. Call `@typeInfo` again on the referenced type to follow it. - ---- - -## Execution Model: QuickJS - -### Why QuickJS? - -ReScript already compiles to JavaScript. Instead of writing a custom interpreter in Rust, comptime functions are compiled to JS through the normal pipeline and executed with QuickJS embedded in the compiler. - -- **Small** (~200KB compiled into the Rust binary), no external dependencies -- **Blank global scope** by default — hermetic by design, only expose comptime builtins -- **ES2020** support — plenty for comptime workloads -- **No JIT needed** — comptime code is short-lived, evaluating type info and unrolling loops - -### Architecture: Partial Evaluation - -QuickJS doesn't produce code — it **makes decisions** that the compiler uses to specialize: - -1. Compiler walks the `@comptime` function's AST -2. Hits `@typeInfo(T)` → evaluates via host function, gets type info -3. Hits `switch` on comptime value → QuickJS evaluates the scrutinee, compiler keeps only the matching branch -4. Hits `inline for` → QuickJS evaluates the array, compiler unrolls the loop -5. Hits `@getAttr(field, "json.key")` → QuickJS evaluates, returns the attribute value -6. Runtime expressions are kept as AST with comptime values substituted as constants - -QuickJS handles **computation** (string parsing, attribute lookup, conditional logic). The compiler handles **specialization** (branch selection, loop unrolling, constant substitution, recursive inlining). - -### In-Memory Compilation Flow - -``` -@comptime function source - ↓ normal parse + type check -Typed AST - ↓ compile to JS (in memory, never written to disk) -JS source string - ↓ stored in CompiledModule.comptime_js - ↓ (available for cross-module comptime calls) - -When called with comptime-known arguments: - ↓ load into QuickJS context - ↓ execute — calls host functions for @typeInfo etc. - ↓ returns decisions/values - ↓ compiler specializes the original AST -Specialized AST (comptime parts resolved, runtime parts remain) - ↓ type check (normal) - ↓ Lambda lowering (normal) - ↓ JS codegen (normal) -Output JS (no trace of comptime) -``` - -### Module State - -Each compiled module carries comptime JS in memory alongside its normal compilation output: - -```rust -struct CompiledModule { - signature: ModuleSignature, // types, for downstream type checking - lambda: Lambda, // runtime code, for JS emission - comptime_js: HashMap, // fn_name → JS source, in memory only -} -``` - -### Cross-Module Comptime - -When `User.res` calls a comptime function from `Codec.res`: - -1. `Codec.res` was already compiled (dependency order) -2. Its comptime JS is in memory in `CompiledModule.comptime_js` -3. Load into the QuickJS context via custom module loader -4. Execute — the call chain works naturally across modules - -QuickJS's custom module loader resolves imports from the compiler's in-memory module map: - -```rust -context.set_module_loader(|module_name| { - compiled_modules.get(module_name) - .map(|m| m.comptime_js_bundle()) -}); -``` - -### Host Functions - -The compiler exposes these to QuickJS: - -```rust -// Type introspection — reads from the compiler's type environment -__comptime_typeInfo(type_path) // → JS object with type structure -__comptime_typeName(type_path) // → string -__comptime_getAttr(field, name) // → string | null -__comptime_compileError(msg) // → throws, compiler catches as compile error -``` - -These cross the Rust-QuickJS FFI boundary. Rust's borrow checker ensures the type environment isn't mutated while QuickJS is reading it. - ---- - -## Why an Integrated In-Process Compiler - -Comptime could theoretically be built on a traditional batch compiler (like OCaml's `bsc`). But an integrated, in-process Rust compiler is fundamentally better suited for it. Here's why. - -### Comptime Erases the Phase Distinction - -A traditional compiler has rigid phases: Parse → Type Check → Lower → Codegen. Each phase completes fully before the next. Artifacts on disk are the boundaries. - -Comptime **destroys this model.** When the compiler hits `@encoder` on a type: - -1. Type checking must pause -2. Comptime code must execute — which requires type info from *this* and *other* modules -3. Comptime produces specialized code -4. That code must be type-checked -5. The newly type-checked code might trigger more comptime -6. Only then can type checking continue - -This is not a pipeline. It's a **conversation** between compilation phases. An in-process compiler does it naturally — all the state is right there. - -### In-Memory Module Graph - -The in-process compiler holds the entire project in memory — all modules' types, signatures, comptime JS, the full dependency graph. This changes what's possible: - -**Comptime dependency resolution is trivial.** When `User.res` hits `@encoder`, the compiler needs the comptime JS for `Spice.encoder`. It's already in memory — compiled earlier in dependency order. Just hand QuickJS a reference. No file lookup, no deserialization, no cache invalidation. - -With a batch compiler, you'd need to serialize comptime JS to disk (a `.comptime` artifact), load it when needed, track a second dependency graph for comptime deps, and handle cache invalidation across packages. You're building a second build system inside the build system. - -### Comptime Dependency Chains - -```rescript -// Package: rescript-schema (comptime JSON schema parser) -@comptime -let parseJsonSchema = (input: string): Schema.t => { ... } - -// Package: rescript-api-gen (depends on rescript-schema) -@comptime.derive("api") -let api = (comptime decl: typeDeclaration): ... => { - let schema = @embedFile(@getAttr(decl, "schema")) - let parsed = Schema.parseJsonSchema(schema) // cross-package comptime call - generateEndpoints(parsed, decl) -} - -// User's code (depends on rescript-api-gen) -@api @schema("./openapi.json") -type endpoints -``` - -**In-process:** All comptime JS from the dependency chain is in memory. QuickJS loads and calls across packages naturally. The compiler knows the full dependency graph and invalidates precisely. - -**Batch:** Each package compiled separately. Need a new artifact format, a resolver for comptime artifacts across packages, a dependency tracker that distinguishes comptime deps from runtime deps, and cross-package cache invalidation. Every piece is duplicated infrastructure. - -### The Type Environment as a Live Query Engine - -When comptime calls `@typeInfo(user)`, the compiler walks its in-memory type environment — arena-allocated, indexed access, no serialization. The query is a function call. - -In a batch compiler, the type environment for other modules was serialized to `.cmi` and discarded. To answer `@typeInfo(User.user)` from `App.res`, you'd need to deserialize `.cmi` files back into queryable structures. And `.cmi` files are lossy — they contain signatures, not full internal representations. Attributes on fields, internal aliases, implementation details needed by comptime may not survive the round-trip. - -### IDE Integration - -Comptime-generated code needs to work seamlessly in the IDE: - -```rescript -@encoder @decoder -type user = { name: string, age: int } - -let json = encode_user(myUser) -// ^^^^^^^^^^^ -// hover: (user) => JSON.t -// go-to-def: → generated by @encoder (Spice.res:15) -``` - -**In-process compiler as LSP backend:** The compiler is a long-lived process with the full module graph, all comptime results, all provenance. When the user edits the `user` type, the compiler incrementally re-runs `@encoder`, updates types, pushes new diagnostics. One process, one source of truth. - -**Batch compiler as LSP backend:** The LSP server shells out to `bsc`, reads `.cmi` files. Generated code provenance is lost. Go-to-definition through comptime requires a separate provenance database. Re-running comptime on edit means re-invoking the compiler and re-reading artifacts. - -### Incremental Comptime Caching - -The in-process compiler can cache comptime results with fine granularity: - -```rust -struct ComptimeCache { - // Key: hash of (comptime function identity + type declaration + attributes) - // Value: specialized AST - cache: HashMap>, -} -``` - -When a type hasn't changed and the derive function hasn't changed, skip re-evaluation entirely. Precise, minimal invalidation because the compiler has the full before/after state in memory. - -### Concurrency - -Each module gets its own `ComptimeEngine` with its own QuickJS instance. Rust's ownership model ensures no shared mutable state between compilation units. Independent modules can compile (and run comptime) in parallel. - -### Rust-QuickJS FFI Safety - -The comptime boundary between Rust and QuickJS is hot — every `@typeInfo` call crosses it. Rust's type system (lifetimes, borrow checker) ensures the type environment isn't mutated during QuickJS callbacks. OCaml's C FFI with QuickJS would require manual GC management (`CAMLparam`/`CAMLreturn` stubs) with no static enforcement. - -### Summary - -| | Batch Compiler | In-Process Rust Compiler | -|---|---|---| -| Phase interleaving | Serialize/deserialize workarounds | Natural — call between phases | -| Cross-module type queries | Deserialize .cmi, lossy | Direct memory access, full fidelity | -| Comptime dependency chains | Second artifact format + build system | Just the module graph | -| IDE integration | Re-run compiler, re-read artifacts | Live state, incremental updates | -| Caching | Disk-based, coarse | In-memory, per-derive granularity | -| Concurrency | GIL / subprocess-per-module | Threads with ownership | - ---- - -## Derive Attributes - -### Rust-Inspired Derives - -Like Rust's `#[derive(Serialize, Deserialize)]`, ReScript comptime supports derive attributes on type declarations: - -```rescript -@encoder @decoder -type user = { - name: string, - @json.key("user_age") age: int, - email: option, -} - -// ↑ automatically generates encode_user and decode_user -``` - -### Defining a Derive Handler - -A derive handler is a comptime function registered to an attribute name: - -```rescript -@comptime.derive("encoder") -let encoder = (comptime T: type) => { - (value: T): JSON.t => { - switch @typeInfo(T) { - | Record({fields}) => - let obj = Dict.make() - inline for field in fields { - let key = @getAttr(field, "json.key")->Option.getOr(field.name) - Dict.set(obj, key, encodeField(field.typ, @field(value, field.name))) - } - JSON.Encode.object(obj) - | _ => @compileError(`@encoder requires a record type`) - } - } -} - -@comptime -let rec encodeField = (comptime T: type, value: T): JSON.t => { - switch @typeInfo(T) { - | String => JSON.Encode.string(value) - | Int => JSON.Encode.int(value) - | Float => JSON.Encode.float(value) - | Bool => JSON.Encode.bool(value) - | Option(inner) => - switch value { - | Some(v) => encodeField(inner, v) - | None => JSON.Null - } - | Array(elem) => - value->Array.map(v => encodeField(elem, v))->JSON.Encode.array - | External({bindings}) => - switch bindings->Array.find(b => - switch b { | Method({jsName: "toJSON"}) => true | _ => false } - ) { - | Some(Method(m)) => value->@send(m.jsName) - | _ => @compileError(`Cannot encode external type ${@typeName(T)}`) - } - | Opaque(_) => - @compileError(`${@typeName(T)} is opaque. Expose the type or add @encode attribute.`) - | _ => @compileError(`Cannot encode ${@typeName(T)}`) - } -} -``` - -### What the Compiler Does - -When processing: - -```rescript -@encoder @decoder -type user = { name: string, @json.key("user_age") age: int, email: option } -``` - -1. Type check the `user` declaration normally -2. See `@encoder` attribute → look up the registered derive handler -3. Call the handler in QuickJS with `T = user` -4. Compiler specializes the result (partial evaluation resolves all comptime expressions) -5. Splice the specialized function in after the type declaration -6. Type check it normally -7. Repeat for `@decoder` - -The user's file effectively becomes: - -```rescript -type user = { name: string, @json.key("user_age") age: int, email: option } - -// generated by @encoder — fully specialized, no type dispatch at runtime -let encode_user = (value: user): JSON.t => { - let obj = Dict.make() - Dict.set(obj, "name", JSON.Encode.string(value.name)) - Dict.set(obj, "user_age", JSON.Encode.int(value.age)) - Dict.set(obj, "email", switch value.email { - | Some(v) => JSON.Encode.string(v) - | None => JSON.Null - }) - JSON.Encode.object(obj) -} - -// generated by @decoder -let decode_user = (json: JSON.t): result => { ... } -``` - -### Decoder Example - -```rescript -@comptime.derive("decoder") -let decoder = (comptime T: type) => { - (json: JSON.t): result => { - switch @typeInfo(T) { - | Record({fields}) => - switch JSON.Classify.classify(json) { - | JSONObject(dict) => - inline for field in fields { - let key = @getAttr(field, "json.key")->Option.getOr(field.name) - let raw = Dict.get(dict, key) - switch (raw, field.optional) { - | (None, false) => return Error(`Missing field: ${key}`) - | _ => () - } - } - // ... build record from decoded fields - | _ => Error("Expected object") - } - | _ => @compileError(`@decoder requires a record type`) - } - } -} -``` - -### Registration (TBD) - -How derive attributes are registered to handlers is an open design question. Options include: - -- **Config-based:** `rescript.json` maps attribute names to handler modules -- **Convention-based:** `@encoder` looks for a module `Encoder` with a `@comptime.derive` export -- **Declaration-based:** `@comptime.derive("encoder")` self-registers when the module is compiled - -The exact mechanism can be decided later. The important thing is: the user's experience is just `@encoder` on a type. - ---- - -## Replacing PPXs - -### Overview - -Comptime can replace all current PPX use cases because: - -1. **PPXs receive strings** via extension points -2. **Comptime can parse strings** at compile time -3. **Both generate code** based on the parsed/introspected information - -### 1. JSON Serialization (ppx_spice, Decco) - -**Current PPX:** -```rescript -@spice -type user = { - name: string, - @spice.key("user_age") age: int, - email: option, -} -// Generates: user_encode, user_decode -``` - -**With Comptime:** -```rescript -// Codec.res - Generic JSON codec generator -@comptime -let rec encodeField = (comptime T: type, value: T): JSON.t => { - switch @typeInfo(T) { - | String => JSON.Encode.string(value) - | Int => JSON.Encode.int(value) - | Float => JSON.Encode.float(value) - | Bool => JSON.Encode.bool(value) - | Option(inner) => - switch value { - | Some(v) => encodeField(inner, v) - | None => JSON.Null - } - | Array(elem) => - value->Array.map(v => encodeField(elem, v))->JSON.Encode.array - | Record({fields}) => - let obj = Dict.make() - inline for field in fields { - let key = @getAttr(field, "json.key")->Option.getOr(field.name) - Dict.set(obj, key, encodeField(field.typ, @field(value, field.name))) - } - JSON.Encode.object(obj) - | External({bindings}) => - switch bindings->Array.find(b => - switch b { | Method({jsName: "toJSON"}) => true | _ => false } - ) { - | Some(_) => value->@send("toJSON") - | None => @compileError(`Cannot encode external type ${@typeName(T)}`) - } - | Opaque(_) => - @compileError(`${@typeName(T)} is opaque. Expose the type or add @encode.`) - | _ => @compileError(`Unsupported type for JSON encoding: ${@typeName(T)}`) - } -} - -@comptime.derive("encoder") -let encoder = (comptime T: type) => { - (value: T): JSON.t => { - switch @typeInfo(T) { - | Record({fields}) => - let obj = Dict.make() - inline for field in fields { - let key = @getAttr(field, "json.key")->Option.getOr(field.name) - Dict.set(obj, key, encodeField(field.typ, @field(value, field.name))) - } - JSON.Encode.object(obj) - | _ => @compileError(`@encoder requires a record type`) - } - } -} - -@comptime -let rec decodeField = (comptime T: type, json: JSON.t): result => { - switch @typeInfo(T) { - | String => - switch JSON.Classify.classify(json) { - | JSONString(s) => Ok(s) - | _ => Error(`Expected string, got ${JSON.Encode.stringify(json)}`) - } - | Int => - switch JSON.Classify.classify(json) { - | JSONNumber(n) => Ok(Int.fromFloat(n)) - | _ => Error(`Expected int`) - } - | Float => - switch JSON.Classify.classify(json) { - | JSONNumber(n) => Ok(n) - | _ => Error(`Expected float`) - } - | Bool => - switch JSON.Classify.classify(json) { - | JSONTrue => Ok(true) - | JSONFalse => Ok(false) - | _ => Error(`Expected bool`) - } - | Option(inner) => - switch JSON.Classify.classify(json) { - | JSONNull => Ok(None) - | _ => decodeField(inner, json)->Result.map(v => Some(v)) - } - | Array(elem) => - switch JSON.Classify.classify(json) { - | JSONArray(arr) => - arr->Array.map(v => decodeField(elem, v))->Array.reduce(Ok([]), (acc, r) => - switch (acc, r) { - | (Ok(arr), Ok(v)) => Ok(Array.concat(arr, [v])) - | (Error(e), _) => Error(e) - | (_, Error(e)) => Error(e) - } - ) - | _ => Error("Expected array") - } - | Record({fields}) => - switch JSON.Classify.classify(json) { - | JSONObject(dict) => - inline for field in fields { - let key = @getAttr(field, "json.key")->Option.getOr(field.name) - let raw = Dict.get(dict, key) - switch (raw, field.optional) { - | (Some(v), _) => - switch decodeField(field.typ, v) { - | Error(e) => return Error(`${field.name}: ${e}`) - | Ok(_) => () - } - | (None, true) => () - | (None, false) => return Error(`Missing field: ${key}`) - } - } - Ok(@buildRecord(T)) - | _ => Error("Expected object") - } - | _ => @compileError(`Cannot decode ${@typeName(T)}`) - } -} - -// Usage -@encoder @decoder -type user = { - name: string, - @json.key("user_age") age: int, - email: option, -} - -let json = encode_user({name: "Alice", age: 30, email: Some("alice@example.com")}) -let user = decode_user(json) -``` - -### 2. GraphQL (graphql-ppx, rescript-relay) - -**Current PPX:** -```rescript -module UserQuery = %graphql(` - query UserQuery($id: ID!) { - user(id: $id) { - id - name - email - } - } -`) -``` - -**With Comptime:** -```rescript -// graphql/parser.res - GraphQL parser written in ReScript, runs in QuickJS - -type token = - | LBrace | RBrace | LParen | RParen | Colon | Bang | Dollar - | Name(string) | StringLit(string) | IntLit(int) - -type graphqlType = - | Named(string) - | NonNull(graphqlType) - | List(graphqlType) - -type variable = {name: string, typ: graphqlType} -type field = {name: string, alias: option, args: array, selectionSet: array} -and argument = {name: string, value: argumentValue} -and argumentValue = Variable(string) | StringValue(string) | IntValue(int) | BoolValue(bool) - -type operation = { - kind: [#query | #mutation | #subscription], - name: option, - variables: array, - selectionSet: array, -} - -@comptime -let tokenize = (comptime input: string): array => { - let tokens = [] - let i = ref(0) - let len = String.length(input) - - while i.contents < len { - let c = String.get(input, i.contents) - switch c { - | '{' => { Array.push(tokens, LBrace); i := i.contents + 1 } - | '}' => { Array.push(tokens, RBrace); i := i.contents + 1 } - | '(' => { Array.push(tokens, LParen); i := i.contents + 1 } - | ')' => { Array.push(tokens, RParen); i := i.contents + 1 } - | ':' => { Array.push(tokens, Colon); i := i.contents + 1 } - | '!' => { Array.push(tokens, Bang); i := i.contents + 1 } - | '$' => { Array.push(tokens, Dollar); i := i.contents + 1 } - | ' ' | '\n' | '\t' | '\r' | ',' => i := i.contents + 1 - | '#' => { - while i.contents < len && String.get(input, i.contents) != '\n' { - i := i.contents + 1 - } - } - | 'a'..'z' | 'A'..'Z' | '_' => { - let start = i.contents - while i.contents < len { - let ch = String.get(input, i.contents) - switch ch { - | 'a'..'z' | 'A'..'Z' | '0'..'9' | '_' => i := i.contents + 1 - | _ => break - } - } - Array.push(tokens, Name(String.sub(input, start, i.contents - start))) - } - | '"' => { - i := i.contents + 1 - let start = i.contents - while i.contents < len && String.get(input, i.contents) != '"' { - i := i.contents + 1 - } - Array.push(tokens, StringLit(String.sub(input, start, i.contents - start))) - i := i.contents + 1 - } - | '0'..'9' => { - let start = i.contents - while i.contents < len { - let ch = String.get(input, i.contents) - switch ch { - | '0'..'9' => i := i.contents + 1 - | _ => break - } - } - Array.push(tokens, IntLit(Int.fromString(String.sub(input, start, i.contents - start))->Option.getExn)) - } - | _ => @compileError(`Unexpected character in GraphQL: '${String.make(1, c)}'`) - } - } - tokens -} - -@comptime -let parse = (comptime tokens: array): operation => { - let pos = ref(0) - - let peek = () => tokens[pos.contents] - let advance = () => { pos := pos.contents + 1 } - let expect = (expected: token) => { - if peek() != expected { - @compileError(`Expected ${tokenToString(expected)}, got ${tokenToString(peek())}`) - } - advance() - } - - let kind = switch peek() { - | Name("query") => { advance(); #query } - | Name("mutation") => { advance(); #mutation } - | Name("subscription") => { advance(); #subscription } - | _ => #query - } - - let name = switch peek() { - | Name(n) if n != "query" && n != "mutation" => { advance(); Some(n) } - | _ => None - } - - let variables = switch peek() { - | LParen => { - advance() - let vars = [] - while peek() != RParen { - expect(Dollar) - let varName = switch peek() { - | Name(n) => { advance(); n } - | _ => @compileError("Expected variable name") - } - expect(Colon) - let varType = parseType(tokens, pos) - Array.push(vars, {name: varName, typ: varType}) - } - expect(RParen) - vars - } - | _ => [] - } - - expect(LBrace) - let selectionSet = parseSelectionSet(tokens, pos) - expect(RBrace) - - {kind, name, variables, selectionSet} -} - -// graphql/codegen.res - Type generation from parsed query -@comptime -let graphql = (comptime query: string) => { - let tokens = GraphQL.Parser.tokenize(query) - let operation = GraphQL.Parser.parse(tokens) - GraphQL.Validator.validate(operation, Schema.schema) - GraphQL.Codegen.generateTypes(operation, Schema.schema) -} - -// Usage -module UserQuery = graphql(` - query UserQuery($id: ID!) { - user(id: $id) { - id - name - email - } - } -`) - -// Generated types available: -// UserQuery.Variables = {id: string} -// UserQuery.Response = {user: {id: string, name: string, email: option}} -// UserQuery.query = "query UserQuery($id: ID!) { ... }" -``` - -### 3. CSS-in-JS (styled-ppx) - -**Current PPX:** -```rescript -module Button = %styled.button(` - background-color: blue; - padding: 10px 20px; - &:hover { - background-color: darkblue; - } -`) -``` - -**With Comptime:** -```rescript -// css/parser.res - CSS parser - -type cssValue = - | Keyword(string) - | Length(float, string) // 10px, 2em, etc. - | Color(string) - | Number(float) - -type cssRule = { - property: string, - value: cssValue, -} - -type cssBlock = { - selector: string, - rules: array, - nested: array, -} - -@comptime -let parseCSS = (comptime input: string): cssBlock => { - let tokens = tokenizeCSS(input) - parseCSSBlock(tokens, "&") -} - -@comptime -let tokenizeCSS = (comptime input: string): array => { - let tokens = [] - let i = ref(0) - let len = String.length(input) - - while i.contents < len { - let c = String.get(input, i.contents) - switch c { - | '{' => { Array.push(tokens, LBrace); i := i.contents + 1 } - | '}' => { Array.push(tokens, RBrace); i := i.contents + 1 } - | ':' => { Array.push(tokens, Colon); i := i.contents + 1 } - | ';' => { Array.push(tokens, Semi); i := i.contents + 1 } - | ' ' | '\n' | '\t' => i := i.contents + 1 - | '-' | 'a'..'z' | 'A'..'Z' => { - let start = i.contents - while i.contents < len { - let ch = String.get(input, i.contents) - switch ch { - | 'a'..'z' | 'A'..'Z' | '0'..'9' | '-' | '_' => i := i.contents + 1 - | _ => break - } - } - Array.push(tokens, Ident(String.sub(input, start, i.contents - start))) - } - | '0'..'9' | '.' => { - let start = i.contents - while i.contents < len { - let ch = String.get(input, i.contents) - switch ch { - | '0'..'9' | '.' => i := i.contents + 1 - | _ => break - } - } - let numStr = String.sub(input, start, i.contents - start) - let unitStart = i.contents - while i.contents < len { - let ch = String.get(input, i.contents) - switch ch { - | 'a'..'z' | '%' => i := i.contents + 1 - | _ => break - } - } - let unit = String.sub(input, unitStart, i.contents - unitStart) - Array.push(tokens, Dimension(Float.fromString(numStr)->Option.getExn, unit)) - } - | '#' => { - i := i.contents + 1 - let start = i.contents - while i.contents < len { - let ch = String.get(input, i.contents) - switch ch { - | '0'..'9' | 'a'..'f' | 'A'..'F' => i := i.contents + 1 - | _ => break - } - } - Array.push(tokens, Hash(String.sub(input, start, i.contents - start))) - } - | '&' => { Array.push(tokens, Ampersand); i := i.contents + 1 } - | _ => i := i.contents + 1 - } - } - tokens -} - -// css/validator.res - CSS property validation - -let validProperties = [ - "background-color", "color", "padding", "margin", "width", "height", - "display", "flex", "border", "font-size", "font-weight", // ... -] - -@comptime -let validateCSS = (comptime block: cssBlock): unit => { - block.rules->Array.forEach(rule => { - if !Array.includes(validProperties, rule.property) { - @compileError(`Unknown CSS property: ${rule.property}`) - } - }) - block.nested->Array.forEach(validateCSS) -} - -// css/styled.res - Generate Emotion styles - -@comptime -let generateClassName = (comptime css: string): string => { - let hash = hashString(css) - `css-${hash}` -} - -@comptime -let styled = (comptime tag: string, comptime css: string) => { - let block = CSS.Parser.parseCSS(css) - CSS.Validator.validateCSS(block) - - let className = generateClassName(css) - let cssString = CSS.Printer.print(block) - - // Inject CSS at module load time - @sideEffect - Emotion.injectGlobal(`.${className} { ${cssString} }`) - - // Return component - React.forwardRef((props, ref) => { - React.createElement( - tag, - { - ...props, - className: className, - ref: ref, - } - ) - }) -} - -// Usage -let Button = styled("button", ` - background-color: blue; - padding: 10px 20px; - &:hover { - background-color: darkblue; - } -`) - -// Usage in JSX - -``` - -### 4. SQL (rescript-embed-lang) - -**Current approach:** -```rescript -let findMovie = %sql.one(`SELECT id, title FROM movies WHERE id = $id`) -``` - -**With Comptime:** -```rescript -// sql/parser.res - SQL parser - -type sqlExpr = - | Column(string) - | Param(string) - | Literal(literal) - | BinOp(sqlExpr, binOp, sqlExpr) - -type selectQuery = { - columns: array, - from: string, - where: option, - orderBy: array<(string, [#asc | #desc])>, - limit: option, -} - -@comptime -let parseSQL = (comptime input: string): sqlQuery => { - let tokens = tokenizeSQL(input) - parseSQLQuery(tokens) -} - -// sql/codegen.res - Type generation - -@comptime -let sql = (comptime query: string, comptime schema: DBSchema) => { - let parsed = SQL.Parser.parseSQL(query) - - // Extract parameters ($id, $name, etc.) - let params = extractParams(parsed) - - // Infer column types from schema - let columns = switch parsed { - | Select(q) => q.columns->Array.map(col => { - let table = schema.tables->Array.find(t => t.name == q.from)->Option.getExn - let column = table.columns->Array.find(c => c.name == col.name)->Option.getExn - {name: col.alias->Option.getOr(col.name), typ: column.typ} - }) - | _ => [] - } - - { - query: query, - execute: (db, params) => db.query(query, params), - } -} - -// Usage -let findMovie = sql( - `SELECT id, title FROM movies WHERE id = $id`, - MovieDB.schema -) - -// Type-safe usage: -let movie = await findMovie.execute(db, {id: "123"}) -// movie: {id: string, title: string} -``` - -### 5. TypeScript Binding Helpers (ppx_ts) - -**Current PPX:** -```rescript -@ppx_ts.keyOf -type config = { - host: string, - port: int, -} -// Generates: type config_keyOf = Host | Port -``` - -**With Comptime:** -```rescript -@comptime.derive("keyOf") -let keyOf = (comptime T: type) => { - switch @typeInfo(T) { - | Record({fields}) => - inline for field in fields { - | @variant(String.capitalize(field.name)) - } - | _ => @compileError("keyOf requires a record type") - } -} - -@comptime.derive("keyToString") -let keyToString = (comptime T: type) => { - let keyType = keyOf(T) - (key: keyType): string => { - switch key { - inline for field in @typeInfo(T)->getFields { - | @variant(String.capitalize(field.name)) => field.name - } - } - } -} - -// Usage -@keyOf -type config = { - host: string, - port: int, -} - -// Generated: type config_key = Host | Port -// Generated: let config_keyToString = ... - -let key: config_key = Host -Console.log(config_keyToString(key)) // "host" -``` - -### 6. Form Bindings (ppx_react_hook_form) - -**With Comptime:** -```rescript -@comptime.derive("form") -let makeForm = (comptime T: type) => { - switch @typeInfo(T) { - | Record({fields}) => - { - useForm: () => { - let form = ReactHookForm.useForm() - - inline for field in fields { - let register = form.register(field.name) - } - - form - }, - - // Type-safe field accessors - fields: inline for field in fields { - @record(field.name, FormField(field.typ)) - }, - } - | _ => @compileError("@form requires a record type") - } -} - -// Usage -@form -type loginForm = { - email: string, - password: string, - rememberMe: bool, -} - -// Generated: LoginForm module with useForm() and typed fields - -@react.component -let make = () => { - let form = LoginForm.useForm() - -
Console.log(data))}> - - - - -
-} -``` - ---- - -## Examples - -### Complete Example: Type-Safe API Client - -```rescript -// api/schema.res - API schema definition -type endpoint<'params, 'response> = { - method: [#GET | #POST | #PUT | #DELETE], - path: string, - params: 'params, - response: 'response, -} - -type user = { - id: string, - name: string, - email: string, -} - -type createUserParams = { - name: string, - email: string, -} - -// api/client.res - Client generator -@comptime -let makeClient = (comptime endpoints: array<(string, endpoint<'p, 'r>)>) => { - inline for (name, ep) in endpoints { - @record(name, (ep.params) => { - fetch(ep.path, { - method: ep.method, - body: Json.stringify(ep.params), - }) - }) - } -} - -// api/endpoints.res - Define endpoints -let endpoints = [ - ("getUser", { - method: #GET, - path: "/users/:id", - params: type {id: string}, - response: type user, - }), - ("createUser", { - method: #POST, - path: "/users", - params: type createUserParams, - response: type user, - }), - ("deleteUser", { - method: #DELETE, - path: "/users/:id", - params: type {id: string}, - response: type {success: bool}, - }), -] - -// Usage -let client = makeClient(endpoints) - -// Fully typed! -let user = await client.getUser({id: "123"}) -let newUser = await client.createUser({name: "Alice", email: "alice@example.com"}) -let result = await client.deleteUser({id: "123"}) -``` - -### Complete Example: ORM Query Builder - -```rescript -// orm/schema.res -type column<'t> = { - name: string, - typ: 't, - nullable: bool, - primaryKey: bool, -} - -type table<'row> = { - name: string, - columns: array>, -} - -// orm/query.res -@comptime -let makeTable = (comptime name: string, comptime T: type): table => { - switch @typeInfo(T) { - | Record({fields}) => - { - name: name, - columns: fields->Array.map(f => { - name: f.name, - typ: f.typ, - nullable: f.optional, - primaryKey: @hasAttr(f, "primaryKey"), - }), - } - | _ => @compileError("Table row must be a record type") - } -} - -@comptime -let select = (comptime table: table<'row>) => { - { - from: table.name, - columns: All, - where: None, - orderBy: [], - limit: None, - - where: (condition) => { ...self, where: Some(condition) }, - orderBy: (column, dir) => { ...self, orderBy: [...self.orderBy, (column, dir)] }, - limit: (n) => { ...self, limit: Some(n) }, - - execute: async (db) => { - let sql = buildSQL(self) - let rows = await db.query(sql) - rows->Array.map(row => parseRow(row, table)) - }, - } -} - -// Usage -type user = { - @primaryKey id: string, - name: string, - email: option, - createdAt: Date.t, -} - -let Users = makeTable("users", user) - -let activeUsers = await - select(Users) - ->where(u => u.createdAt > Date.now() - days(30)) - ->orderBy("createdAt", #desc) - ->limit(10) - ->execute(db) - -// activeUsers: array -``` - ---- - -## Implementation Plan - -### Phase 1: Core Infrastructure - -**Goal:** QuickJS integration, basic comptime evaluation - -1. Embed QuickJS in the Rust compiler via `rquickjs` -2. Add `@comptime` attribute parsing -3. Compile `@comptime` functions to JS (in memory) -4. Implement comptime parameter detection and specialization -5. Add fuel limits and error handling -6. Implement basic partial evaluation (switch on comptime values, constant substitution) - -### Phase 2: Type Introspection - -**Goal:** Enable `@typeInfo` and related builtins - -1. Define the full `typeInfo` type in Rust -2. Implement `typeInfo` conversion from compiler internals -3. Register `__comptime_typeInfo` as QuickJS host function -4. Implement `@typeName`, `@getAttr`, `@field`, `@compileError` -5. Handle Opaque vs External distinction -6. Expose external binding info - -### Phase 3: Partial Evaluation - -**Goal:** Zig-style specialization - -1. Implement `inline for` loop unrolling -2. Implement switch branch elimination on comptime values -3. Implement recursive comptime specialization -4. Implement constant inlining from comptime results -5. Splice specialized AST back into module structure - -### Phase 4: Derive System - -**Goal:** Attribute-triggered comptime - -1. Implement `@comptime.derive` registration -2. Implement derive invocation at type declaration boundaries -3. Declaration-level interleaving (pause type checking → run comptime → splice → resume) -4. Cross-module comptime (load comptime JS from in-memory module graph) -5. Error reporting with comptime provenance - -### Phase 5: Standard Library & Tooling - -**Goal:** Practical comptime libraries and IDE support - -1. JSON codec generator (encoder/decoder) -2. Parser utilities for DSLs -3. LSP support for comptime-generated code (hover, go-to-def, provenance) -4. Comptime result caching - ---- - -## Appendix: Zig Comptime Reference - -### How Zig Does It - -Zig's compiler uses a multi-stage pipeline: - -1. **AST → ZIR**: Source is parsed into Zig Intermediate Representation -2. **ZIR → AIR**: Semantic analysis transforms ZIR to Analyzed IR -3. **Comptime evaluation happens in Sema** (step 2) - -The Sema phase attempts to evaluate each instruction: -- If operands are comptime-known → evaluate immediately -- If runtime values needed → generate AIR instructions - -Zig explicitly chose to build a self-hosted compiler (abandoning the C++ bootstrap) because comptime needed deep integration with the compilation pipeline. The C++ bootstrap had limited comptime support. The self-hosted compiler made comptime first-class. - -### Key Zig Features - -```zig -// comptime keyword forces compile-time evaluation -const len = comptime multiply(4, 5); // 20 - -// comptime parameters -fn Vec(comptime T: type, comptime N: usize) type { - return struct { - data: [N]T, - }; -} - -// Type introspection -fn dump(value: anytype) void { - const T = @TypeOf(value); - switch (@typeInfo(T)) { - .Int => std.debug.print("int: {}", .{value}), - .Struct => |s| { - inline for (s.fields) |field| { - std.debug.print("{}: {}\n", .{field.name, @field(value, field.name)}); - } - }, - } -} - -// inline for - unrolled at comptime -inline for (fields) |field| { - // Generates separate code for each field -} -``` - -### Why Template Haskell and Rust Proc Macros Are Painful - -Both are comptime-like features bolted onto batch compilers: - -**Rust proc macros** must live in a separate crate, compiled to a dylib. They only see token streams — no type information. This isn't a design choice, it's an architectural limitation: proc macros run before type checking. - -**Template Haskell** has a "stage restriction" — a splice can't reference definitions from the same module that appear after it. GHC processes the file in chunks separated by splices. Cross-module TH requires the dependency to be fully compiled first. - -Both systems are widely considered the most painful parts of their respective ecosystems. The pain comes from the architecture, not from bad design. ReScript's comptime avoids these pitfalls by being integrated into the compiler's compilation model. - -### References - -- [Zig Comptime Guide](https://zig.guide/language-basics/comptime/) -- [What is Zig's Comptime?](https://kristoff.it/blog/what-is-zig-comptime/) -- [Things Zig comptime Won't Do](https://matklad.github.io/2025/04/19/things-zig-comptime-wont-do.html) -- [Comptime Zig ORM](https://matklad.github.io/2025/03/19/comptime-zig-orm.html) -- [Zig Sema: ZIR → AIR](https://mitchellh.com/zig/sema) diff --git a/docs/comptime/EXAMPLES.md b/docs/comptime/EXAMPLES.md deleted file mode 100644 index 067e0607c7..0000000000 --- a/docs/comptime/EXAMPLES.md +++ /dev/null @@ -1,641 +0,0 @@ -# Comptime Examples: Replacing PPXs - -Concrete examples showing how comptime replaces every major PPX use case. Each section shows the current PPX pain, the full comptime implementation, and what the compiler produces. - ---- - -## 1. JSON Codec (replaces `ppx_spice` / `Decco`) - -### Comptime library - -```rescript -// === Codec.res — reusable library, written in ReScript, not OCaml === - -@comptime -let rec encodeField = (comptime T: type, value: T): JSON.t => { - switch @typeInfo(T) { - | String => JSON.Encode.string(value) - | Int => JSON.Encode.int(value) - | Float => JSON.Encode.float(value) - | Bool => JSON.Encode.bool(value) - | Option({inner}) => - switch value { - | Some(v) => encodeField(inner, v) - | None => JSON.Null - } - | Array({element}) => - value->Array.map(v => encodeField(element, v))->JSON.Encode.array - | Record({fields}) => - let obj = Dict.make() - inline for field in fields { - let key = @getAttr(field, "json.key")->Option.getOr(field.jsName) - if field.optional { - switch @field(value, field.name) { - | Some(v) => Dict.set(obj, key, encodeField(field.typ, v)) - | None => () - } - } else { - Dict.set(obj, key, encodeField(field.typ, @field(value, field.name))) - } - } - JSON.Encode.object(obj) - | Variant({constructors, tag}) => - let tagKey = tag->Option.getOr("TAG") - inline for ctor in constructors { - switch value { - | @variant(ctor.name) => - let obj = Dict.make() - Dict.set(obj, tagKey, JSON.Encode.string(ctor.name)) - switch ctor.args { - | NoArgs => () - | InlineRecord(fields) => - inline for f in fields { - Dict.set(obj, f.name, encodeField(f.typ, @ctorField(value, ctor.name, f.name))) - } - | TupleArgs(args) => - inline for (i, arg) in Array.withIndex(args) { - Dict.set(obj, `_${Int.toString(i)}`, encodeField(arg, @ctorArg(value, ctor.name, i))) - } - } - JSON.Encode.object(obj) - } - } - | Recursive(_) => @callEncoder(T, value) - | _ => @compileError(`Cannot encode ${@typeName(T)}`) - } -} - -@comptime.derive("encoder") -let encoder = (comptime T: type) => { - (value: T): JSON.t => encodeField(T, value) -} - -@comptime.derive("decoder") -let decoder = (comptime T: type) => { - (json: JSON.t): result => decodeField(T, json, "$") -} -``` - -### Usage - -```rescript -@encoder @decoder -type address = { - street: string, - city: string, - @json.key("zip_code") zip: string, -} - -@encoder @decoder -type user = { - name: string, - @json.key("user_age") age: int, - email: option, - address: address, - tags: array, -} - -let json = encode_user(myUser) -let result = decode_user(json) // result with path-aware errors -``` - -### What the compiler emits (no generics, no runtime dispatch) - -```javascript -function encode_user(value) { - var obj = {}; - obj["name"] = value.name; - obj["user_age"] = value.age; - if (value.email !== undefined) obj["email"] = value.email; - var addr = {}; - addr["street"] = value.address.street; - addr["city"] = value.address.city; - addr["zip_code"] = value.address.zip; - obj["address"] = addr; - obj["tags"] = value.tags; - return obj; -} -``` - -### Recursive types work naturally - -```rescript -@encoder @decoder -type rec treeNode = { - value: string, - children: array, -} - -// Compiler sees Recursive({name: "treeNode"}) and generates self-referencing call: -let rec encode_treeNode = (value: treeNode): JSON.t => { - let obj = Dict.make() - Dict.set(obj, "value", JSON.Encode.string(value.value)) - Dict.set(obj, "children", - value.children->Array.map(v => encode_treeNode(v))->JSON.Encode.array - ) - JSON.Encode.object(obj) -} -``` - -### Variant encoding - -```rescript -@encoder @decoder -type shape = - | Circle({radius: float}) - | Rectangle({width: float, height: float}) - | Point - -// Generated: -let encode_shape = (value: shape): JSON.t => { - switch value { - | Circle({radius}) => - let obj = Dict.make() - Dict.set(obj, "TAG", JSON.Encode.string("Circle")) - Dict.set(obj, "radius", JSON.Encode.float(radius)) - JSON.Encode.object(obj) - | Rectangle({width, height}) => - let obj = Dict.make() - Dict.set(obj, "TAG", JSON.Encode.string("Rectangle")) - Dict.set(obj, "width", JSON.Encode.float(width)) - Dict.set(obj, "height", JSON.Encode.float(height)) - JSON.Encode.object(obj) - | Point => - let obj = Dict.make() - Dict.set(obj, "TAG", JSON.Encode.string("Point")) - JSON.Encode.object(obj) - } -} -``` - ---- - -## 2. GraphQL (replaces `graphql-ppx` / `rescript-relay`) - -### Comptime library - -```rescript -// === GraphQL.res — parser + codegen + schema validation, all in ReScript === - -@comptime -let graphql = (comptime query: string, comptime schema: Schema.t) => { - // Parse the query string at compile time - let operation = Parser.parse(query) - - // Validate against schema — unknown fields become compile errors - Validator.validate(operation, schema) - // e.g. @compileError(`Field "nmae" not found on type "User". Did you mean "name"?`) - - // Generate typed module - { - // The query string itself (for sending to the server) - query: query, - - // Type-safe variables constructor - makeVariables: inline for v in operation.variables { - @record(v.name, scalarToRescript(v.typ)) - }, - - // Response type derived from schema + selection set - parseResponse: (json: JSON.t) => { - inline for field in operation.selectionSet { - let schemaField = Schema.lookupField(schema, operation.rootType, field.name) - @record( - field.alias->Option.getOr(field.name), - decodeGraphqlField(schemaField.typ, field, schema, json) - ) - } - }, - } -} -``` - -### Usage - -```rescript -// Schema loaded at compile time from introspection JSON -@comptime let schema = GraphQL.Schema.load(@embedFile("./schema.graphql.json")) - -module UserQuery = GraphQL.graphql(` - query UserQuery($id: ID!) { - user(id: $id) { - id - name - email - posts(first: 10) { - title - createdAt - } - } - } -`, schema) - -// Fully typed — typo in field name = compile error -let response = await fetch("/graphql", { - method: "POST", - body: Json.stringify({ - "query": UserQuery.query, - "variables": UserQuery.makeVariables(~id="123"), - }), -}) -let data = UserQuery.parseResponse(await response.json()) -// data.user.name: string -// data.user.posts: array<{title: string, createdAt: string}> -``` - -The GraphQL parser, validator, and codegen are all ReScript. Anyone can read, debug, and contribute. Schema validation errors are compile errors with good messages, not cryptic PPX crashes. - ---- - -## 3. CSS-in-JS (replaces `styled-ppx`) - -### Comptime library - -```rescript -// === CSS.res — parser + validator === - -@comptime -let styled = (comptime tag: string, comptime css: string) => { - // Parse CSS at compile time - let block = Parser.parse(css) - - // Validate property names — compile error on typos - inline for rule in block.rules { - if !isValidProperty(rule.property) { - @compileError(`Unknown CSS property "${rule.property}". Did you mean "${suggestProperty(rule.property)}"?`) - } - } - - // Generate deterministic class name from content hash - let className = `css-${hashString(css)}` - let cssString = Printer.print(block, className) - - // Runtime: inject stylesheet + return component - @sideEffect Emotion.injectGlobal(cssString) - - React.forwardRef((props, ref) => { - ReactDOM.createElement(tag, { - ...props, - className: switch props.className { - | Some(c) => `${className} ${c}` - | None => className - }, - ref, - }) - }) -} -``` - -### Usage - -```rescript -let Button = CSS.styled("button", ` - background-color: #2563eb; - padding: 10px 20px; - border-radius: 6px; - color: white; - font-weight: 600; - - &:hover { - background-color: #1d4ed8; - } - - &:disabled { - opacity: 0.5; - cursor: not-allowed; - } -`) - -// Typo = compile error: -let Bad = CSS.styled("div", ` - backgrond-color: red; - // ^^^^^^^ Error: Unknown CSS property "backgrond-color". Did you mean "background-color"? -`) - -// Usage in JSX — it's just a React component - -``` - ---- - -## 4. SQL (replaces `rescript-embed-lang` / type-safe SQL) - -### Comptime library - -```rescript -// === SQL.res === - -@comptime -let sql = (comptime query: string, comptime schema: DBSchema.t) => { - let parsed = Parser.parse(query) - - // Validate table/column names against schema - Validator.validate(parsed, schema) - // @compileError(`Column "naem" not found in table "users". Did you mean "name"?`) - - // Extract $param types from schema - let params = extractParams(parsed, schema) - - // Infer result row type from SELECT columns - let columns = inferColumns(parsed, schema) - - { - query: query, - execute: async (db: DB.t, params: @buildRecord(params)): array<@buildRecord(columns)> => { - await db.query(query, params) - }, - executeOne: async (db: DB.t, params: @buildRecord(params)): option<@buildRecord(columns)> => { - let rows = await db.query(query, params) - rows->Array.get(0) - }, - } -} -``` - -### Usage - -```rescript -@comptime let schema = DBSchema.load(@embedFile("./schema.sql")) - -let findUser = SQL.sql(`SELECT id, name, email FROM users WHERE id = $id`, schema) -let searchUsers = SQL.sql(`SELECT id, name FROM users WHERE name LIKE $pattern LIMIT $limit`, schema) - -// Fully typed params and results: -let user = await findUser.executeOne(db, {id: "123"}) -// user: option<{id: string, name: string, email: string}> - -let users = await searchUsers.execute(db, {pattern: "%alice%", limit: 10}) -// users: array<{id: string, name: string}> - -// Wrong column name = compile error: -let bad = SQL.sql(`SELECT nmae FROM users`, schema) -// Error: Column "nmae" not found in table "users". Did you mean "name"? -``` - ---- - -## 5. Form Generation (replaces `ppx_react_hook_form`) - -### Comptime library - -```rescript -// === Form.res === - -@comptime.derive("form") -let form = (comptime T: type) => { - switch @typeInfo(T) { - | Record({fields}) => { - useForm: (): form => { - let rhf = ReactHookForm.useForm() - { - handleSubmit: rhf.handleSubmit, - formState: rhf.formState, - register: inline for field in fields { - @record(field.name, rhf.register(field.name)) - }, - watch: inline for field in fields { - @record(field.name, () => rhf.watch(field.name)) - }, - } - } - } - | _ => @compileError("@form requires a record type") - } -} -``` - -### Usage - -```rescript -@form -type loginForm = { - email: string, - password: string, - @form.min(1) @form.max(100) age: int, - rememberMe: bool, -} - -@react.component -let make = () => { - let form = LoginForm.useForm() - -
Console.log(data))}> - - - - - -
-} -``` - ---- - -## 6. Type Building (replaces `ppx_ts` utility types) - -Comptime value functions (`@comptime let`) take values and return values. Comptime type functions (`@comptime type`) take types and return types. Both use `@typeInfo` for introspection, but type functions use type-building builtins (`@buildVariant`, `@buildRecord`) to construct new type declarations. - -### KeyOf — variant of record field names - -```rescript -// === TypeUtils.res === - -// Type-level comptime: takes a type, returns a type -@comptime -type keyOf<'T> = { - switch @typeInfo('T) { - | Record({fields}) => - @buildVariant(inline for field in fields { - @variantCase({name: field.name->String.capitalize, as: field.name}) - }) - | _ => @compileError("keyOf requires a record type") - } -} -``` - -```rescript -// === Usage — just a type expression, no attributes needed === - -type user = { name: string, age: int, email: string } - -type user_key = keyOf -// Compiler evaluates at compile time, produces: -// type user_key = -// | @as("name") Name -// | @as("age") Age -// | @as("email") Email - -// Use it: -let fieldName = (key: user_key): string => { - switch key { - | Name => "name" - | Age => "age" - | Email => "email" - } -} -``` - -### Partial — make all fields optional - -```rescript -@comptime -type partial<'T> = { - switch @typeInfo('T) { - | Record({fields}) => - @buildRecord(inline for field in fields { - @recordField({name: field.name, typ: field.typ, optional: true}) - }) - | _ => @compileError("partial requires a record type") - } -} -``` - -```rescript -type user = { name: string, age: int, email: string } - -type userPatch = partial -// Produces: -// type userPatch = { name?: string, age?: int, email?: string } - -let patch: userPatch = { name: "Alice" } // age and email omitted -``` - -### Pick — subset of record fields - -```rescript -@comptime -type pick<'T, 'Keys> = { - switch @typeInfo('T) { - | Record({fields}) => - let keys = @comptimeValue('Keys) // extract the comptime string array - let picked = fields->Array.filter(f => Array.includes(keys, f.name)) - if Array.length(picked) != Array.length(keys) { - let unknown = keys->Array.filter(k => !Array.some(fields, f => f.name == k)) - @compileError(`Unknown fields: ${Array.join(unknown, ", ")}`) - } - @buildRecord(inline for field in picked { - @recordField({name: field.name, typ: field.typ}) - }) - | _ => @compileError("pick requires a record type") - } -} -``` - -```rescript -type user = { name: string, age: int, email: string } - -type userPreview = pick -// Produces: -// type userPreview = { name: string, email: string } - -// Typo in field name = compile error: -type bad = pick -// Error: Unknown fields: emial -``` - -### Readonly — make all fields immutable (strip mutable) - -```rescript -@comptime -type readonly<'T> = { - switch @typeInfo('T) { - | Record({fields}) => - @buildRecord(inline for field in fields { - @recordField({name: field.name, typ: field.typ, mutable_: false}) - }) - | _ => @compileError("readonly requires a record type") - } -} -``` - -```rescript -type state = { mutable count: int, mutable label: string } - -type frozenState = readonly -// Produces: -// type frozenState = { count: int, label: string } -``` - -### Enum from string array - -```rescript -@comptime -type makeEnum<'Values> = { - let values = @comptimeValue('Values) - @buildVariant(inline for v in values { - @variantCase({name: v->String.capitalize, as: v}) - }) -} -``` - -```rescript -type status = makeEnum<["active", "inactive", "suspended"]> -// Produces: -// type status = -// | @as("active") Active -// | @as("inactive") Inactive -// | @as("suspended") Suspended -``` - -### Composing type-level comptime - -Comptime types compose naturally — the output of one can be the input to another: - -```rescript -type user = { name: string, age: int, email: string, password: string } - -// Pick some fields, then make them optional -type userPatch = partial> -// Produces: -// type userPatch = { name?: string, age?: int, email?: string } - -// Keys of a subset -type editableFields = keyOf> -// Produces: -// type editableFields = | @as("name") Name | @as("age") Age | @as("email") Email -``` - -### Derive attributes still work for type-level comptime - -If you want attribute-triggered type generation (like `@keyOf` on a type declaration), `@comptime.derive` works with comptime types too: - -```rescript -// Register keyOf as a derive attribute -@comptime.derive("keyOf") -type keyOf<'T> = { ... } // same body as above - -// Now both styles work: -type user_key = keyOf // explicit call -@keyOf type user = { ... } // derive attribute — generates user_key alongside -``` - ---- - -## Summary - -Comptime has two modes, matching the two things you do in a language — compute values and define types: - -| | Value-level comptime | Type-level comptime | -|---|---|---| -| **Syntax** | `@comptime let f = ...` | `@comptime type f<'T> = ...` | -| **Input** | Types + runtime values | Types only | -| **Output** | Specialized runtime code | New type declarations | -| **Usage** | `f(myType, myValue)` | `type t = f` | -| **Example** | JSON encoder | keyOf, partial, pick | - -Both use the same introspection (`@typeInfo`, `@getAttr`, `inline for`) and the same execution model (QuickJS). The difference is just what they produce — runtime expressions vs type declarations. - -Key primitives: -- `@typeInfo(T)` — structured type introspection -- `inline for` — compile-time loop unrolling -- `@compileError(msg)` — user-friendly error messages -- `@field(value, name)` — comptime-known field access -- `@getAttr(field, name)` — read custom attributes -- `@embedFile(path)` — embed file contents at compile time -- `@buildVariant` / `@variantCase` — construct variant types -- `@buildRecord` / `@recordField` — construct record types diff --git a/docs/comptime/IMPLEMENTATION.md b/docs/comptime/IMPLEMENTATION.md new file mode 100644 index 0000000000..1a527602bc --- /dev/null +++ b/docs/comptime/IMPLEMENTATION.md @@ -0,0 +1,253 @@ +# Compile-time macros: the compiler side + +How the design in [README.md](README.md) is implemented in the Rust +compiler. Read that first. + +## Where things are + +| Path | What | +| --- | --- | +| `compiler-rust/src/macros/mod.rs` | The `MacroHost` trait (the JavaScript engine), `MacroExpansionRequired`, and where compiler text and engine text are converted. | +| `compiler-rust/src/macros/expand.rs` | The expansion of one file: the pass loop, `%comptime` evaluation, position mapping. | +| `compiler-rust/src/macros/discover.rs` | The type checker's hooks: recognizing macro uses, running the macro, recording edits, instances of generics. | +| `compiler-rust/src/macros/quote.rs` | Lowering `%code`, `%type` and `%pat` in a macro's own file. | +| `compiler-rust/src/macros/reflect.rs` | Answers about types: `Type.info`, printing a type as source, the literal shape of a `%comptime` value. | +| `compiler-rust/src/macros/edit.rs` | `SourceText`: text with a map back to the original, and edits on it. | +| `compiler-rust/src/macros/host.js` | The engine side: module loader, sandbox, call entry point. The same script in QuickJS and in the browser. | +| `compiler-rust/src/macros/quickjs.rs` | The engine of native builds (feature `macro-quickjs`, part of `native`). | +| `packages/@rescript/runtime/Macro.res` | The API macros are written against. | +| `compiler-rust/src/parser` | `${...}` holes, the payloads of quotes, macro arguments. | +| `compiler-rust/tests/macros.rs` | End-to-end tests: small projects compiled in memory. | +| `playground/` | The browser playground and its host. | + +## Parsing + +- `${` is a token (`Token::DollarLbrace`). `${expr}` parses to the extension + `res.hole` with the expression as payload, where an expression, a type or + a pattern is expected. The scanner did not accept `$` outside template + strings before, so no existing source changes meaning. +- `%code(...)` has the ordinary payload of an extension: an expression or + structure items. `%type(...)` takes a type and `%pat(...)` a pattern. +- An extension whose name starts with an uppercase letter takes + comma-separated arguments: expressions in expression, item and module + position, types in type position. One argument is kept as itself, several + as a tuple. +- The parser has a mode for expanded text (`Parser::for_expanded_source`): + identifiers may contain `$`, and `Position::cnum` counts characters, which + is what `SourceText` maps. + +## One file, start to finish + +`driver::compile_source_in_process` compiles the file as it always did. The +type checker runs with `MacroMode::Off`: at a macro use it sets +`macro_expansion_required` and fails the item, and the driver returns +`MacroExpansionRequired`. Only then does expansion run: + +```mermaid +sequenceDiagram + participant D as driver + participant X as expand_source + participant T as type checker (discover) + participant E as engine (host.js) + D->>X: source text + loop until a pass records no edit + X->>X: parse; lower quotes; frontend + X->>T: type check with MacroMode::Discover + T->>E: call Json.encode with {code, type handle} + E-->>T: need info:3 + T->>E: call again, with the answer + E-->>T: code as text + T-->>X: edits, errors, %comptime sites + X->>X: apply edits + end + X-->>D: expanded text + origin map + D->>D: parse expanded text, remap positions, compile +``` + +The final compile is the ordinary pipeline on the expanded text. It also +returns the text (`InProcessCompileResult::expanded_source`). + +### Why text + +A macro's result is source text, and expansion is edits of the file's text +followed by a new type check. The alternative is splicing parse trees and +typing only the new piece. + +Text was chosen because it makes generated code go through exactly what +written code goes through (the parser, the frontend passes, inference, later +macro uses inside it) without a second path for any of them, and because the +expanded file is a thing a person can read. Its cost is a type check of the +file per pass. Changing it later does not change the language: the surface +(`code<'a>`, quotes, `Macro`) does not say how code is represented. + +`SourceText` keeps, for every character, the offset in the original file it +stands for: itself for text that was there, the start of the replaced range +for generated text. `expand::remap_positions` rewrites every position in the +parse arena of the expanded text through that map, so everything after +parsing sees original positions. + +## Quotes + +`quote::lowering_edits` rewrites the quotes of a file as text: + +```rescript +%code(JSON.Encode.string(${value})) +// becomes +(Macro.__quoteCode(["JSON.Encode.string(", ")"], [Macro.__holeCode(value)])) +``` + +The pieces are the source text around the holes. `__holeCode`, `__holeType` +and `__holePat` are identity functions whose types make the hole's +expression check as `code<'a>`, `typ` or `pat`; `__holeItem` is for a hole +that stands where a whole declaration does. A quote of declarations lowers +to `__quoteDecls`. At run time a quote is string concatenation, with +parentheses around each filled hole except a declaration. + +While it copies a piece, the lowering qualifies the top-level value and +module names of the macro's own file with the file's module name, so that +`encode(v)` inside a quote in `Json.res` reads `Json.encode(v)` at the use. +This is the only hygiene there is so far. + +## The type checker's hooks + +`TypeCheckContext::macro_mode` is `Off` or `Discover(Discovery)`. The hooks +are called from `typecore.rs` and `typemod.rs`: + +| Hook | Called at | Does | +| --- | --- | --- | +| `expression_extension` | `Pexp_extension` | `%M.f(...)`, `%comptime`, leftover quotes and holes | +| `type_extension`, `pattern_extension` | `Ptyp_extension`, `Ppat_extension` | macros in type and pattern position | +| `declarations_extension` | `Pstr_extension`, `Pmod_extension` | macros that return declarations | +| `type_item`, `value_item` | a `type` or `let` item with a macro attribute | derive on a type, rewrite of a `let` | +| `generic_use`, `note_application` | an identifier, an application | notes a use of a `@generic` | +| `begin_item`, `end_item` | around each top-level item | resolves the noted generics once the item is inferred | + +In a discovery pass a hook runs the macro and pushes an `Edit`. The item +then fails with a marker error and the pass goes on with the next item: a +failed item is skipped in discovery, so one pass expands every macro it can +reach. Real type errors are left for the final compile to report. + +`typemod.rs` copies `@macro` and `@generic` from a `let` to the value +description of the exported value (`mark_macro_values`), which is how a use +in another file knows the value is a macro. + +### Arguments + +A macro's parameter types decide what each argument becomes +(`signature`/`ParamKind`): `code<'a>` gets `{c: , t: }`, +where the type comes from typing the argument on its own; `typ` gets a type, +`{c: , id: }`; any other type gets the JSON value of a +literal +(`literal`). `Type.decl` and `Decl.value` are built from the item the +attribute is on. + +### Generics + +A `@generic` used in another file is typed as a function at its erased type +(`code` read as `t`), and the use is noted with its environment and type. +At `end_item` the types are final. For each use, `resolve_generic`: + +1. prints the argument and result types. A type that still has an unknown + part is an error asking for an annotation; +2. looks up the instance by key: macro, argument types, compile-time values, + result type; +3. if there is none, runs the macro with parameters named `a$`, `b$`, ... + and adds `name = (a$: t): r => ` to the instance group of the + current top-level item; +4. replaces the callee, or the whole call when there are compile-time + arguments, with the instance name. + +Instance groups are `let rec` items marked `@res.macroInstances`, inserted +before the top-level item that needed them. `typemod.rs` leaves them out of +the signature and `raw_lambda/convert.rs` out of the exports. An instance +that an earlier item turns out to need moves to that item's group, with the +instances it calls (`Discovery::finish`). `InstanceTable` lives across the +passes of a file. + +The calls a generated instance makes to the generic (the `encode(...)` on +each field) are ordinary uses, found by the next pass. + +### `%comptime` + +A discovery pass types the expression and records the site with the shape +of its type (`reflect::value_shape`). After the pass, +`expand::evaluate_comptime` compiles `opens + let value = ` as a +module of its own in memory, sends its JavaScript to the engine (`kind: +"eval"`), and `host.js` writes the value as a literal by the shape. + +## The engine + +`MacroHost::call(request) -> response` is the whole interface, JSON both +ways. The embedder provides `__rescript_macro_source(moduleName)`, which +returns the compiled JavaScript of a module; `host.js` loads modules through +it, turning ES module output into CommonJS by text when needed. + +```json +{"kind": "call", "module": "Json", "name": "encode", + "args": [{"c": "alice", "t": {"c": "user", "id": 1}}], + "expected": {"c": "JSON.t", "id": 2}, + "answers": {"info:1": {"TAG": "Record", "name": "user", "fields": []}}} +``` + +The response is `{"ok": ""}`, `{"error": "...", "offset": n}` or +`{"need": ""}`. A question is `info:`, +`companion::`, `readFile:` or `env:`. On `need` +the compiler adds the answer and calls again (`Discovery::run`). Answers +are in the layout the compiled `Macro.Type.info` variant has at run time, +so the macro reads them without decoding. + +The compiler keeps source text as one `char` per byte of the file. +`macros::call_host` converts requests to real text and responses back. + +`host.js` gives macro modules a `Math` without `random`, a `Date` without +the current time, and no `fetch`, timers or other input and output of the +embedder. + +**QuickJS** (`quickjs.rs`): one runtime per thread that expands macros, +created on first use, with a 512 MB memory limit and an interrupt handler +that stops a call after 20 seconds. `QuickJsHost::invalidate` makes engines +drop the modules they loaded, for when compiled JavaScript changes. + +**Browser** (`playground/crate/src/lib.rs`): the host calls +`__rescript_macro_call` of the page, which evaluated `host.js`. The compiler +runs in a worker; the page replaces the worker when a build takes more than +20 seconds. + +## The runtime as source + +The tests and the playground have no compiled standard library: modules of +`@rescript/runtime` are type checked from source on demand. +`ModuleRegistry::set_source_fallback_is_runtime` says that those modules are +the runtime: they are checked with the runtime package's flags +(`-nopervasives -open Pervasives`) and imported from +`@rescript/runtime/lib/...`. + +## Tests + +`cargo test --manifest-path compiler-rust/Cargo.toml --test macros` compiles +small projects in memory, with QuickJS as the engine, and checks the +JavaScript and the expanded source. One test compiles every example of the +playground. `playground/scripts/smoke.mjs` builds and runs the same examples +with the compiler in WebAssembly. + +## Next steps + +In the order that seems right: + +1. **Build system.** In `rewatch`: treat a macro name in an extension or + attribute as a reference to its module (`binary_ast/deps.rs`), create one + `QuickJsHost` per build whose source function reads the compiled + JavaScript of a module, and on `MacroExpansionRequired` expand from the + source file and compile the result. Then measure a large project. +2. **Cache.** Store `(macro module digest, request, answers) -> result` in + `lib/bs/rescript.sqlite`, and record the files `readFile` read and the + interfaces `Type.info` looked at as inputs of the module, next to the + `reads` the build already tracks. +3. **Hygiene.** Rename the binders a quote introduces per expansion. +4. **Positions inside generated code**, using the quote's pieces to map an + offset in generated text to an offset in the macro's file. +5. **`rescript expand `** and the editor: show the expansion; hover + and definitions inside macro arguments. +6. **Port ppx-spice** to a library of macros, with the Rust port as the + oracle, and delete `binary_ast/spice_ppx.rs`. +7. **Trees instead of text**, if the measurements of step 1 ask for it. diff --git a/docs/comptime/PROTOTYPE_NOTES.md b/docs/comptime/PROTOTYPE_NOTES.md deleted file mode 100644 index fde493eb38..0000000000 --- a/docs/comptime/PROTOTYPE_NOTES.md +++ /dev/null @@ -1,179 +0,0 @@ -# Comptime Implementation Notes - -> These notes describe the prototype that was removed from the Rust compiler -> before release. They record what worked, as input for a future -> implementation; the code they refer to no longer exists. - -## Core Design - -The comptime system has three components: - -1. **`@comptime` functions are inlined at call sites** — so the type checker sees concrete types -2. **`@typeInfo(expr)` is a builtin** — returns a `typeInfo` value based on the static type of `expr`. Requires a concrete type (no type variables). -3. **The existing compiler optimizer** handles switch folding, constant propagation, dead branch elimination - -There is no special "comptime mode." The type checker handles `@typeInfo`, `@field`, and `inline for` as general capabilities. The `@comptime` attribute just means "inline this function." - -## `@typeInfo` Requires Concrete Types - -`@typeInfo(expr)` looks at `expr`'s static type. It must be fully resolved — no type variables: - -```rescript -@typeInfo(myUser) // ✅ myUser: user — concrete -@typeInfo(myString) // ✅ myString: string — concrete -@typeInfo(items) // ✅ items: array — concrete -@typeInfo(x) // ❌ x: 'a — Error: @typeInfo requires a concrete type -``` - -The `@comptime` inlining ensures types are concrete: the function body is inlined with the call site's concrete types. - -## How It Works: Nested Encoder Example - -```rescript -type address = { street: string, city: string } -type user = { name: string, age: int, address: address, tags: array, email: option } - -@comptime -let rec encode = (value) => { - switch @typeInfo(value) { - | String => Json.string(value) - | Int => JSON.Encode.int((value)) - | Record({fields}) => - let obj = Dict.empty() - inline for field in fields { - Dict.set(obj, field.name, encode(@field(value, field.name))) - } - Json.object_(obj) - | Array({element}) => - value->Array.map(item => encode(item))->Json.array - | Option({inner}) => - switch value { - | Some(v) => encode(v) - | None => Json.null - } - } -} - -let json = encode(myUser) -``` - -### Step-by-step: `encode(myUser)` where myUser: user - -**1. Inline.** `encode` is `@comptime`. The compiler inlines its body with `value = myUser` (type: `user`). - -**2. `@typeInfo(value)`.** The type checker sees `value: user`. Calls `build_type_info(user)` → `Record({name: "user", fields: [name: String, age: Int, address: Record(address), tags: Array(String), email: Option(String)]})`. Returns a literal `typeInfo` value. - -**3. Switch.** Scrutinee is known `Record({fields})`. Matches the `Record` branch. **Skips** String, Int, Array, Option branches (never type-checked — important because e.g. `Json.string(value)` where `value: user` would fail). - -**4. `inline for field in fields`.** `fields` is known (5 elements). Type checker unrolls — type-checks the body 5 times: - -**Iteration: "name" (String)** -- `field.name` → `"name"` (comptime constant) -- `@field(value, "name")` → validates "name" exists on user → `myUser.name: string` -- `encode(myUser.name)` → inline → `@typeInfo` → String → `Json.string(myUser.name)` -- Emit: `Dict.set(obj, "name", Json.string(myUser.name))` - -**Iteration: "age" (Int)** -- `encode(myUser.age)` → Int → `JSON.Encode.int((myUser.age))` - -**Iteration: "address" (Record)** -- `encode(myUser.address)` → Record(address) → nested `inline for` over street, city -- Produces: `let obj$1 = Dict.empty(); Dict.set(obj$1, "street", ...); Dict.set(obj$1, "city", ...); Json.object_(obj$1)` - -**Iteration: "tags" (Array\)** -- `encode(myUser.tags)` → `Array({element: String})` -- Body: `value->Array.map(item => encode(item))->Json.array` -- `item: string` (concrete — from `array`) → `encode(item)` inlines → `Json.string(item)` -- Result: `myUser.tags->Array.map(item => Json.string(item))->Json.array` - -**Iteration: "email" (Option\)** -- `encode(myUser.email)` → `Option({inner: String})` -- Body: `switch value { | Some(v) => encode(v) | None => Json.null }` -- This is a **runtime switch** (value is runtime). Type checker checks both branches: - - `Some(v)` → `v: string` → `encode(v)` → String → `Json.string(v)` ✅ - - `None` → `Json.null` ✅ - -### Final JS output - -```javascript -let obj = Dict.empty(); -Dict.set(obj, "name", Json.string(myUser.name)); -Dict.set(obj, "age", JSON.Encode.int((myUser.age))); -let obj$1 = Dict.empty(); -Dict.set(obj$1, "street", Json.string(myUser.address.street)); -Dict.set(obj$1, "city", Json.string(myUser.address.city)); -Dict.set(obj, "address", Json.object_(obj$1)); -Dict.set(obj, "tags", myUser.tags->Array.map(item => Json.string(item))->Json.array); -Dict.set(obj, "email", myUser.email !== undefined ? Json.string(myUser.email) : Json.null); -let json = Json.object_(obj); -``` - -## What `type_expect` Does - -These are general type checker capabilities, not comptime-specific: - -| Expression | What happens | -|---|---| -| `@typeInfo(expr)` | Look up expr's static type (must be concrete). Build TypeInfo. Return literal `typeInfo` value. | -| `switch { cases }` | Match known value against patterns. Type-check ONLY matching branch. Skip others. | -| `inline for x in { body }` | Unroll: type-check body N times with x bound to each element. Splice results as sequence. | -| `@field(value, )` | Validate field exists on value's type. Produce `Texp_field` with correct type. Compile error if field doesn't exist. | -| `f(arg)` where f is `@comptime` | Inline f's body. Type-check with arg's concrete type. | - -## Two Comptime Mechanisms - -### `@comptime` — Specialization via Inlining - -Function body inlined at each call site. Type checker type-checks with concrete types. `@typeInfo`, `@field`, `inline for` are builtins. Optimizer folds switches. - -No JS engine needed. - -### `@comptime.inline` — Full Evaluation in JS Engine (Boa) - -Entire function executes at compile time. All arguments must be comptime-known (literals, typeInfo values, results of other comptime.inline calls). Compiled to JS, executed in Boa, result inlined as constant. - -```rescript -@comptime.inline -let capitalize = (s: string): string => { - String.charAt(s, 0)->String.toUpperCase ++ String.sliceToEnd(s, ~start=1) -} -``` - -Called with comptime-known argument → Boa evaluates → result inlined. -Called with runtime argument → compile error. - -### Composition - -```rescript -@comptime.inline -let capitalize = (s: string): string => { ... } - -@comptime -let rec encode = (value) => { - switch @typeInfo(value) { - | Record({fields}) => - inline for field in fields { - Dict.set(obj, capitalize(field.name), encode(@field(value, field.name))) - // ^^^^^^^^^^^^^^^^^^^^^^ - // field.name is "name" (comptime-known from inline for) - // capitalize("name") → Boa evaluates → "Name" - } - } -} -``` - -## Lambda Switch Constant Folding ✅ DONE - -`Lswitch` on known constant → pick matching branch directly. -`switch Red { | Red => "red" | Green => "green" }` → `"red"`. - -## Implementation Order - -1. ✅ **Lambda switch constant folding** -2. **`typeInfo` as predefined type** — variant type with Record, String, Int, etc. constructors -3. **`@typeInfo(expr)` in type checker** — resolve static type, construct literal typeInfo value -4. **Skip non-matching switch branches** — type-check only the branch that matches the known scrutinee -5. **`inline for` unrolling** — type-check body N times with bound variable -6. **`@field(value, name)` validation + generation** — validate field, produce Texp_field -7. **`@comptime` inlining** — inline function body at call sites -8. **`@comptime.inline` + Boa** — full compile-time evaluation diff --git a/docs/comptime/README.md b/docs/comptime/README.md index ee62eaac69..f5f0a26418 100644 --- a/docs/comptime/README.md +++ b/docs/comptime/README.md @@ -1,16 +1,593 @@ -# Comptime (proposed) - -Compile-time metaprogramming for ReScript, modelled on Zig's `comptime`: -regular ReScript functions that run during compilation, introspect types, and -specialize code. It is meant to replace most PPX use cases. - -This is a design proposal. The compiler does not implement it. An early -prototype in the Rust compiler was removed before the first Rust release, so -the feature can be rebuilt on top of the released architecture. - -| Document | Contents | -|----------|----------| -| [DESIGN.md](DESIGN.md) | Proposed architecture: goals, `@typeInfo`, execution model, in-process compilation, derive attributes, PPX replacement | -| [EXAMPLES.md](EXAMPLES.md) | Worked examples (JSON codecs, DSL parsing, derive) | -| [BUILDERS.md](BUILDERS.md) | `typeInfo` shape and the record/variant builder builtins | -| [PROTOTYPE_NOTES.md](PROTOTYPE_NOTES.md) | Lessons from the removed prototype (inlining strategy, `@typeInfo` on concrete types, optimizer reuse) | +# RFC: compile-time macros + +A macro is a ReScript function that the compiler runs while it compiles +another file. It returns code. It does the jobs a PPX does, and it can ask the +type checker about types, the way Zig's `comptime` can. + +```rescript +// Debug.res +open Macro + +@macro +let log = (e: code<'a>): code<'a> => + %code({ + let value = ${e} + Console.log2(${Code.string(Code.print(e) ++ " =")}, value) + value + }) +``` + +```rescript +// Main.res +let total = %Debug.log(price *. Int.toFloat(quantity)) +// prints: price *. Int.toFloat(quantity) = 37.5 +``` + +**Status.** Implemented in the Rust compiler (`compiler-rust/src/macros`), +with tests (`compiler-rust/tests/macros.rs`) and a browser playground +(`playground/`). `rescript build` does not expand macros yet; see +[What is missing](#what-is-missing). [IMPLEMENTATION.md](IMPLEMENTATION.md) +describes the compiler side. + +- [Why](#why) +- [A tour](#a-tour) +- [Reference](#reference) +- [How it runs](#how-it-runs) +- [Cost](#cost) +- [Compared with](#compared-with) +- [What is missing](#what-is-missing) +- [Open questions](#open-questions) +- [Trying it](#trying-it) + +## Why + +ReScript code generation is done by PPXs today: native executables, written +in OCaml against a frozen copy of the parse tree, started once per file. They +see syntax only, so a JSON deriver cannot know what `user` is unless the type +is written out next to the attribute, and they cannot be written in ReScript. +The Rust compiler carries a port of one PPX (7,000 lines for ppx-spice) +because starting a process per file was too slow for it. + +The first proposal for this directory copied Zig: mark a function `comptime` +and let the compiler partially evaluate its body. That works well when the +output is an expression built by walking a record. Every other shape of +output (a record literal, the arms of a switch, a new type, a module, a +derived name) needed a builtin of its own; the list reached 21 builtins, 3 +attributes and 3 grammar forms, and the prototype needed a second evaluator +inside the type checker. + +This design has one mechanism. A macro is an ordinary function: its loops +are loops and its helpers are functions. What it returns is written as +ReScript, and is type checked like code written by hand. + +| | PPX | First proposal | This RFC | +| --- | --- | --- | --- | +| Written in | OCaml | ReScript | ReScript | +| Sees types | no | yes | yes | +| Output shapes | any syntax | expressions; a builtin per other shape | expressions, types, patterns, declarations | +| Special forms | none (attributes and extensions) | 27 | 7 | +| Runs in | a process per file | an evaluator in the type checker, plus a JS engine | a JS engine in the compiler | +| Macro body is type checked | by OCaml | no | yes | + +## A tour + +Every example here is a project in `playground/examples` and is compiled by +the tests. + +### Quotes and holes + +`%code(...)` is a quote: a piece of ReScript that is not evaluated, a value +of type `code<'a>`. `${...}` is a hole in it, filled with another piece of +code. `%type(...)` and `%pat(...)` quote a type and a pattern. + +A quote is checked for syntax where it is written. Its types are checked +where the macro is used, after the holes are filled. + +A parameter of type `code<'a>` receives the code of the argument. A parameter +of an ordinary type receives a value, which the call site has to write as a +literal. There is no `comptime` keyword: the type of the parameter says when +it exists. + +```rescript +@generic +let rec pow = (base: code, n: int): code => + if n == 0 { + %code(1.0) + } else if mod(n, 2) == 0 { + %code({ + let half = ${pow(base, n / 2)} + half *. half + }) + } else { + %code(${base} *. ${pow(base, n - 1)}) + } +``` + +`Power.pow(x, 10)` compiles to four multiplications. The recursion ran in the +compiler. + +### Three ways to use a macro + +| You write | The macro is | It receives | Its result | +| --- | --- | --- | --- | +| `%M.f(args)` | `@macro` | the code of each argument (`code<'a>` parameters) and the value of each literal (other parameters) | replaces the `%M.f(...)`: an expression, a type, a pattern, the contents of a module, or top-level declarations | +| `@M.f` on a `type` or a `let` | `@macro` | the checked type declaration (`Type.decl`), or the `let` before it is checked (`Decl.value`) | declarations: added after the type, or in place of the `let` | +| `M.f(args)` | `@generic` | the code of each argument, with its type | the body of a function the compiler makes for that type | + +The first two are visible at the call site, like a PPX extension or +attribute. The third looks like a function call, and is for the functions +that would be generic if the language could express them: encoders, +comparisons, printers. + +### Asking about types + +`typeOf(value)` is the type of an argument of a `@generic`. `Type.info` +describes a type one level deep: its fields or constructors, with their types +as values that can be asked again. + +```rescript +@generic +let encode = (value: code<'a>): code => + switch Type.info(typeOf(value)) { + | String => %code(JSON.Encode.string(${value})) + | Int => %code(JSON.Encode.int(${value})) + | Float => %code(JSON.Encode.float(${value})) + | Bool => %code(JSON.Encode.bool(${value})) + | Option(_) => + %code( + switch ${value} { + | Some(v) => encode(v) + | None => JSON.Encode.null + } + ) + | Array(_) => %code(JSON.Encode.array(${value}->Array.map(v => encode(v)))) + | Record({fields}) => + let entries = fields->Array.map(f => { + let key = f.attrs->Attr.string("Json.key")->Option.getOr(f.jsName) + %code((${Code.string(key)}, encode(${value->Code.field(f.name)}))) + }) + %code(JSON.Encode.object(Dict.fromArray(${Code.array(entries)}))) + | Abstract({name}) => + switch Type.companion(typeOf(value), "toJson") { + | Some(toJson) => %code(${toJson}(${value})) + | None => error(`${name} is abstract and its module has no toJson`) + } + | _ => error(`Json.encode cannot encode the type ${Type.name(typeOf(value))}`) + } +``` + +The macro does not recurse into the fields. It returns code that calls +`encode` on each field, and the compiler expands those calls in turn. That is +why a recursive type works, and why each type gets one function. + +```rescript +type user = { + name: string, + @Json.key("user_age") age: int, + email: option, + tags: array, +} + +let json = Json.encode(alice) +``` + +The file the compiler compiles after expansion (redundant parentheses +removed): + +```rescript +@res.macroInstances @warning("-39") +let rec encode$user = (a$: user): JSON.t => + JSON.Encode.object(Dict.fromArray([ + ("name", encode$string(a$.name)), + ("user_age", encode$int(a$.age)), + ("email", encode$option_string(a$.email)), + ("tags", encode$array_string(a$.tags)), + ])) +and encode$string = (a$: string): JSON.t => JSON.Encode.string(a$) +and encode$int = (a$: int): JSON.t => JSON.Encode.int(a$) +and encode$option_string = (a$: option): JSON.t => + switch a$ { + | Some(v) => encode$string(v) + | None => JSON.Encode.null + } +and encode$array_string = (a$: array): JSON.t => + JSON.Encode.array(a$->Array.map(v => encode$string(v))) + +let json = encode$user(alice) +``` + +A name with a `$` cannot be written in source, so an instance cannot collide +with a name of the file. The group is not part of the module's signature and +is not exported. The backend inlines the small ones: the JavaScript of +`encode$user` reads `a$.name` directly. + +A `@generic` waits for inference. It is expanded when the top-level item that +contains the call has been type checked, with the types inference settled on: + +```rescript +let team = [alice, bob] +let all = team->Array.map(member => Json.encode(member)) // member: user +``` + +When the type is still unknown at that point, the error says so and asks for +an annotation. + +A type the macro cannot see into is `Abstract`. `Type.companion(t, "toJson")` +is the value `toJson` in the module that defines the type, if there is one: +the way a library says "encode my type like this" without the macro knowing +the library. + +### Declarations from a type + +A macro attached to a type receives the declaration and returns +declarations, which are added after the type. + +```rescript +@macro +let derive = (t: Type.decl): decls => + switch Type.info(t.typ) { + | Variant({constructors}) => + let label = (c: Type.constructor) => c.attrs->Attr.string("Enum.label")->Option.getOr(c.jsName) + let toString = Code.switch_( + %code(value), + constructors->Array.map(c => { + let (pattern, _) = Pat.constructor(c) + (pattern, Code.string(label(c))) + }), + ) + %code( + let ${Pat.var(t.name ++ "ToString")} = (value: ${t.typ}): string => ${toString} + let ${Pat.var(t.name ++ "Values")}: array<${t.typ}> = + ${Code.array(constructors->Array.map(c => Code.ident(c.name)))} + ) + | _ => error("Enum.derive needs a variant type") + } +``` + +```rescript +@Enum.derive +type color = Red | Green | @Enum.label("navy blue") Blue + +colorValues->Array.map(colorToString) // ["Red", "Green", "navy blue"] +``` + +Names are built with `Pat.var`: a hole can stand where a name is bound. + +### Types, patterns, modules + +```rescript +// Partial.res: every field optional +@macro +let t = (source: typ): typ => + switch Type.info(source) { + | Record({fields}) => Type.record(fields->Array.map(f => {...f, optional: true})) + | _ => error(`Partial.t needs a record type, and ${Type.name(source)} is not one`) + } +``` + +```rescript +type userPatch = %Partial.t(user) + +let describe = code => + switch code { + | %Http.status("ok") => "fine" // a macro that returns pat + | _ => "other" + } + +module Length = %Units.table("meters", [("feet", 0.3048), ("miles", 1609.344)]) + +@Trace.calls +let marathon = (miles: float) => Length.milesToMeters(miles) /. 1000.0 +``` + +### Computing now + +`%comptime(expr)` evaluates an expression while compiling and puts the value +in its place as a literal. It needs no macro: `expr` is ordinary code that +uses other modules. + +```rescript +let primes = %comptime(Sieve.primesBelow(60)) +``` + +```js +let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59]; +``` + +The output does not import `Sieve`. + +### Reading files + +`Macro.readFile(path)` is the text of a file of the project. The example +`files` reads `en.json`: `%I18n.t("title")` is a string, `%I18n.t("greeting")` +is a function with a labelled argument for each placeholder of the message, +and a key that is not in the file does not compile: + +``` + We've found a bug for you! + Main.res:8:12-29 + + 7 │ // A key that is not in en.json does not compile: + 8 │ let oops = %I18n.t("goodbye") + + I18n.t: There is no message "goodbye" in en.json. It has: title, greeting, empty +``` + +### Errors + +`Macro.error(message)` stops compilation with the message at the macro use, +as above. Code a macro generates is type checked like written code, and a +type error in it is reported at the macro use. A syntax error in generated +code shows the generated code: + +``` +A macro generated code with a syntax error. The frame shows the expanded source. + + Syntax error! + UseBad.res:1:13 + + 1 │ let x = (1 +) + + Did you forget to write an expression here? +``` + +## Reference + +### The seven forms + +| Form | Where | Meaning | +| --- | --- | --- | +| `@macro` | on a `let` | The function is a macro: used as `%M.f(...)` or attached as `@M.f`. | +| `@generic` | on a `let` | The function is a macro that is called like a function, with one instance per type. | +| `%code(...)` | expression | A quoted expression, or quoted declarations when the content is `let`, `type` or `module` items. | +| `%type(...)` | expression | A quoted type. | +| `%pat(...)` | expression | A quoted pattern. | +| `${...}` | inside a quote | A hole: an expression of type `code`, `typ` or `pat`, by its position. | +| `%comptime(expr)` | expression | The value of `expr`, computed while compiling. | + +Everything else is the module `Macro` of the standard library +(`packages/@rescript/runtime/Macro.res`). + +### Using a macro + +A macro is named by a module path: `%Json.encode(x)`, `@Json.codec`, +`%Lib.Numbers.answer()`. An extension or attribute whose name starts with a +lowercase letter is not a macro, so existing PPX names and built-in +attributes keep their meaning. + +| Position | Example | Macro type | +| --- | --- | --- | +| Expression | `%Debug.log(x + 1)` | `(...) => code<'a>` | +| Type | `type t = %Partial.t(user)` | `(typ, ...) => typ` | +| Pattern | `\| %Http.status("ok") => ...` | `(...) => pat` | +| Top level | `%%Gen.constants("k", 3)` | `(...) => decls` | +| Module | `module K = %Gen.constants("k", 3)` | `(...) => decls` | +| On a type | `@Enum.derive type color = ...` | `Type.decl => decls` | +| On a `let` | `@Trace.calls let f = ...` | `Decl.value => decls` | +| Call | `Json.encode(user)` | `@generic`: `(code<'a>, ...) => code<'b>` | + +Arguments are separated by commas. An argument for a `code<'a>` parameter is +any expression. An argument for a parameter of another type is a compile-time +value: a number, a string, a boolean, `()`, or an array, tuple or record of +those. + +A `@generic` is typed at the call as an ordinary function, with `code` +read as `t`: `Json.encode` is an `'a => JSON.t`. It can be piped into and +passed as a value (`users->Array.map(Json.encode)`). A `@generic` with a +compile-time parameter has to be called directly. + +### The `Macro` module + +| | | +| --- | --- | +| `code<'a>`, `typ`, `pat`, `decls` | Code that evaluates to an `'a`; a type; a pattern; declarations. | +| `error(message)`, `errorAt(~offset, message)` | Stop compilation at the macro use. | +| `typeOf(code)` | The type of an argument of a `@generic`. | +| `expected()` | The type the call site of a `@generic` expects as result. | +| `readFile(path)`, `env(name)` | The text of a file, looked up from the directory of the file being compiled and then its parents; an environment variable of the build. | +| `Type.info(t)` | What the type is, one level deep (below). | +| `Type.name(t)` | The type as source text: `array`. | +| `Type.companion(t, name)` | The value `name` in the module that defines `t`, as code. | +| `Type.record(fields)`, `Type.variant(constructors)`, `Type.field`, `Type.constructor` | Build a type. | +| `Code.string`, `int`, `float`, `bool`, `unit` | Literals. | +| `Code.ident(name)` | A name that is resolved where the macro is used. | +| `Code.field`, `array`, `tuple`, `record`, `call`, `switch_`, `fn` | Build code whose shape depends on data: a field access, a switch with one arm per constructor, a function with one parameter per name. | +| `Code.print(code)` | The source text of a piece of code. | +| `Code.raw(text)` | Code from source text. Nothing checks it until the macro's result is compiled. | +| `Code.decls(items)` | Several declarations in a row. | +| `Pat.var(name)`, `Pat.any`, `Pat.string`, `Pat.int` | Patterns. | +| `Pat.constructor(c)` | The pattern that matches a constructor and binds its arguments, and the code of each bound argument with its type. | +| `Attr.find`, `has`, `string` | Look up an attribute of a field, constructor or declaration. | + +`Type.info` returns one of: + +```rescript +type info = + | Int | Float | String | Bool | Unit | BigInt | Char + | Option(typ) | Array(typ) | List(typ) | Dict(typ) | Promise(typ) + | Result(typ, typ) + | Tuple(array) + | Record({name: string, fields: array, attrs: array}) + | Variant({name: string, constructors: array, attrs: array}) + | PolyVariant({constructors: array}) + | Function({params: array, result: typ}) + | Abstract({name: string}) // hidden by an interface, or external + | Unknown // inference has not settled it +``` + +A `field` has `name`, `jsName` (the `@as` name), `typ`, `optional`, +`mutable_` and `attrs`. A `constructor` has `name`, `jsName`, `args`, +`fields` (of an inline record) and `attrs`. + +### Rules + +- **A macro cannot be used in the file that defines it.** The compiler runs + the compiled JavaScript of the macro's file, so that file is compiled + first. A use of a macro is a dependency on its file. +- **A macro is deterministic.** It has no clock, no random numbers, no + network and no file system of its own: `Math.random()`, `Date.now()` and + `new Date()` raise. Its inputs are its arguments, the answers of the + compiler (`Type.info`, `Type.companion`), `readFile` and `env`. That makes + an expansion a function of inputs the build can record. +- **A macro has limits.** A call may take 20 seconds and its engine 512 MB; + expansion of a file stops after 64 rounds. Each is an error at the macro + use, not a hang. +- **Names in a quote.** A top-level name of the macro's own file that a + quote mentions is resolved in that file: inside `Json.res`, `encode(v)` in + a quote means `Json.encode(v)` wherever the macro is used. Every other + name is resolved where the macro is used. A binder in a quote + (`let value = ...`) is not renamed, so it can shadow a name the argument + code uses; see [What is missing](#what-is-missing). +- **Instances.** An instance of a `@generic` is keyed by the macro, the + types and values of its arguments and its result type. A file has one + instance per key, in a `let rec` group before the first top-level item + that needs it. Instances are not shared between files. +- **`%comptime`** can use other modules, not values of its own file. The + value has to be writable as a literal: numbers, strings, booleans, `()`, + arrays, tuples, options, dicts and records of those. + +## How it runs + +```mermaid +flowchart LR + A[Main.res] --> B[parse and type check] + B -->|no macro used| J[JavaScript] + B -->|a macro is used| C[expansion pass] + C --> D{edits?} + D -->|yes: apply to the source text| C + D -->|no| E[compile the expanded text] + E --> J + C <-->|call, answer, call again| F[(JS engine: the macro's compiled module)] +``` + +1. An ordinary compilation stops at the first macro use. A file without + macros is compiled exactly as before, in one pass. +2. Expansion works on the source text. A pass type checks the file; at each + macro use the type checker runs the macro and records the result as an + edit of the text. The edits are applied and the next pass starts. A pass + without edits ends it. Code a macro generated can use macros: they are + expanded in the next pass. +3. The expanded text is compiled like any file. Every position is mapped + back to the source as written, so errors, warnings and source maps point + at the file the user edits; generated code has the position of the macro + use it came from. +4. Macros run as JavaScript: the compiled output of the macro's module, in a + JavaScript engine inside the compiler. Native builds embed QuickJS, one + engine per compiler thread, created on first use. The playground uses the + browser's engine. +5. The engine cannot call into the compiler. When a macro asks something + (`Type.info`, `readFile`), the call ends with the question, the compiler + answers it, and the macro runs again with the answer. A macro is + deterministic, so the second run takes the same path. + +Because expansion produces source text, the expanded file is something a +person can read, and a tool can show. The playground's "Expanded" tab is that +text. + +## Cost + +Measured on an Apple M-series Mac mini, release builds. + +| What | Time | +| --- | --- | +| Create a QuickJS engine | 92 µs, once per compiler thread | +| Load a macro module | 84 µs, once per engine | +| Run a derive-style macro (10-field record, 41 questions to the compiler) | 14 µs | +| Start ppx-spice once (it is started once per file) | 6.1 ms | +| Start Node once | 70 ms | + +The engine numbers are from a benchmark of the embedding with stub answers +(rquickjs 0.9); they do not include the type checker's work to answer. + +The cost that matters is the passes. Each pass type checks the whole file +again, and a file needs one pass more than its deepest nesting of generated +code that uses macros: `Json.encode(user)` takes a pass for `user`, one for +the field types, one for what those contain. A file that uses no macro is +not affected: it takes the path it always took. + +Not measured yet: a large project end to end. That needs the build system +integration. + +## Compared with + +| | Runs | Sees types | Output | Notes | +| --- | --- | --- | --- | --- | +| PPX (OCaml) | native process per file | no | parse tree | not writable in ReScript; frozen AST | +| Zig `comptime` | interpreter in the compiler | yes | the function body, partially evaluated | no quotes; the first proposal followed it | +| Rust procedural macros | native code per crate | no | token stream | derive sees syntax only | +| Template Haskell | interpreter in the compiler | yes (`reify`) | quotes and splices | the closest relative: typed quotes, staged by type | +| Scala 3 macros | the compiler's VM | yes | typed quotes | `inline` plus quotes; the staging idea here is the same | +| This RFC | JS engine in the compiler | yes | quotes of ReScript source | macro code is the module's ordinary JavaScript | + +## What is missing + +Implemented and tested: everything in the tour and the reference above. Not +implemented: + +- **`rescript build`.** The build system compiles from parse trees it made + earlier and does not call expansion. It needs: macro names in the + dependency scan, a host that reads the compiled JavaScript of a module, + and expansion when a compilation asks for it. The compiler side is one + call (`driver::compile_source_in_process` does it for the tests and the + playground). +- **A cache.** An expansion is a function of the macro's code, its + arguments, the answers it got and the files it read. Storing results in + the build database (`lib/bs/rescript.sqlite`) keyed on those makes + rebuilds skip the engine. +- **Hygiene for binders.** A `let` inside a quote can capture a name used by + argument code. The plan is a fresh mark per expansion on binders that a + quote introduces, with `Code.ident` as the explicit way out. +- **Positions inside generated code.** A type error in generated code is + reported at the macro use, not at the place in the quote. +- **Attribute payloads beyond one string.** `@Json.key("user_age")` reaches + the macro; `@Json.codec({strict: true})` does not yet pass its argument. +- **Parametric types.** `Type.info` of `result` or a record with type + parameters works for the common shapes, without a specification of what + it returns for the rest. +- **Types local to an expression** cannot be named by an instance, which + lives at the top level. +- **Sharing instances between files.** Two files that encode `user` each + get an `encode$user`. +- **Editor tooling**: hover and go-to-definition inside macro uses, and a + command to show the expansion. +- **Interface files.** A macro module with a `.resi` is untested: the + interface has to carry `@macro` and `@generic`. +- **Windows and the playground of rescript-lang.org.** QuickJS is C; it + builds on macOS and Linux here and is untested on the other release + targets. + +## Open questions + +1. **Explicit quotes or Zig-style bodies.** This RFC chooses quotes: one + mechanism for every output shape, at the cost of a quote mark on each + generated piece. +2. **The plain-call form.** `Json.encode(user)` hides that a macro runs. + The alternative is `%Json.encode(user)` everywhere, which is honest and + noisier, and cannot be passed as a value. +3. **The engine.** QuickJS only, or Node as an option for macros that need + npm packages with native parts. QuickJS runs plain JavaScript packages. +4. **Names.** `@macro`, `@generic`, `%code`, `%comptime`, the module + `Macro`. `Macro.Type` takes the place of the standard library's `Type` + under `open Macro`; it includes that module so nothing is lost. +5. **Text or trees.** Expansion edits source text and type checks again. + It is simple, and gives generated code everything written code gets. A + tree-based expansion that types only the generated piece is faster and + much more code. The measurement that decides is a large project with + many derives. + +## Trying it + +```bash +# the tests +cargo test --manifest-path compiler-rust/Cargo.toml --test macros + +# the playground +cd playground +npm ci +npm run build:wasm +npm run dev +``` + +The playground has an example for each section of the tour. Its "Expanded" +tab shows the file after expansion, "JavaScript" the output, and "Output" +what the program prints. From 197bc19374852f57180144e1622eb27f39a8ad7d Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:17:49 +0100 Subject: [PATCH 12/38] playground: wrap long lines of the expanded source Co-authored-by: Jaap Frolich Session: https://jakes-mac-mini.tail23a77e.ts.net:8443/session/os-01a1ca09-2757-709a-bbb1-e57ccc4d104f Signed-off-by: Jaap Frolich --- playground/index.html | 1 + playground/src/App.jsx | 2 ++ 2 files changed, 3 insertions(+) diff --git a/playground/index.html b/playground/index.html index b57e6e5195..811570001e 100644 --- a/playground/index.html +++ b/playground/index.html @@ -4,6 +4,7 @@ ReScript macros playground +
diff --git a/playground/src/App.jsx b/playground/src/App.jsx index 7ca86d5f58..edc5fceee5 100644 --- a/playground/src/App.jsx +++ b/playground/src/App.jsx @@ -43,6 +43,8 @@ const READONLY_OPTIONS = { domReadOnly: true, renderLineHighlight: "none", padding: { top: 8 }, + wordWrap: "on", + wrappingIndent: "deepIndent", }; function languageOf(filename) { From adc427f40d833fbbe1572bc1d631522365b467c1 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:20:11 +0100 Subject: [PATCH 13/38] CHANGELOG: compile-time macros Co-authored-by: Jaap Frolich Session: https://jakes-mac-mini.tail23a77e.ts.net:8443/session/os-01a1ca09-2757-709a-bbb1-e57ccc4d104f Signed-off-by: Jaap Frolich --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 778d702ae4..be130bb8a9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,8 @@ #### :rocket: New Feature +- Add compile-time macros to the Rust compiler: `@macro` and `@generic` functions that return quoted code (`%code`, `%type`, `%pat` with `${...}` holes), `%comptime`, and the `Macro` module. `rescript build` does not expand them yet; see `docs/comptime`. https://github.com/jfrolich/rescript-rust/pull/90 + #### :bug: Bug fix - JSX v4: keep `@directive` on an async component's own function instead of its generated sync wrapper, so `@react.component let make = @directive("'use cache';") async (...) => ...` compiles to an async function that starts with `'use cache'` (ReScript 12 dropped the directive; Next.js rejects it on a sync function). From 85cd51edb75f0af4e052d38b02759ebf16cc52ac Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:34:06 +0100 Subject: [PATCH 14/38] macros: name instances by what differs, more examples - An instance is named after the types at the open positions of the macro's signature: Decode.fromJson at user is fromJson$user, not fromJson$JSON_t. - A parameter the generated code does not mention is written as _, so it does not warn. - CompilerOptions::capture_loaded_modules returns the units a compilation loaded, for a host that keeps them for the next one. - Examples: a JSON decoder by expected type, equality, default values, pattern macros and checked literals. Co-authored-by: Jaap Frolich Session: https://jakes-mac-mini.tail23a77e.ts.net:8443/session/os-01a1ca09-2757-709a-bbb1-e57ccc4d104f Signed-off-by: Jaap Frolich --- compiler-rust/src/cli/bsc.rs | 1 + compiler-rust/src/driver.rs | 28 ++++++++++++ compiler-rust/src/macros/discover.rs | 33 +++++++++++-- playground/examples/decode/Decode.res | 61 +++++++++++++++++++++++++ playground/examples/decode/Main.res | 30 ++++++++++++ playground/examples/default/Default.res | 20 ++++++++ playground/examples/default/Main.res | 15 ++++++ playground/examples/equal/Equal.res | 28 ++++++++++++ playground/examples/equal/Main.res | 12 +++++ playground/examples/index.json | 36 +++++++++++++++ playground/examples/pattern/Http.res | 26 +++++++++++ playground/examples/pattern/Main.res | 16 +++++++ 12 files changed, 301 insertions(+), 5 deletions(-) create mode 100644 playground/examples/decode/Decode.res create mode 100644 playground/examples/decode/Main.res create mode 100644 playground/examples/default/Default.res create mode 100644 playground/examples/default/Main.res create mode 100644 playground/examples/equal/Equal.res create mode 100644 playground/examples/equal/Main.res create mode 100644 playground/examples/pattern/Http.res create mode 100644 playground/examples/pattern/Main.res diff --git a/compiler-rust/src/cli/bsc.rs b/compiler-rust/src/cli/bsc.rs index c00248f946..75713d9879 100644 --- a/compiler-rust/src/cli/bsc.rs +++ b/compiler-rust/src/cli/bsc.rs @@ -544,6 +544,7 @@ fn run(args: Vec, registry: Option) -> Result<()> { gentype_declarations_only: false, js_package_specs: Vec::new(), capture_intermediates: false, + capture_loaded_modules: false, dumps: Vec::new(), skip_js_render: false, publish_in_process_signature: true, diff --git a/compiler-rust/src/driver.rs b/compiler-rust/src/driver.rs index a51350df4d..e14814e171 100644 --- a/compiler-rust/src/driver.rs +++ b/compiler-rust/src/driver.rs @@ -662,6 +662,9 @@ pub struct CompilerOptions { /// When true, `compile_source_in_process` captures the typed tree, /// raw lambda, and lambda sexps for display (used by the playground). pub capture_intermediates: bool, + /// Return the units a compilation loaded in its result's + /// `loaded_modules`. + pub capture_loaded_modules: bool, /// Intermediate representations an in-process compile captures into its /// result's `dumps`, in this order. pub dumps: Vec, @@ -869,6 +872,7 @@ impl Default for CompilerOptions { gentype_resolver: None, gentype_declarations_only: false, capture_intermediates: false, + capture_loaded_modules: false, dumps: Vec::new(), skip_js_render: false, publish_in_process_signature: true, @@ -12493,6 +12497,9 @@ pub struct InProcessCompileResult { pub warnings: String, /// The source after macro expansion, when the file uses macros. pub expanded_source: Option, + /// The other units this compilation loaded, with + /// `CompilerOptions::capture_loaded_modules`. + pub loaded_modules: Vec, } /// Owned in-process compilation state after typechecking and Lambda lowering, @@ -12508,6 +12515,9 @@ pub struct InProcessPreJsCompileResult { pub jsx_preserve: bool, pub signature: crate::types::decl::Signature, pub pers_struct: Option, + /// The other units this compilation loaded, with + /// `CompilerOptions::capture_loaded_modules`. + pub loaded_modules: Vec, /// Resolves the location handles of `lowered_lambda` and /// `hoisted_functions`; outlives the parse arena and typed tree. pub lam_locs: crate::lambda::LamLocTable, @@ -13600,6 +13610,22 @@ pub fn compile_preprocessed_structure_in_process_until_js( pers_struct: pers_struct.take(), })?; } + // The units this compilation loaded, for a host that keeps them for the + // next compilation instead of loading them again (the playground, which + // type checks the standard library from source). + let loaded_modules = if options.capture_loaded_modules { + let (modules, _) = + persistent_env_after_signature.extract_all_cached_modules(&type_ctx, Some(arena)); + let mut modules: Vec = modules + .into_iter() + .filter(|(name, _)| name != module_name) + .map(|(_, module)| module) + .collect(); + modules.sort_by(|a, b| a.ps_name.cmp(&b.ps_name)); + modules + } else { + Vec::new() + }; tctx.persistent_env = Some(persistent_env_after_signature); // Capture typed tree sexp for the playground (only if requested). @@ -13901,6 +13927,7 @@ pub fn compile_preprocessed_structure_in_process_until_js( jsx_preserve, signature: published_signature, pers_struct, + loaded_modules, lam_locs, typed_tree_sexp, raw_lambda_sexp, @@ -14126,6 +14153,7 @@ pub fn finish_preprocessed_structure_in_process_from_js_boundary_with_metadata_h }); Ok(InProcessCompileResult { expanded_source: None, + loaded_modules: std::mem::take(&mut pre_js.loaded_modules), js_output: js, js_outputs, signature: pre_js.signature, diff --git a/compiler-rust/src/macros/discover.rs b/compiler-rust/src/macros/discover.rs index 06c76f0970..210659ceee 100644 --- a/compiler-rust/src/macros/discover.rs +++ b/compiler-rust/src/macros/discover.rs @@ -147,6 +147,15 @@ enum ResultKind { struct Signature { params: Vec, result: ResultKind, + /// Per parameter, and for the result: whether the declared type has a + /// type variable, so that its type differs from use to use. + open_params: Vec, + open_result: bool, +} + +/// Whether a type of a macro's declared signature has a type variable. +fn is_open(ctx: &TypeContext, ty: TypeExprRef) -> bool { + reflect::print_type(ctx, ty).contains('\'') } fn macro_type_name(ctx: &TypeContext, ty: TypeExprRef) -> Option<(String, Vec)> { @@ -198,6 +207,8 @@ fn signature(ctx: &TypeContext, ty: TypeExprRef) -> (Signature, Vec Signature { params: types.iter().map(|ty| param_kind(ctx, *ty)).collect(), result: result_kind(ctx, *ret), + open_params: types.iter().map(|ty| is_open(ctx, *ty)).collect(), + open_result: is_open(ctx, *ret), }, types, *ret, @@ -207,6 +218,8 @@ fn signature(ctx: &TypeContext, ty: TypeExprRef) -> (Signature, Vec Signature { params: Vec::new(), result: result_kind(ctx, ty), + open_params: Vec::new(), + open_result: is_open(ctx, ty), }, Vec::new(), ty, @@ -1222,10 +1235,10 @@ fn resolve_generic(tctx: &mut TypeCheckContext<'_>, discovery: &mut Discovery, g let mut code = json!({ "c": param }); code["t"] = reflect::type_ref(ctx, &mut table, ty); macro_args.push(code); - params.push(format!("{param}: {printed}")); + params.push((param, printed.clone())); key_parts.push(printed.clone()); - // A unit argument says nothing about the instance. - if printed != "unit" { + // The name says what differs from instance to instance. + if generic.signature.open_params.get(index) == Some(&true) { name_parts.push(printed); } if let Some(call) = &generic.call @@ -1289,7 +1302,7 @@ fn resolve_generic(tctx: &mut TypeCheckContext<'_>, discovery: &mut Discovery, g return; } }; - if name_parts.is_empty() { + if generic.signature.open_result || name_parts.is_empty() { name_parts.push(result.clone()); } let name = discovery @@ -1302,7 +1315,17 @@ fn resolve_generic(tctx: &mut TypeCheckContext<'_>, discovery: &mut Discovery, g }; discovery.add_instance(format!( "{name} = ({}){annotation} => {body}", - params.join(", ") + params + .iter() + .map(|(param, ty)| { + // A parameter the macro's code does not mention. + let used = body + .split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '$')) + .any(|word| word == param); + format!("{}: {ty}", if used { param } else { "_" }) + }) + .collect::>() + .join(", ") )); name } diff --git a/playground/examples/decode/Decode.res b/playground/examples/decode/Decode.res new file mode 100644 index 0000000000..8176d24b7c --- /dev/null +++ b/playground/examples/decode/Decode.res @@ -0,0 +1,61 @@ +open Macro + +exception DecodeError(string) +let fail = (message: string) => throw(DecodeError(message)) + +let field = (json: JSON.t, key: string): JSON.t => + switch json { + | Object(fields) => fields->Dict.get(key)->Option.getOr(JSON.Null) + | _ => fail(`expected an object with the field "${key}"`) + } + +// The result type of this @generic is a type variable: nothing in the +// arguments says what to decode to. `expected()` is the type the call site +// wants, so the annotation `let user: user = ...` picks the decoder. +@generic +let fromJson = (json: code): code<'a> => + switch Type.info(expected()) { + | String => + %code( + switch ${json} { + | String(text) => text + | _ => fail("expected a string") + } + ) + | Int => + %code( + switch ${json} { + | Number(number) => Float.toInt(number) + | _ => fail("expected a number") + } + ) + | Bool => + %code( + switch ${json} { + | Boolean(bool) => bool + | _ => fail("expected true or false") + } + ) + | Option(inner) => + %code( + switch ${json} { + | Null => None + | present => Some((fromJson(present): ${inner})) + } + ) + | Array(inner) => + %code( + switch ${json} { + | Array(items) => items->Array.map(item => (fromJson(item): ${inner})) + | _ => fail("expected an array") + } + ) + | Record({fields}) => + Code.record( + fields->Array.map(f => ( + f.name, + %code((fromJson(field(${json}, ${Code.string(f.jsName)})): ${f.typ})), + )), + ) + | _ => error(`Decode.fromJson cannot decode to ${Type.name(expected())}`) + } diff --git a/playground/examples/decode/Main.res b/playground/examples/decode/Main.res new file mode 100644 index 0000000000..fdc43a5225 --- /dev/null +++ b/playground/examples/decode/Main.res @@ -0,0 +1,30 @@ +type address = {street: string, city: string} + +type user = { + name: string, + age: int, + email: option, + addresses: array
, +} + +let json = JSON.parseOrThrow(`{ + "name": "Alice", + "age": 30, + "email": null, + "addresses": [{"street": "Main St 1", "city": "Utrecht"}] +}`) + +// The annotation is what the macro decodes to. +let user: user = Decode.fromJson(json) + +Console.log(user) +Console.log(user.addresses->Array.map(address => address.city)) + +// Something that is not a user fails at run time, with a message: +let broken = try { + let user: user = Decode.fromJson(JSON.parseOrThrow(`{"name": 1}`)) + user.name +} catch { +| Decode.DecodeError(message) => "Not a user: " ++ message +} +Console.log(broken) diff --git a/playground/examples/default/Default.res b/playground/examples/default/Default.res new file mode 100644 index 0000000000..ad8e831da6 --- /dev/null +++ b/playground/examples/default/Default.res @@ -0,0 +1,20 @@ +open Macro + +// A value for every type, chosen by the type the call site expects. +@generic +let value = (_: code): code<'a> => + switch Type.info(expected()) { + | Int => %code(0) + | Float => %code(0.0) + | String => %code("") + | Bool => %code(false) + | Array(_) => %code([]) + | Option(_) => %code(None) + | Record({fields}) => Code.record(fields->Array.map(f => (f.name, %code(value())))) + | Variant({constructors}) => + switch constructors->Array.find(c => c.args->Array.length == 0 && c.fields->Array.length == 0) { + | Some(c) => Code.ident(c.name) + | None => error(`Default.value: ${Type.name(expected())} has no constructor without arguments`) + } + | _ => error(`Default.value: there is no default for ${Type.name(expected())}`) + } diff --git a/playground/examples/default/Main.res b/playground/examples/default/Main.res new file mode 100644 index 0000000000..1d2287f5d8 --- /dev/null +++ b/playground/examples/default/Main.res @@ -0,0 +1,15 @@ +type theme = Light | Dark | Custom(string) + +type settings = { + name: string, + retries: int, + verbose: bool, + tags: array, + theme: theme, + proxy: option, +} + +let initial: settings = Default.value() + +Console.log(initial) +Console.log({...initial, name: "production", retries: 3}) diff --git a/playground/examples/equal/Equal.res b/playground/examples/equal/Equal.res new file mode 100644 index 0000000000..76add29300 --- /dev/null +++ b/playground/examples/equal/Equal.res @@ -0,0 +1,28 @@ +open Macro + +// Two arguments of the same type. The comparison is written out per type: +// no run-time reflection, no walking of unknown values. +@generic +let equal = (a: code<'a>, b: code<'a>): code => + switch Type.info(typeOf(a)) { + | Int | Float | String | Bool | Unit | BigInt | Char => %code(${a} === ${b}) + | Option(_) => + %code( + switch (${a}, ${b}) { + | (Some(left), Some(right)) => equal(left, right) + | (None, None) => true + | _ => false + } + ) + | Array(_) => + %code({ + let (left, right) = (${a}, ${b}) + Array.length(left) == Array.length(right) && + left->Array.everyWithIndex((item, index) => equal(item, right->Array.getUnsafe(index))) + }) + | Record({fields}) => + fields->Array.reduce(%code(true), (all, f) => + %code(${all} && equal(${a->Code.field(f.name)}, ${b->Code.field(f.name)})) + ) + | _ => error(`Equal.equal cannot compare values of type ${Type.name(typeOf(a))}`) + } diff --git a/playground/examples/equal/Main.res b/playground/examples/equal/Main.res new file mode 100644 index 0000000000..842c398bcb --- /dev/null +++ b/playground/examples/equal/Main.res @@ -0,0 +1,12 @@ +type point = {x: int, y: int} +type shape = {name: string, corners: array, label: option} + +let square = { + name: "square", + corners: [{x: 0, y: 0}, {x: 1, y: 0}, {x: 1, y: 1}, {x: 0, y: 1}], + label: None, +} + +Console.log(Equal.equal(square, {...square, label: None})) +Console.log(Equal.equal(square, {...square, corners: [{x: 0, y: 0}]})) +Console.log(Equal.equal({x: 1, y: 2}, {x: 1, y: 2})) diff --git a/playground/examples/index.json b/playground/examples/index.json index 87c28e2406..cff6c61c70 100644 --- a/playground/examples/index.json +++ b/playground/examples/index.json @@ -81,5 +81,41 @@ "Units.res", "Main.res" ] + }, + { + "id": "decode", + "title": "Generic by result type: JSON decoder", + "summary": "Decode.fromJson(json) decodes to the type the call site expects.", + "files": [ + "Decode.res", + "Main.res" + ] + }, + { + "id": "equal", + "title": "Generic with two arguments: equality", + "summary": "Equal.equal(a, b) is written out field by field for the type of its arguments.", + "files": [ + "Equal.res", + "Main.res" + ] + }, + { + "id": "default", + "title": "A value for every type", + "summary": "Default.value() builds a value from the expected type alone.", + "files": [ + "Default.res", + "Main.res" + ] + }, + { + "id": "pattern", + "title": "Pattern macros and checked literals", + "summary": "%Http.status(\"ok\") is a pattern; %Http.color(\"#ff8800\") is checked and converted while compiling.", + "files": [ + "Http.res", + "Main.res" + ] } ] diff --git a/playground/examples/pattern/Http.res b/playground/examples/pattern/Http.res new file mode 100644 index 0000000000..48e00047a2 --- /dev/null +++ b/playground/examples/pattern/Http.res @@ -0,0 +1,26 @@ +open Macro + +// A macro that returns `pat` is used where a pattern is written. +@macro +let status = (name: string): pat => + switch name { + | "ok" => %pat(200 | 201 | 204) + | "redirect" => %pat(301 | 302 | 307 | 308) + | "missing" => Pat.int(404) + | "server error" => %pat(500 | 502 | 503) + | _ => error(`Http.status: "${name}" is not a status this macro knows`) + } + +// A literal that is checked and converted while compiling. +@macro +let color = (hex: string): code<(int, int, int)> => { + let channel = (start: int) => { + let value = Float.parseInt(String.slice(hex, ~start, ~end=start + 2), ~radix=16) + Float.isNaN(value) ? error(`Http.color: "${hex}" is not a color like #ff8800`) : Code.int(Float.toInt(value)) + } + if String.length(hex) != 7 || !String.startsWith(hex, "#") { + error(`Http.color: "${hex}" is not a color like #ff8800`) + } else { + Code.tuple([channel(1), channel(3), channel(5)]) + } +} diff --git a/playground/examples/pattern/Main.res b/playground/examples/pattern/Main.res new file mode 100644 index 0000000000..efab6df9ef --- /dev/null +++ b/playground/examples/pattern/Main.res @@ -0,0 +1,16 @@ +let describe = (code: int) => + switch code { + | %Http.status("ok") => "fine" + | %Http.status("redirect") => "moved" + | %Http.status("missing") => "not found" + | %Http.status("server error") => "broken" + | _ => "something else" + } + +Console.log([200, 302, 404, 503, 418]->Array.map(describe)) + +let (red, green, blue) = %Http.color("#ff8800") +Console.log3(red, green, blue) + +// Not a color, so not a program: +// let oops = %Http.color("#ff88") From 236999ddfed75a6812c700d2ac4b0e9a1b7d97c8 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:42:30 +0100 Subject: [PATCH 15/38] parser: report $ in an interpolated template pattern as before After the first interpolation of a template literal in a pattern, the rest is scanned as ordinary tokens, and OCaml's scanner reports the $ of a later ${ as an unknown character. ${ is a token now, so the pattern parser reports it the same way. Fixes the diagnostic parity of tests/syntax_tests/data/parsing/errors/pattern/templateLiteral.res. Co-authored-by: Jaap Frolich Session: https://jakes-mac-mini.tail23a77e.ts.net:8443/session/os-01a1ca09-2757-709a-bbb1-e57ccc4d104f Signed-off-by: Jaap Frolich --- compiler-rust/src/parser/pattern.rs | 6 ++++++ compiler-rust/src/parser/state.rs | 12 ++++++++++++ 2 files changed, 18 insertions(+) diff --git a/compiler-rust/src/parser/pattern.rs b/compiler-rust/src/parser/pattern.rs index fa3be91be1..63385b053f 100644 --- a/compiler-rust/src/parser/pattern.rs +++ b/compiler-rust/src/parser/pattern.rs @@ -94,6 +94,12 @@ fn parse_template_constant( fn skip_tokens(p: &mut Parser<'_>) { if p.token != Token::Eof { p.next(); + // The rest of the template is scanned as ordinary tokens, where + // a `$` is not one: OCaml's scanner reports it. `${` is a token + // here (the hole of a macro quote), so report it the same way. + if p.token == Token::DollarLbrace { + p.report_unknown_character('$', p.start_pos); + } if p.token == Token::Backtick { p.next(); } else { diff --git a/compiler-rust/src/parser/state.rs b/compiler-rust/src/parser/state.rs index 3a2863c900..44cd4adfa0 100644 --- a/compiler-rust/src/parser/state.rs +++ b/compiler-rust/src/parser/state.rs @@ -476,6 +476,18 @@ impl<'src> Parser<'src> { } /// Record a diagnostic error at specific positions. + /// Report a character that is not a token where it stands, as the + /// scanner does: outside the parser's error regions. + pub fn report_unknown_character(&mut self, ch: char, start_pos: Position) { + let mut end_pos = start_pos; + end_pos.cnum += 1; + self.diagnostics.push(ParserDiagnostic { + start_pos, + end_pos, + category: DiagnosticCategory::unknown_uchar(ch), + }); + } + pub fn err_at(&mut self, start_pos: Position, end_pos: Position, category: DiagnosticCategory) { if let Some(region) = self.regions.last_mut() { if *region == RegionStatus::Report { From 7753c553a1c3f1ddfe71b95292228cd6c63ad353 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:55:46 +0100 Subject: [PATCH 16/38] site: the RFC as a page with live examples The playground's index page is now the RFC, rendered from docs/comptime/README.md. Each example block in it is a live example: the project on the left, and on the right the source after expansion with the lines the macros wrote marked, the JavaScript, the parse tree, typed tree and Lambda, and the program's output. An example starts from a result built with the site and loads the compiler when it is edited. The full playground moves to playground.html, and IMPLEMENTATION.md gets a page of its own. The wasm entry point keeps the standard library modules a compile loaded, so later compiles do not type check them again (700 ms to under 300 ms per file), and returns the expansion formatted by the printer. Co-authored-by: Jaap Frolich Session: https://jakes-mac-mini.tail23a77e.ts.net:8443/session/os-01a1ca09-2757-709a-bbb1-e57ccc4d104f Signed-off-by: Jaap Frolich --- docs/comptime/README.md | 225 +++- playground/.gitignore | 1 + playground/README.md | 24 +- playground/crate/src/lib.rs | 158 ++- playground/implementation.html | 30 + playground/index.html | 27 +- playground/package-lock.json | 220 ++++ playground/package.json | 17 +- playground/playground.html | 13 + playground/scripts/prebuild-examples.mjs | 47 + playground/src/App.jsx | 3 + playground/src/compiler-worker.js | 1 + playground/src/engine.js | 21 +- playground/src/rfc/CodeEditor.jsx | 75 ++ playground/src/rfc/Diagrams.jsx | 148 +++ playground/src/rfc/Example.jsx | 317 ++++++ playground/src/rfc/Markdown.jsx | 178 +++ playground/src/rfc/Page.jsx | 158 +++ playground/src/rfc/compiler.js | 106 ++ playground/src/rfc/highlight.jsx | 124 ++ playground/src/rfc/implementation.jsx | 19 + playground/src/rfc/main.jsx | 19 + playground/src/rfc/rescript-mode.js | 83 ++ playground/src/rfc/rfc.css | 1310 ++++++++++++++++++++++ playground/src/style.css | 14 + playground/vite.config.js | 14 + 26 files changed, 3304 insertions(+), 48 deletions(-) create mode 100644 playground/implementation.html create mode 100644 playground/playground.html create mode 100644 playground/scripts/prebuild-examples.mjs create mode 100644 playground/src/rfc/CodeEditor.jsx create mode 100644 playground/src/rfc/Diagrams.jsx create mode 100644 playground/src/rfc/Example.jsx create mode 100644 playground/src/rfc/Markdown.jsx create mode 100644 playground/src/rfc/Page.jsx create mode 100644 playground/src/rfc/compiler.js create mode 100644 playground/src/rfc/highlight.jsx create mode 100644 playground/src/rfc/implementation.jsx create mode 100644 playground/src/rfc/main.jsx create mode 100644 playground/src/rfc/rescript-mode.js create mode 100644 playground/src/rfc/rfc.css diff --git a/docs/comptime/README.md b/docs/comptime/README.md index f5f0a26418..b3a5badee8 100644 --- a/docs/comptime/README.md +++ b/docs/comptime/README.md @@ -71,8 +71,9 @@ ReScript, and is type checked like code written by hand. ## A tour -Every example here is a project in `playground/examples` and is compiled by -the tests. +Every example here is a project in `playground/examples`, compiled by the +tests. On the web version of this page each one is live: edit the code and +the expansion, the JavaScript and the output follow. ### Quotes and holes @@ -83,11 +84,33 @@ code. `%type(...)` and `%pat(...)` quote a type and a pattern. A quote is checked for syntax where it is written. Its types are checked where the macro is used, after the holes are filled. + + +```rescript +// Debug.res +@macro +let log = (e: code<'a>): code<'a> => + %code({ + let value = ${e} + Console.log2(${Code.string(Code.print(e) ++ " =")}, value) + value + }) + +// Main.res +let total = %Debug.log(price *. Int.toFloat(quantity)) +``` + + + +### Code and values + A parameter of type `code<'a>` receives the code of the argument. A parameter of an ordinary type receives a value, which the call site has to write as a literal. There is no `comptime` keyword: the type of the parameter says when it exists. + + ```rescript @generic let rec pow = (base: code, n: int): code => @@ -103,6 +126,8 @@ let rec pow = (base: code, n: int): code => } ``` + + `Power.pow(x, 10)` compiles to four multiplications. The recursion ran in the compiler. @@ -125,6 +150,8 @@ comparisons, printers. describes a type one level deep: its fields or constructors, with their types as values that can be asked again. + + ```rescript @generic let encode = (value: code<'a>): code => @@ -156,9 +183,7 @@ let encode = (value: code<'a>): code => } ``` -The macro does not recurse into the fields. It returns code that calls -`encode` on each field, and the compiler expands those calls in turn. That is -why a recursive type works, and why each type gets one function. +Used on a record: ```rescript type user = { @@ -171,18 +196,18 @@ type user = { let json = Json.encode(alice) ``` -The file the compiler compiles after expansion (redundant parentheses -removed): +The file the compiler compiles after expansion: ```rescript -@res.macroInstances @warning("-39") let rec encode$user = (a$: user): JSON.t => - JSON.Encode.object(Dict.fromArray([ - ("name", encode$string(a$.name)), - ("user_age", encode$int(a$.age)), - ("email", encode$option_string(a$.email)), - ("tags", encode$array_string(a$.tags)), - ])) + JSON.Encode.object( + Dict.fromArray([ + ("name", encode$string(a$.name)), + ("user_age", encode$int(a$.age)), + ("email", encode$option_string(a$.email)), + ("tags", encode$array_string(a$.tags)), + ]), + ) and encode$string = (a$: string): JSON.t => JSON.Encode.string(a$) and encode$int = (a$: int): JSON.t => JSON.Encode.int(a$) and encode$option_string = (a$: option): JSON.t => @@ -196,9 +221,16 @@ and encode$array_string = (a$: array): JSON.t => let json = encode$user(alice) ``` + + +The macro does not recurse into the fields. It returns code that calls +`encode` on each field, and the compiler expands those calls in turn. That is +why a recursive type works, and why each type gets one function: an +*instance*. + A name with a `$` cannot be written in source, so an instance cannot collide -with a name of the file. The group is not part of the module's signature and -is not exported. The backend inlines the small ones: the JavaScript of +with a name of the file. The instances are not part of the module's signature +and are not exported. The backend inlines the small ones: the JavaScript of `encode$user` reads `a$.name` directly. A `@generic` waits for inference. It is expanded when the top-level item that @@ -217,11 +249,86 @@ is the value `toJson` in the module that defines the type, if there is one: the way a library says "encode my type like this" without the macro knowing the library. +### By the type that is expected + +`expected()` is the type the call site of a `@generic` wants as result. A +decoder has nothing else to go on: its argument is always `JSON.t`. + + + +```rescript +@generic +let fromJson = (json: code): code<'a> => + switch Type.info(expected()) { + | String => + %code( + switch ${json} { + | String(text) => text + | _ => fail("expected a string") + } + ) + | Option(inner) => + %code( + switch ${json} { + | Null => None + | present => Some((fromJson(present): ${inner})) + } + ) + | Record({fields}) => + Code.record( + fields->Array.map(f => ( + f.name, + %code((fromJson(field(${json}, ${Code.string(f.jsName)})): ${f.typ})), + )), + ) + // ... + } + +// Main.res: the annotation is what the macro decodes to +let user: user = Decode.fromJson(json) +``` + + + +The same idea gives a value for every type: + + + +```rescript +let initial: settings = Default.value() +``` + + + +### Two arguments + +A `@generic` can take several pieces of code. Structural equality, written +out per type: + + + +```rescript +@generic +let equal = (a: code<'a>, b: code<'a>): code => + switch Type.info(typeOf(a)) { + | Int | Float | String | Bool | Unit | BigInt | Char => %code(${a} === ${b}) + | Record({fields}) => + fields->Array.reduce(%code(true), (all, f) => + %code(${all} && equal(${a->Code.field(f.name)}, ${b->Code.field(f.name)})) + ) + // ... + } +``` + + + ### Declarations from a type A macro attached to a type receives the declaration and returns declarations, which are added after the type. + + ```rescript @macro let derive = (t: Type.decl): decls => @@ -251,9 +358,28 @@ type color = Red | Green | @Enum.label("navy blue") Blue colorValues->Array.map(colorToString) // ["Red", "Green", "navy blue"] ``` + + Names are built with `Pat.var`: a hole can stand where a name is bound. -### Types, patterns, modules +One declaration per field, with the field's type in it: + + + +```rescript +@Lens.derive +type point = {x: int, y: int, label: string} + +origin->Lens.update(point_x, x => x + 10) +``` + + + +### Types + +A macro in a type position takes types and returns a type. + + ```rescript // Partial.res: every field optional @@ -263,29 +389,58 @@ let t = (source: typ): typ => | Record({fields}) => Type.record(fields->Array.map(f => {...f, optional: true})) | _ => error(`Partial.t needs a record type, and ${Type.name(source)} is not one`) } -``` -```rescript +// Main.res type userPatch = %Partial.t(user) +``` + + + +### Patterns and checked literals +A macro that returns `pat` is used where a pattern is written. A macro that +takes a literal can check it and convert it while compiling: a color that is +not a color is not a program. + + + +```rescript let describe = code => switch code { - | %Http.status("ok") => "fine" // a macro that returns pat + | %Http.status("ok") => "fine" + | %Http.status("missing") => "not found" | _ => "other" } +let (red, green, blue) = %Http.color("#ff8800") +``` + + + +### Modules and lets + +A macro that returns declarations can fill a module, stand at the top level, +or replace the `let` it is attached to. + + + +```rescript module Length = %Units.table("meters", [("feet", 0.3048), ("miles", 1609.344)]) @Trace.calls let marathon = (miles: float) => Length.milesToMeters(miles) /. 1000.0 ``` + + ### Computing now `%comptime(expr)` evaluates an expression while compiling and puts the value in its place as a literal. It needs no macro: `expr` is ordinary code that uses other modules. + + ```rescript let primes = %comptime(Sieve.primesBelow(60)) ``` @@ -294,14 +449,27 @@ let primes = %comptime(Sieve.primesBelow(60)) let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59]; ``` + + The output does not import `Sieve`. ### Reading files -`Macro.readFile(path)` is the text of a file of the project. The example -`files` reads `en.json`: `%I18n.t("title")` is a string, `%I18n.t("greeting")` -is a function with a labelled argument for each placeholder of the message, -and a key that is not in the file does not compile: +`Macro.readFile(path)` is the text of a file of the project. Here +`%I18n.t("title")` is a string, `%I18n.t("greeting")` is a function with a +labelled argument for each placeholder of the message, and a key that is not +in `en.json` does not compile. + + + +```rescript +let title: string = %I18n.t("title") +let greet = %I18n.t("greeting") + +greet(~name="Alice", ~count="3") +``` + + ``` We've found a bug for you! @@ -488,6 +656,8 @@ text. Measured on an Apple M-series Mac mini, release builds. + + | What | Time | | --- | --- | | Create a QuickJS engine | 92 µs, once per compiler thread | @@ -496,6 +666,8 @@ Measured on an Apple M-series Mac mini, release builds. | Start ppx-spice once (it is started once per file) | 6.1 ms | | Start Node once | 70 ms | + + The engine numbers are from a benchmark of the embedding with stub answers (rquickjs 0.9); they do not include the type checker's work to answer. @@ -588,6 +760,5 @@ npm run build:wasm npm run dev ``` -The playground has an example for each section of the tour. Its "Expanded" -tab shows the file after expansion, "JavaScript" the output, and "Output" -what the program prints. +The playground's main page is this document with the examples live; the +full playground, with any number of files, is `playground.html`. diff --git a/playground/.gitignore b/playground/.gitignore index 9cf9ec4728..f7031f4ddd 100644 --- a/playground/.gitignore +++ b/playground/.gitignore @@ -3,3 +3,4 @@ dist/ public/stdlib.json # Override root .gitignore that excludes *.jsx (ReScript build artifacts) !*.jsx +src/rfc/prebuilt.json diff --git a/playground/README.md b/playground/README.md index 50ab69d3bc..d3f5d151ba 100644 --- a/playground/README.md +++ b/playground/README.md @@ -1,14 +1,19 @@ -# Macros playground +# Macros site and playground -A browser playground for the Rust compiler and its compile-time macros -([docs/comptime](../docs/comptime/README.md)). The compiler runs in -WebAssembly in a worker; macros run in the browser's JavaScript engine. A +A static site for the Rust compiler's compile-time macros. The compiler runs +in WebAssembly in a worker; macros run in the browser's JavaScript engine. A project is a few files: they are compiled in dependency order, and the compiled program is run. -The right-hand side shows, for the selected file, the source after macro -expansion, the JavaScript, the program's output, and the compiler's -intermediate trees. +| Page | What | +| --- | --- | +| `index.html` | The RFC, rendered from [docs/comptime/README.md](../docs/comptime/README.md). Each `` block in it becomes a live example: the project on the left, and on the right the source after expansion with the generated lines marked, the JavaScript, the compiler's trees, and the program's output. | +| `implementation.html` | [docs/comptime/IMPLEMENTATION.md](../docs/comptime/IMPLEMENTATION.md). | +| `playground.html` | The full playground: any number of files, share links. | + +The examples on the RFC page show a result that was built with the site, so +the page reads without loading the compiler; it is loaded when an example is +edited or its trees are opened. ## Build @@ -17,7 +22,7 @@ cd playground npm ci npm run build:wasm # compiler-rust -> crate/pkg (needs wasm-pack and the wasm32-unknown-unknown target) npm run smoke # builds and runs every example with the wasm compiler, in Node -npm run build # static site in dist/ +npm run build # builds the examples for the RFC page, then the static site in dist/ ``` `npm run dev` serves it with hot reload. @@ -37,9 +42,10 @@ and the compiled program import. `npm run build` bundles both into | --- | --- | | `crate/` | The wasm-bindgen entry points: `compile_file`, the virtual file system, and the macro host that calls into the page. | | `src/engine.js` | The build: file order, compiling, running macros and the program. No dependency on the page; `scripts/smoke.mjs` runs it in Node. | +| `src/rfc/` | The RFC pages: the Markdown renderer, the live example, the diagrams. `scripts/prebuild-examples.mjs` writes the results they start from. | | `src/compiler-worker.js`, `src/compiler-client.js` | The worker the compiler runs in, and the page's side: a build that takes more than 20 seconds is stopped by replacing the worker. | | `src/App.jsx` | The page. | -| `examples/` | The example projects, listed in `examples/index.json`. `compiler-rust/tests/macros.rs` compiles all of them. | +| `examples/` | The example projects, listed in `examples/index.json`. `compiler-rust/tests/macros.rs` compiles all of them; the RFC page and the playground both show them. | ## Adding an example diff --git a/playground/crate/src/lib.rs b/playground/crate/src/lib.rs index 4b9f2e4c76..3cf68c3973 100644 --- a/playground/crate/src/lib.rs +++ b/playground/crate/src/lib.rs @@ -1,6 +1,7 @@ use wasm_bindgen::prelude::*; use std::cell::RefCell; +use std::collections::HashMap; use std::path::PathBuf; use std::sync::Arc; @@ -37,6 +38,8 @@ fn from_compiler_text(text: &str) -> String { thread_local! { static REGISTRY: RefCell = RefCell::new(new_registry()); + /// The modules of the standard library, with the path of their source. + static RUNTIME_SOURCES: RefCell> = RefCell::new(HashMap::new()); } fn new_registry() -> ModuleRegistry { @@ -65,6 +68,7 @@ pub fn vfs_delete_file(path: &str) { pub fn vfs_clear() { wasm_vfs::clear(); REGISTRY.with(|r| *r.borrow_mut() = new_registry()); + RUNTIME_SOURCES.with(|sources| sources.borrow_mut().clear()); } /// Register a module's source path for on-demand type checking. @@ -76,6 +80,142 @@ pub fn register_source_module(module_name: &str, source_path: &str) { r.borrow_mut() .insert_source_fallback_path(module_name.to_string(), source_path.into()); }); + RUNTIME_SOURCES.with(|sources| { + sources + .borrow_mut() + .insert(module_name.to_string(), source_path.into()); + }); +} + +/// Keep the standard library modules a compilation type checked from +/// source, so that the next compilation does not check them again. +fn keep_runtime_modules(loaded: Vec) { + RUNTIME_SOURCES.with(|sources| { + let sources = sources.borrow(); + REGISTRY.with(|r| { + let mut registry = r.borrow_mut(); + for module in loaded { + let name = module.ps_name.clone(); + let Some(path) = sources.get(&name) else { + continue; + }; + if registry.has_cached_module(&name) { + continue; + } + registry.register_module( + &name, + module, + InMemoryModuleInfo::new(path.clone(), false, Default::default(), true), + ); + } + }); + }); +} + +// ── Expanded source ───────────────────────────────────────────────────────── + +/// The macro-expanded source of a file as a person wants to read it: without +/// the bookkeeping attributes of expansion, and formatted. +fn readable_expansion(expanded: &str, filename: &str) -> String { + let text = strip_expansion_attributes(expanded); + let mut parser = Parser::for_expanded_source(filename, &text); + let structure = module::parse_structure(&mut parser); + if parser.has_errors() { + return text; + } + let comments = parser.comments().to_vec(); + let printed = rescript_compiler::parser::printer::print_structure_with_comments( + &structure, + comments, + parser.arena_mut(), + ); + space_instance_groups(&unescape_generated_names(&printed)) +} + +/// An instance group reads as one block: no blank line between its +/// functions, one after it. +fn space_instance_groups(text: &str) -> String { + let lines: Vec<&str> = text.lines().collect(); + let mut out = String::with_capacity(text.len()); + let mut in_group = false; + for (index, line) in lines.iter().enumerate() { + let continues = |line: &str| { + line.starts_with("and ") || line.starts_with([' ', '}', ')', ']', '|']) + }; + if in_group { + if line.is_empty() { + let next = lines[index + 1..].iter().find(|next| !next.is_empty()); + if next.is_some_and(|next| continues(next)) { + continue; + } + in_group = false; + } else if !continues(line) { + in_group = false; + out.push('\n'); + } + } + if let Some(rest) = line.strip_prefix("let rec ") + && rest.split([' ', ':', '=']).next().is_some_and(|name| name.contains('$')) + { + in_group = true; + } + out.push_str(line); + out.push('\n'); + } + out +} + +/// Remove `@res.macroInstances`, the `@warning("-39")` that follows it, and +/// `@expanded.M.f`, the mark of a macro attribute that was expanded. +fn strip_expansion_attributes(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + let mut rest = text; + loop { + let next = ["@res.macroInstances @warning(\"-39\") ", "@expanded."] + .iter() + .filter_map(|marker| rest.find(marker).map(|at| (at, *marker))) + .min(); + let Some((at, marker)) = next else { + out.push_str(rest); + return out; + }; + out.push_str(&rest[..at]); + rest = &rest[at + marker.len()..]; + if marker == "@expanded." { + // The macro's name, and the whitespace up to what it was on. + let end = rest + .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '.')) + .unwrap_or(rest.len()); + rest = rest[end..].trim_start(); + } + } +} + +/// The printer writes a name with a `$` as an exotic identifier, `\"a$"`. +fn unescape_generated_names(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + let mut rest = text; + while let Some(at) = rest.find("\\\"") { + out.push_str(&rest[..at]); + let after = &rest[at + 2..]; + match after.find('"') { + Some(end) + if after[..end].contains('$') + && after[..end] + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$' || c == '\'') => + { + out.push_str(&after[..end]); + rest = &after[end + 1..]; + } + _ => { + out.push_str("\\\""); + rest = after; + } + } + } + out.push_str(rest); + out } /// Forget a compiled module, so that modules compiled later cannot see it. @@ -161,7 +301,7 @@ fn parse_tree_sexp(source: &str, filename: &str) -> Option { /// of `@rescript/runtime` itself. Returns JSON with the JavaScript, the /// macro-expanded source when the file uses macros, the warnings and the /// intermediate representations: -/// `{ type: "success", js, expanded, warnings, parse_tree, typed_tree, raw_lambda, lambda }` +/// `{ type: "success", js, expanded, expanded_raw, formatted, warnings, parse_tree, typed_tree, raw_lambda, lambda }` /// or `{ type: "error", message, parse_tree }`. #[wasm_bindgen] pub fn compile_file(source: &str, filename: &str, is_runtime: bool) -> String { @@ -179,6 +319,7 @@ pub fn compile_file(source: &str, filename: &str, is_runtime: bool) -> String { source_filename: Some(filename.to_string()), module_name: Some(module_name.clone()), capture_intermediates: true, + capture_loaded_modules: true, output_module_format: Some(ModuleFormat::EsModule), macro_host: Some(host), ..Default::default() @@ -195,7 +336,8 @@ pub fn compile_file(source: &str, filename: &str, is_runtime: bool) -> String { ); match result { - Ok(compiled) => { + Ok(mut compiled) => { + keep_runtime_modules(std::mem::take(&mut compiled.loaded_modules)); if let Some(pers_struct) = compiled.pers_struct { REGISTRY.with(|r| { r.borrow_mut().register_module( @@ -213,7 +355,17 @@ pub fn compile_file(source: &str, filename: &str, is_runtime: bool) -> String { serde_json::json!({ "type": "success", "js": from_compiler_text(&compiled.js_output), - "expanded": compiled.expanded_source.as_deref().map(from_compiler_text), + "expanded": compiled + .expanded_source + .as_deref() + .map(|expanded| from_compiler_text(&readable_expansion(expanded, filename))), + "expanded_raw": compiled.expanded_source.as_deref().map(from_compiler_text), + // The file as written, printed the same way: the lines of + // `expanded` that are not in it were generated. + "formatted": compiled + .expanded_source + .is_some() + .then(|| from_compiler_text(&readable_expansion(&source, filename))), "warnings": from_compiler_text(&compiled.warnings), "parse_tree": parse_tree, "typed_tree": compiled.typed_tree_sexp, diff --git a/playground/implementation.html b/playground/implementation.html new file mode 100644 index 0000000000..6b08cad940 --- /dev/null +++ b/playground/implementation.html @@ -0,0 +1,30 @@ + + + + + + + + + + Macros: the compiler side · ReScript RFC + + + + +
+ + + diff --git a/playground/index.html b/playground/index.html index 811570001e..f2220b54db 100644 --- a/playground/index.html +++ b/playground/index.html @@ -1,13 +1,30 @@ - + - - ReScript macros playground - + + + + + + Compile-time macros for ReScript · RFC + +
- + diff --git a/playground/package-lock.json b/playground/package-lock.json index 2a9491ffa4..e567d4067b 100644 --- a/playground/package-lock.json +++ b/playground/package-lock.json @@ -9,7 +9,17 @@ "version": "0.1.0", "dependencies": { "@base-ui/react": "^1.0.0", + "@codemirror/autocomplete": "^6.20.4", + "@codemirror/commands": "^6.11.1", + "@codemirror/lang-javascript": "^6.2.5", + "@codemirror/lang-json": "^6.0.2", + "@codemirror/language": "^6.13.1", + "@codemirror/state": "^6.7.6", + "@codemirror/view": "^6.43.15", + "@lezer/highlight": "^1.2.5", "@monaco-editor/react": "^4.7.0", + "codemirror": "^6.0.2", + "marked": "^18.2.0", "monaco-editor": "^0.52.0", "react": "^19.0.0", "react-dom": "^19.0.0" @@ -365,6 +375,119 @@ } } }, + "node_modules/@codemirror/autocomplete": { + "version": "6.20.4", + "resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.20.4.tgz", + "integrity": "sha512-yF8RhOf2SXlg00+qtupzLhrglcas61boqaONiNcbPIebHCpJocpqTBA6dyrtUrQO47hqyTdeob/3XnYilT7TaQ==", + "license": "MIT", + "dependencies": { + "@codemirror/language": "^6.0.0", + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.17.0", + "@lezer/common": "^1.0.0" + } + }, + "node_modules/@codemirror/commands": { + "version": "6.11.1", + "resolved": "https://registry.npmjs.org/@codemirror/commands/-/commands-6.11.1.tgz", + "integrity": "sha512-O/4hG3SC1YwcmQ0d2UVNDs+AsaNWd1iHVxbTeEBuqH+6bExAiPK3iS/BvpY6rZGURALv4ZD3sIgcCmRvw3ehBg==", + "license": "MIT", + "dependencies": { + "@codemirror/language": "^6.0.0", + "@codemirror/state": "^6.7.0", + "@codemirror/view": "^6.27.0", + "@lezer/common": "^1.1.0" + } + }, + "node_modules/@codemirror/lang-javascript": { + "version": "6.2.5", + "resolved": "https://registry.npmjs.org/@codemirror/lang-javascript/-/lang-javascript-6.2.5.tgz", + "integrity": "sha512-zD4e5mS+50htS7F+TYjBPsiIFGanfVqg4HyUz6WNFikgOPf2BgKlx+TQedI1w6n/IqRBVBbBWmGFdLB/7uxO4A==", + "license": "MIT", + "dependencies": { + "@codemirror/autocomplete": "^6.0.0", + "@codemirror/language": "^6.6.0", + "@codemirror/lint": "^6.0.0", + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.17.0", + "@lezer/common": "^1.0.0", + "@lezer/javascript": "^1.0.0" + } + }, + "node_modules/@codemirror/lang-json": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/@codemirror/lang-json/-/lang-json-6.0.2.tgz", + "integrity": "sha512-x2OtO+AvwEHrEwR0FyyPtfDUiloG3rnVTSZV1W8UteaLL8/MajQd8DpvUb2YVzC+/T18aSDv0H9mu+xw0EStoQ==", + "license": "MIT", + "dependencies": { + "@codemirror/language": "^6.0.0", + "@lezer/json": "^1.0.0" + } + }, + "node_modules/@codemirror/language": { + "version": "6.13.1", + "resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.13.1.tgz", + "integrity": "sha512-zfvU2r3TyylQLMj/te+5CnQ0rSqZi8B1oTCBbQkagcLW4Xc6imab6qN+pEJhsuNOLaJqiRyBXp9UhWA1DhVvDw==", + "license": "MIT", + "dependencies": { + "@codemirror/state": "^6.0.0", + "@codemirror/streamparser": "^6.0.0", + "@codemirror/view": "^6.23.0", + "@lezer/common": "^1.5.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.0.0", + "style-mod": "^4.0.0" + } + }, + "node_modules/@codemirror/lint": { + "version": "6.9.7", + "resolved": "https://registry.npmjs.org/@codemirror/lint/-/lint-6.9.7.tgz", + "integrity": "sha512-28/+iWLYxKxsvGYhSYL7zaCZqLz5+FFFDq9tVsvGv9kv8RY4fFAchJ5WX9M3YrrRlTIsECjsXPqeNgnSmNP2dg==", + "license": "MIT", + "dependencies": { + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.42.0", + "crelt": "^1.0.5" + } + }, + "node_modules/@codemirror/search": { + "version": "6.7.2", + "resolved": "https://registry.npmjs.org/@codemirror/search/-/search-6.7.2.tgz", + "integrity": "sha512-gUYkYhT2+n/+VGZ+8EzE5WFkYZUZYm1VOKDudIsNqh42uRVQJ0a6Yss9sdKT3MeOYfuL1N6AZA57oza0Oyr0LA==", + "license": "MIT", + "dependencies": { + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.37.0", + "crelt": "^1.0.5" + } + }, + "node_modules/@codemirror/state": { + "version": "6.7.6", + "resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.7.6.tgz", + "integrity": "sha512-kAz+AncRtKuIknedxT1bq4XwXv4UowhbkHU1myPrtVb/jZtImWuV5BXzv5vK6i3kYACsdiZiQKFQQ5Mq7elW8w==", + "license": "MIT", + "dependencies": { + "@marijn/find-cluster-break": "^1.0.0" + } + }, + "node_modules/@codemirror/streamparser": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/@codemirror/streamparser/-/streamparser-6.0.0.tgz", + "integrity": "sha512-JTFPF6xrfjt0mnfGPgzcLiMwYmvIyNaoizp8BYzv8FE8KrT6GBGDZ190rtt+O7Wke3gG/MFHyiY9YGNeimof4w==", + "license": "MIT" + }, + "node_modules/@codemirror/view": { + "version": "6.43.15", + "resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.43.15.tgz", + "integrity": "sha512-HHsfpqFeHyXLs983pSRe38Xajs0vFWZQ2BuX0m7Ki8w3jZ5iD8cuR3lBz2/5/X53Dhf32SBHKh6rtSTB6tKeGw==", + "license": "MIT", + "dependencies": { + "@codemirror/state": "^6.7.0", + "crelt": "^1.0.6", + "style-mod": "^4.1.0", + "w3c-keyname": "^2.2.4" + } + }, "node_modules/@date-fns/tz": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/@date-fns/tz/-/tz-1.4.1.tgz", @@ -902,6 +1025,58 @@ "@jridgewell/sourcemap-codec": "^1.4.14" } }, + "node_modules/@lezer/common": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.5.5.tgz", + "integrity": "sha512-Pw7PVCndruF1pb3ebCxpSVpkMHSDjwRCLcTRw+RizUKco5QbWylwq2g4lnG/RYN7yTTQDXE9F77MwtkAyphrjg==", + "license": "MIT" + }, + "node_modules/@lezer/highlight": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.5.tgz", + "integrity": "sha512-O1GMVKgtf5YspFaRzpmqkVgMtIk2HG9uMAbH6wdAIdNh3TVzCsch/+cRi+6l2//UGDKe6NB9BW3cvuR5ezMQ0w==", + "license": "MIT", + "dependencies": { + "@lezer/common": "^1.3.0" + } + }, + "node_modules/@lezer/javascript": { + "version": "1.5.6", + "resolved": "https://registry.npmjs.org/@lezer/javascript/-/javascript-1.5.6.tgz", + "integrity": "sha512-sEvOqpl4vJQca0NugSQK02vQPbc5KrvoojnYGoqqFgFO0MtcYhwGiHKVEB+LuXYJnfyXo4QPA8ztbrEa4Fw5NA==", + "license": "MIT", + "dependencies": { + "@lezer/common": "^1.2.0", + "@lezer/highlight": "^1.1.3", + "@lezer/lr": "^1.3.0" + } + }, + "node_modules/@lezer/json": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@lezer/json/-/json-1.0.3.tgz", + "integrity": "sha512-BP9KzdF9Y35PDpv04r0VeSTKDeox5vVr3efE7eBbx3r4s3oNLfunchejZhjArmeieBH+nVOpgIiBJpEAv8ilqQ==", + "license": "MIT", + "dependencies": { + "@lezer/common": "^1.2.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.0.0" + } + }, + "node_modules/@lezer/lr": { + "version": "1.4.12", + "resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.4.12.tgz", + "integrity": "sha512-On9HU4oMMiHPMkQDgoTnGahjgG5n/MkN38CgG77sMraKLL+3JBbeQNi1FcCXV9QRqwF9/BUXP3caHyJC1fBOTQ==", + "license": "MIT", + "dependencies": { + "@lezer/common": "^1.0.0" + } + }, + "node_modules/@marijn/find-cluster-break": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@marijn/find-cluster-break/-/find-cluster-break-1.0.4.tgz", + "integrity": "sha512-Wy0V7+SGUjnF9/TkiM1hKVDPj7jKXduPNboMVtHTA8dySMURWqfg/JZ9E2Sq8JgSJmkl7k7Qe9FLeMSrSraWmQ==", + "license": "MIT" + }, "node_modules/@monaco-editor/loader": { "version": "1.7.0", "resolved": "https://registry.npmjs.org/@monaco-editor/loader/-/loader-1.7.0.tgz", @@ -1423,6 +1598,21 @@ ], "license": "CC-BY-4.0" }, + "node_modules/codemirror": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/codemirror/-/codemirror-6.0.2.tgz", + "integrity": "sha512-VhydHotNW5w1UGK0Qj96BwSk/Zqbp9WbnyK2W/eVMv4QyF41INRGpjUhFJY7/uDNuudSc33a/PKr4iDqRduvHw==", + "license": "MIT", + "dependencies": { + "@codemirror/autocomplete": "^6.0.0", + "@codemirror/commands": "^6.0.0", + "@codemirror/language": "^6.0.0", + "@codemirror/lint": "^6.0.0", + "@codemirror/search": "^6.0.0", + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.0.0" + } + }, "node_modules/convert-source-map": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", @@ -1430,6 +1620,12 @@ "dev": true, "license": "MIT" }, + "node_modules/crelt": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.7.tgz", + "integrity": "sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA==", + "license": "MIT" + }, "node_modules/date-fns": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/date-fns/-/date-fns-4.1.0.tgz", @@ -1604,6 +1800,18 @@ "yallist": "^3.0.2" } }, + "node_modules/marked": { + "version": "18.2.0", + "resolved": "https://registry.npmjs.org/marked/-/marked-18.2.0.tgz", + "integrity": "sha512-KaeL+tAbtvI930q7HE2PN5lYXYdT8EiSmxHlN6F3rsfb57wd5mp5W5TLazpdj4inTQBJdgjYwbs40W/0VUGU+Q==", + "license": "MIT", + "bin": { + "marked": "bin/marked.js" + }, + "engines": { + "node": ">= 20" + } + }, "node_modules/monaco-editor": { "version": "0.52.2", "resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.52.2.tgz", @@ -1806,6 +2014,12 @@ "integrity": "sha512-HTEHMNieakEnoe33shBYcZ7NX83ACUjCu8c40iOGEZsngj9zRnkqS9j1pqQPXwobB0ZcVTk27REb7COQ0UR59w==", "license": "MIT" }, + "node_modules/style-mod": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/style-mod/-/style-mod-4.1.4.tgz", + "integrity": "sha512-XXWIQt633/EpAFx8aZDOTjBzrCaGmhvEQlQo6MVPfa2OzO2cWo+4hV9h+6UkHYlXGfy+ODXKUdP7Pthmcu5ATw==", + "license": "MIT" + }, "node_modules/tinyglobby": { "version": "0.2.16", "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.16.tgz", @@ -1948,6 +2162,12 @@ "vite": "^2 || ^3 || ^4 || ^5 || ^6 || ^7 || ^8" } }, + "node_modules/w3c-keyname": { + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz", + "integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==", + "license": "MIT" + }, "node_modules/yallist": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", diff --git a/playground/package.json b/playground/package.json index 296a2aa3e8..4e6df0c0c4 100644 --- a/playground/package.json +++ b/playground/package.json @@ -4,12 +4,13 @@ "version": "0.1.0", "type": "module", "scripts": { - "dev": "node scripts/bundle-stdlib.js && vite", - "build": "node scripts/bundle-stdlib.js && vite build", + "dev": "npm run prebuild:examples && vite", + "build": "npm run prebuild:examples && vite build", "bundle:stdlib": "node scripts/bundle-stdlib.js", "build:wasm": "cd crate && wasm-pack build --target web --release", "smoke": "node scripts/bundle-stdlib.js && node scripts/smoke.mjs", - "preview": "vite preview" + "preview": "vite preview", + "prebuild:examples": "node scripts/bundle-stdlib.js && node scripts/prebuild-examples.mjs" }, "devDependencies": { "@vitejs/plugin-react": "^4.3.0", @@ -18,7 +19,17 @@ }, "dependencies": { "@base-ui/react": "^1.0.0", + "@codemirror/autocomplete": "^6.20.4", + "@codemirror/commands": "^6.11.1", + "@codemirror/lang-javascript": "^6.2.5", + "@codemirror/lang-json": "^6.0.2", + "@codemirror/language": "^6.13.1", + "@codemirror/state": "^6.7.6", + "@codemirror/view": "^6.43.15", + "@lezer/highlight": "^1.2.5", "@monaco-editor/react": "^4.7.0", + "codemirror": "^6.0.2", + "marked": "^18.2.0", "monaco-editor": "^0.52.0", "react": "^19.0.0", "react-dom": "^19.0.0" diff --git a/playground/playground.html b/playground/playground.html new file mode 100644 index 0000000000..303d0f98a1 --- /dev/null +++ b/playground/playground.html @@ -0,0 +1,13 @@ + + + + + + Playground · ReScript compile-time macros + + + +
+ + + diff --git a/playground/scripts/prebuild-examples.mjs b/playground/scripts/prebuild-examples.mjs new file mode 100644 index 0000000000..2e78c568eb --- /dev/null +++ b/playground/scripts/prebuild-examples.mjs @@ -0,0 +1,47 @@ +#!/usr/bin/env node +/** + * Builds every example with the wasm compiler and writes what the RFC page + * shows before the compiler has loaded in the browser: per file the expanded + * source and the JavaScript, and the program's output. + */ +import { readFile, writeFile } from "fs/promises"; +import { join } from "path"; +import * as wasm from "../crate/pkg/rescript_playground_wasm.js"; +import { createEngine } from "../src/engine.js"; + +const root = join(import.meta.dirname, ".."); +wasm.initSync({ module: await readFile(join(root, "crate/pkg/rescript_playground_wasm_bg.wasm")) }); +const stdlib = JSON.parse(await readFile(join(root, "public/stdlib.json"), "utf-8")); +const engine = createEngine(wasm, stdlib); + +const prebuilt = {}; +for (const example of JSON.parse(await readFile(join(root, "examples/index.json"), "utf-8"))) { + const files = []; + for (const name of example.files) { + files.push({ name, source: await readFile(join(root, "examples", example.id, name), "utf-8") }); + } + const { order, results, logs } = engine.build(files); + const failed = order.find((name) => results[name]?.type !== "success"); + if (failed || logs === null) { + console.error(`${example.id}: ${failed} does not compile\n${results[failed]?.message}`); + process.exit(1); + } + prebuilt[example.id] = { + order, + logs, + results: Object.fromEntries( + order.map((name) => [ + name, + { + type: "success", + js: results[name].js, + expanded: results[name].expanded ?? null, + formatted: results[name].formatted ?? null, + warnings: "", + }, + ]), + ), + }; +} +await writeFile(join(root, "src/rfc/prebuilt.json"), JSON.stringify(prebuilt)); +console.log(`Prebuilt ${Object.keys(prebuilt).length} examples -> src/rfc/prebuilt.json`); diff --git a/playground/src/App.jsx b/playground/src/App.jsx index edc5fceee5..906c76cc27 100644 --- a/playground/src/App.jsx +++ b/playground/src/App.jsx @@ -286,6 +286,9 @@ export default function App() {
+ + ← RFC +

ReScript macros

Rust Compiler setFocus(event.target.value)}> + {sources.map((file) => ( + + ))} + + + )} +
+ {isInternal(view) && ( +
+ {INTERNALS.map(([key, label]) => ( + + ))} +
+ )} +
+ { + if (active !== focusFile.name) setActive(focusFile.name); + else selectRange(editorView.current, loc); + }} + /> +
+ 0} warnings={warnings} /> + +
+
+ 0 ? "pulse failed" : live ? "pulse live" : "pulse"} /> + {note} +
+ + ); +} + +function ResultView({ view, file, result, problems, busy, cursor, onNodeClick }) { + if (problems.length > 0) { + return ( +
+ {problems.map((problem, index) => ( +
+            {problem.message}
+          
+ ))} +
+ ); + } + if (!result) return
{busy ? "Compiling…" : "Nothing compiled yet."}
; + if (result.type !== "success") return
{result.message}
; + if (view === "expanded") { + if (!result.expanded) { + return ( + <> +
This file uses no macro: it is compiled as written.
+ + + ); + } + return ; + } + if (view === "js") return ; + const sexp = result[view]; + if (!sexp) return
{busy ? "Compiling…" : "Loading the compiler…"}
; + return ; +} + +/** The file after expansion, with the lines the macros wrote set apart. */ +function Expanded({ result }) { + const marked = useMemo( + () => (result.formatted ? addedLines(result.formatted, result.expanded) : null), + [result.formatted, result.expanded], + ); + const first = useRef(null); + // Bring the first generated line into view: it is what the example is about. + useEffect(() => { + const scroller = first.current?.closest(".pane-scroll"); + const line = first.current?.querySelector(".line.marked"); + if (!scroller || !line) return; + const offset = line.getBoundingClientRect().top - scroller.getBoundingClientRect().top + scroller.scrollTop; + scroller.scrollTop = Math.max(0, offset - 72); + }, [marked]); + return ( +
+ {marked && marked.size > 0 && ( +
+ + written by macros +
+ )} + +
+ ); +} + +function Output({ logs, failed, warnings }) { + return ( +
+
Output
+ {failed || logs === null ? ( +
The program runs when every file compiles.
+ ) : logs.length === 0 ? ( +
The program printed nothing.
+ ) : ( + logs.map((log, index) => ( +
+            {log.text}
+          
+ )) + )} + {warnings.map((warning, index) => ( +
+          {warning}
+        
+ ))} +
+ ); +} diff --git a/playground/src/rfc/Markdown.jsx b/playground/src/rfc/Markdown.jsx new file mode 100644 index 0000000000..5e5f31d324 --- /dev/null +++ b/playground/src/rfc/Markdown.jsx @@ -0,0 +1,178 @@ +/** Renders the RFC's Markdown as React elements. */ +import React from "react"; +import { marked } from "marked"; +import { Code } from "./highlight.jsx"; +import { FlowDiagram, SequenceDiagram } from "./Diagrams.jsx"; + +export function slug(text) { + return text + .toLowerCase() + .replace(/[^\w\s-]/g, "") + .trim() + .replace(/\s+/g, "-"); +} + +function plain(tokens) { + return (tokens ?? []) + .map((token) => (token.tokens ? plain(token.tokens) : token.text ?? token.raw ?? "")) + .join(""); +} + +function decode(text) { + return text + .replace(/&/g, "&") + .replace(/</g, "<") + .replace(/>/g, ">") + .replace(/"/g, '"') + .replace(/'/g, "'"); +} + +function inline(tokens, links) { + return (tokens ?? []).map((token, index) => { + switch (token.type) { + case "strong": + return {inline(token.tokens, links)}; + case "em": + return {inline(token.tokens, links)}; + case "codespan": + return {decode(token.text)}; + case "br": + return
; + case "del": + return {inline(token.tokens, links)}; + case "link": { + const href = links(token.href); + const external = /^https?:/.test(href); + return ( + + {inline(token.tokens, links)} + + ); + } + case "html": + return null; + default: + return token.tokens ? ( + {inline(token.tokens, links)} + ) : ( + decode(token.text ?? token.raw) + ); + } + }); +} + +function block(token, index, links) { + switch (token.type) { + case "heading": { + const Tag = `h${token.depth}`; + const id = slug(plain(token.tokens)); + return ( + + + {inline(token.tokens, links)} + + ); + } + case "paragraph": + return

{inline(token.tokens, links)}

; + case "code": { + if (token.lang === "mermaid") { + return token.text.trimStart().startsWith("sequenceDiagram") ? ( + + ) : ( + + ); + } + return ; + } + case "list": { + const Tag = token.ordered ? "ol" : "ul"; + return ( + + {token.items.map((item, itemIndex) => ( +
  • + {item.tokens.map((child, childIndex) => + child.type === "text" ? ( + {inline(child.tokens ?? [child], links)} + ) : ( + block(child, childIndex, links) + ), + )} +
  • + ))} +
    + ); + } + case "table": + return ( +
    + + + + {token.header.map((cell, cellIndex) => ( + + ))} + + + + {token.rows.map((row, rowIndex) => ( + + {row.map((cell, cellIndex) => ( + + ))} + + ))} + +
    {inline(cell.tokens, links)}
    {inline(cell.tokens, links)}
    +
    + ); + case "blockquote": + return
    {token.tokens.map((child, childIndex) => block(child, childIndex, links))}
    ; + case "hr": + return
    ; + default: + return null; + } +} + +/** + * Split the document at its markers. `` up to + * `` is replaced by the live example (the static code in + * between is what other renderers show); `` up to + * `` is replaced by a chart of the table in between. + */ +export function segments(markdown) { + const out = []; + const marker = /[\s\S]*?|[\s\S]*?/g; + let position = 0; + for (const match of markdown.matchAll(marker)) { + if (match.index > position) out.push({ type: "markdown", text: markdown.slice(position, match.index) }); + out.push(match[1] ? { type: "example", id: match[1] } : { type: "chart", id: match[2] }); + position = match.index + match[0].length; + } + if (position < markdown.length) out.push({ type: "markdown", text: markdown.slice(position) }); + return out; +} + +export function lex(text) { + return marked.lexer(text); +} + +/** The second and third level headings, each with the section it is in. */ +export function headings(markdown) { + let section = null; + return lex(markdown.replace(//g, "")) + .filter((token) => token.type === "heading" && (token.depth === 2 || token.depth === 3)) + .map((token) => { + const text = plain(token.tokens); + const id = slug(text); + if (token.depth === 2) section = id; + return { depth: token.depth, text, id, section }; + }); +} + +export function Markdown({ tokens, links = (href) => href }) { + return <>{tokens.map((token, index) => block(token, index, links))}; +} diff --git a/playground/src/rfc/Page.jsx b/playground/src/rfc/Page.jsx new file mode 100644 index 0000000000..3175bb89d8 --- /dev/null +++ b/playground/src/rfc/Page.jsx @@ -0,0 +1,158 @@ +import React, { useEffect, useMemo, useState } from "react"; +import { examples } from "../examples.js"; +import prebuilt from "./prebuilt.json"; +import { Example } from "./Example.jsx"; +import { CostChart } from "./Diagrams.jsx"; +import { headings, lex, Markdown, segments } from "./Markdown.jsx"; +import { warmUp } from "./compiler.js"; + +const REPOSITORY = "https://github.com/jfrolich/rescript-rust"; + +function useTheme() { + const [theme, setTheme] = useState(() => localStorage.getItem("theme") ?? "auto"); + useEffect(() => { + if (theme === "auto") delete document.documentElement.dataset.theme; + else document.documentElement.dataset.theme = theme; + localStorage.setItem("theme", theme); + }, [theme]); + const dark = + theme === "dark" || (theme === "auto" && window.matchMedia("(prefers-color-scheme: dark)").matches); + return [dark, () => setTheme(dark ? "light" : "dark")]; +} + +/** The heading the reader is under, for the table of contents. */ +function useActiveHeading(ids) { + const [active, setActive] = useState(ids[0]); + useEffect(() => { + const update = () => { + let current = ids[0]; + for (const id of ids) { + const element = document.getElementById(id); + if (element && element.getBoundingClientRect().top < 120) current = id; + } + setActive(current); + }; + update(); + window.addEventListener("scroll", update, { passive: true }); + return () => window.removeEventListener("scroll", update); + }, [ids]); + return active; +} + +/** + * One document of the RFC. `pages` maps the file name of a sibling + * document to its page. + */ +export function Page({ markdown, title, lede, pages, current }) { + const [dark, toggleTheme] = useTheme(); + const parts = useMemo(() => { + // The page has its own title and table of contents. + const body = markdown.replace(/^# .*\n/, "").replace(/\n(- \[[^\]]+\]\(#[^)]+\)\n)+/, "\n"); + return segments(body).map((segment) => + segment.type === "markdown" ? { ...segment, tokens: lex(segment.text) } : segment, + ); + }, [markdown]); + const toc = useMemo(() => headings(markdown), [markdown]); + const ids = useMemo(() => toc.map((entry) => entry.id), [toc]); + const active = useActiveHeading(ids); + const activeSection = toc.find((entry) => entry.id === active)?.section; + + // Load the compiler once the page has settled, so the first edit is quick. + useEffect(() => { + if (!parts.some((part) => part.type === "example")) return undefined; + const timer = setTimeout(warmUp, 2500); + return () => clearTimeout(timer); + }, [parts]); + + const links = (href) => { + if (pages[href]) return pages[href]; + if (!href.startsWith("#") && !/^[a-z]+:/.test(href)) return `${REPOSITORY}/blob/comptime-macros/docs/comptime/${href}`; + return href; + }; + + return ( + <> +
    + + + Submodule + + +
    + +
    +

    + + ReScript · request for comments +

    +

    {title}

    +

    {lede}

    +
    + Draft + Implemented on a branch + + Pull request #90 ↗ + + + Open the playground → + +
    +
    + +
    + +
    + {parts.map((part, index) => { + if (part.type === "markdown") return ; + if (part.type === "chart") return ; + const example = examples.find((candidate) => candidate.id === part.id); + if (!example) return null; + return ; + })} + +
    +
    + + ); +} diff --git a/playground/src/rfc/compiler.js b/playground/src/rfc/compiler.js new file mode 100644 index 0000000000..b8163ef46f --- /dev/null +++ b/playground/src/rfc/compiler.js @@ -0,0 +1,106 @@ +/** + * One compiler worker for the whole page. Every example asks it to build + * its project; requests run one at a time, and a newer request of the same + * example replaces one that has not started. The worker (and the 10 MB of + * WebAssembly behind it) is created on first use. + */ + +const TIME_LIMIT = 20_000; + +let worker = null; +let ready = false; +let running = null; // {id, key, resolve, reject, timer} +const waiting = new Map(); // key -> {files, resolve, reject} +let nextId = 1; +const listeners = new Set(); +let status = "idle"; // idle | loading | ready | failed + +function setStatus(next) { + status = next; + for (const listener of listeners) listener(status); +} + +export function compilerStatus() { + return status; +} + +export function onCompilerStatus(listener) { + listeners.add(listener); + return () => listeners.delete(listener); +} + +function start() { + ready = false; + setStatus("loading"); + worker = new Worker(new URL("../compiler-worker.js", import.meta.url), { type: "module" }); + worker.onmessage = (event) => { + const message = event.data; + if (message.type === "ready") { + ready = true; + setStatus("ready"); + next(); + } else if (message.type === "built") { + if (!running || running.id !== message.id) return; + const done = running; + clearTimeout(done.timer); + running = null; + if (message.result.crashed) { + restart(); + done.reject(new Error(message.result.crashed)); + } else { + done.resolve({ result: message.result, ms: message.ms }); + } + next(); + } else if (message.type === "failed") { + fail(`The compiler failed: ${message.message}`); + } + }; + worker.onerror = (event) => fail(`The compiler failed: ${event.message || "it could not be loaded"}`); + worker.postMessage({ type: "init", stdlibUrl: new URL("stdlib.json", document.baseURI).href }); +} + +function fail(message) { + const done = running; + running = null; + if (done) { + clearTimeout(done.timer); + done.reject(new Error(message)); + } + restart(); +} + +function restart() { + if (worker) worker.terminate(); + start(); +} + +function next() { + if (!ready || running || waiting.size === 0) return; + const [key, request] = waiting.entries().next().value; + waiting.delete(key); + const id = nextId++; + const timer = setTimeout(() => { + fail(`The build was stopped after ${TIME_LIMIT / 1000} seconds. A macro or the program probably does not terminate.`); + }, TIME_LIMIT); + running = { id, key, timer, resolve: request.resolve, reject: request.reject }; + worker.postMessage({ type: "build", id, files: request.files }); +} + +/** Start loading the compiler, if it is not loaded or loading. */ +export function warmUp() { + if (!worker) start(); +} + +/** + * Build `files` for the example `key`. Resolves with `{result, ms}`, or with + * `null` when a newer request of the same example replaced this one. + */ +export function build(key, files) { + warmUp(); + return new Promise((resolve, reject) => { + const replaced = waiting.get(key); + if (replaced) replaced.resolve(null); + waiting.set(key, { files, resolve, reject }); + next(); + }); +} diff --git a/playground/src/rfc/highlight.jsx b/playground/src/rfc/highlight.jsx new file mode 100644 index 0000000000..1d0f5011de --- /dev/null +++ b/playground/src/rfc/highlight.jsx @@ -0,0 +1,124 @@ +/** Static syntax highlighting with the editor's languages. */ +import React from "react"; +import { highlightTree, classHighlighter } from "@lezer/highlight"; +import { javascriptLanguage } from "@codemirror/lang-javascript"; +import { jsonLanguage } from "@codemirror/lang-json"; +import { rescript } from "./rescript-mode.js"; + +const languages = { + rescript, + res: rescript, + js: javascriptLanguage, + javascript: javascriptLanguage, + json: jsonLanguage, +}; + +export function languageOf(filename) { + if (filename.endsWith(".res") || filename.endsWith(".resi")) return "rescript"; + if (filename.endsWith(".json")) return "json"; + if (filename.endsWith(".js") || filename.endsWith(".mjs")) return "javascript"; + return "text"; +} + +export function codemirrorLanguage(name) { + return languages[name] ?? null; +} + +/** `code` as an array of React nodes, with a class on each token. */ +export function highlight(code, languageName) { + const language = languages[languageName]; + if (!language) return [code]; + const nodes = []; + let position = 0; + highlightTree(language.parser.parse(code), classHighlighter, (from, to, classes) => { + if (from > position) nodes.push(code.slice(position, from)); + nodes.push( + + {code.slice(from, to)} + , + ); + position = to; + }); + if (position < code.length) nodes.push(code.slice(position)); + return nodes; +} + +/** The highlighted nodes, split into lines. */ +function lines(nodes) { + const out = [[]]; + nodes.forEach((node, index) => { + const text = typeof node === "string" ? node : node.props.children; + const parts = text.split("\n"); + parts.forEach((part, partIndex) => { + if (partIndex > 0) out.push([]); + if (part === "") return; + out[out.length - 1].push( + typeof node === "string" ? ( + part + ) : ( + + {part} + + ), + ); + }); + }); + if (out.length > 1 && out[out.length - 1].length === 0) out.pop(); + return out; +} + +/** + * The lines of `after` that are not lines of `before`, by a longest common + * subsequence of the two, as a set of line numbers counted from zero. + */ +export function addedLines(before, after) { + const a = before.split("\n").map((line) => line.trim()); + const b = after.split("\n").map((line) => line.trim()); + const width = b.length + 1; + const table = new Uint16Array((a.length + 1) * width); + for (let i = a.length - 1; i >= 0; i--) { + for (let j = b.length - 1; j >= 0; j--) { + table[i * width + j] = + a[i] === b[j] ? table[(i + 1) * width + j + 1] + 1 : Math.max(table[(i + 1) * width + j], table[i * width + j + 1]); + } + } + const added = new Set(); + let i = 0; + let j = 0; + while (j < b.length) { + if (i < a.length && a[i] === b[j]) { + i++; + j++; + } else if (i < a.length && table[(i + 1) * width + j] >= table[i * width + j + 1]) { + i++; + } else { + if (b[j] !== "") added.add(j); + j++; + } + } + return added; +} + +/** `marked` is a set of line numbers to set apart, counted from zero. */ +export function Code({ code, language, className = "", marked = null }) { + const nodes = React.useMemo(() => highlight(code, language), [code, language]); + if (!marked || marked.size === 0) { + return ( +
    +        {nodes}
    +      
    + ); + } + return ( +
    +      
    +        {lines(nodes).map((line, index) => (
    +          
    +            {line}
    +            {"\n"}
    +          
    +        ))}
    +      
    +    
    + ); +} diff --git a/playground/src/rfc/implementation.jsx b/playground/src/rfc/implementation.jsx new file mode 100644 index 0000000000..2437059481 --- /dev/null +++ b/playground/src/rfc/implementation.jsx @@ -0,0 +1,19 @@ +import React from "react"; +import { createRoot } from "react-dom/client"; +import markdown from "../../../docs/comptime/IMPLEMENTATION.md?raw"; +import { Page } from "./Page.jsx"; +import "./rfc.css"; + +createRoot(document.getElementById("root")).render( + + Macros: the compiler side + + } + lede="How the design of the RFC is implemented in the Rust compiler: parsing, the expansion passes, the type checker's hooks and the JavaScript engine." + pages={{ "IMPLEMENTATION.md": "implementation.html", "README.md": "./" }} + />, +); diff --git a/playground/src/rfc/main.jsx b/playground/src/rfc/main.jsx new file mode 100644 index 0000000000..b66e8dcdb8 --- /dev/null +++ b/playground/src/rfc/main.jsx @@ -0,0 +1,19 @@ +import React from "react"; +import { createRoot } from "react-dom/client"; +import readme from "../../../docs/comptime/README.md?raw"; +import { Page } from "./Page.jsx"; +import "./rfc.css"; + +createRoot(document.getElementById("root")).render( + + Compile-time macros for ReScript + + } + lede="One mechanism for what PPXs do today, written in ReScript, that can also ask the type checker about types. Every example on this page is live: edit it and see what the compiler makes of it." + pages={{ "IMPLEMENTATION.md": "implementation.html", "README.md": "./" }} + />, +); diff --git a/playground/src/rfc/rescript-mode.js b/playground/src/rfc/rescript-mode.js new file mode 100644 index 0000000000..8f385790c4 --- /dev/null +++ b/playground/src/rfc/rescript-mode.js @@ -0,0 +1,83 @@ +/** ReScript for CodeMirror: a tokenizer, used for editing and for static highlighting. */ +import { StreamLanguage } from "@codemirror/language"; + +const keywords = new Set([ + "and", "as", "assert", "async", "await", "catch", "constraint", "downto", "else", "exception", + "external", "for", "if", "in", "include", "lazy", "let", "module", "mutable", "of", "open", + "private", "rec", "switch", "to", "try", "type", "when", "while", "with", +]); +const atoms = new Set(["true", "false"]); + +function token(stream, state) { + if (state.comment > 0) { + while (!stream.eol()) { + if (stream.match("*/")) { + state.comment -= 1; + if (state.comment === 0) break; + } else if (stream.match("/*")) { + state.comment += 1; + } else { + stream.next(); + } + } + return "comment"; + } + if (state.template) { + while (!stream.eol()) { + const ch = stream.next(); + if (ch === "\\") stream.next(); + else if (ch === "`") { + state.template = false; + break; + } + } + return "string"; + } + if (stream.eatSpace()) return null; + if (stream.match("//")) { + stream.skipToEnd(); + return "comment"; + } + if (stream.match("/*")) { + state.comment = 1; + return "comment"; + } + if (stream.match(/^"(?:[^"\\]|\\.)*"?/)) return "string"; + if (stream.match(/^'(?:[^'\\]|\\.)'/)) return "string"; + if (stream.match("`")) { + state.template = true; + return "string"; + } + if (stream.match(/^\d[\d_]*(?:\.[\d_]*)?(?:[eE][+-]?\d+)?n?/)) return "number"; + // A hole in a quote. + if (stream.match("${")) return "atom"; + // Extensions and attributes: %code, %Json.encode, @macro, @@directive. + if (stream.match(/^%%?[A-Za-z_][\w.]*/)) return "meta"; + if (stream.match(/^@@?[A-Za-z_][\w.]*/)) return "meta"; + if (stream.match(/^~[a-z_]\w*/)) return "propertyName"; + if (stream.match(/^#[A-Za-z_]\w*/)) return "atom"; + if (stream.match(/^'[a-z_]\w*/)) return "typeName"; + if (stream.match(/^[A-Z][\w$]*/)) return "typeName"; + if (stream.match(/^[a-z_][\w$']*/)) { + const word = stream.current(); + if (keywords.has(word)) return "keyword"; + if (atoms.has(word)) return "atom"; + return "variableName"; + } + if (stream.match(/^(?:=>|->|\.\.\.|===|!==|==|!=|<=|>=|&&|\|\||\+\+|\+\.|-\.|\*\.|\/\.|:=|[-+*/=<>|!?:])/)) { + return "operator"; + } + stream.next(); + return "punctuation"; +} + +export const rescript = StreamLanguage.define({ + name: "rescript", + startState: () => ({ comment: 0, template: false }), + token, + languageData: { + commentTokens: { line: "//", block: { open: "/*", close: "*/" } }, + closeBrackets: { brackets: ["(", "[", "{", '"', "`"] }, + indentOnInput: /^\s*[})\]]$/, + }, +}); diff --git a/playground/src/rfc/rfc.css b/playground/src/rfc/rfc.css new file mode 100644 index 0000000000..5160d0d036 --- /dev/null +++ b/playground/src/rfc/rfc.css @@ -0,0 +1,1310 @@ +:root { + --paper: #f4f1e9; + --surface: #fbfaf6; + --sunken: #ece8dc; + --ink: #18201d; + --muted: #656b65; + --line: rgba(24, 32, 29, 0.14); + --line-strong: rgba(24, 32, 29, 0.28); + --green: #153f35; + --lime: #b7e455; + --orange: #d9522c; + --accent: var(--green); + --hole: rgba(183, 228, 85, 0.5); + --generated: rgba(183, 228, 85, 0.26); + --generated-edge: #8fbf2f; + --tok-keyword: #8b2f6b; + --tok-string: #2a6b3f; + --tok-number: #9a5b00; + --tok-type: #1f5c9c; + --tok-meta: #c2410c; + --tok-comment: #8a8f86; + --tok-property: #6b5a1e; + --error: #b3261e; + --warn: #8a6100; + --serif: "Iowan Old Style", Baskerville, "Times New Roman", serif; + --sans: Inter, ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; + --mono: "JetBrains Mono", "SF Mono", ui-monospace, Menlo, Consolas, monospace; + color-scheme: light; +} + +@media (prefers-color-scheme: dark) { + :root:not([data-theme="light"]) { + --paper: #0f1513; + --surface: #161e1b; + --sunken: #0b100e; + --ink: #e9e6dc; + --muted: #98a39c; + --line: rgba(233, 230, 220, 0.13); + --line-strong: rgba(233, 230, 220, 0.3); + --accent: var(--lime); + --orange: #f08a63; + --hole: rgba(183, 228, 85, 0.22); + --generated: rgba(183, 228, 85, 0.11); + --generated-edge: #b7e455; + --tok-keyword: #e39acb; + --tok-string: #9bd3a4; + --tok-number: #e8b563; + --tok-type: #8cbcf0; + --tok-meta: #f59e6c; + --tok-comment: #6f7a73; + --tok-property: #d6c888; + --error: #ff8a80; + --warn: #e8c468; + color-scheme: dark; + } +} + +:root[data-theme="dark"] { + --paper: #0f1513; + --surface: #161e1b; + --sunken: #0b100e; + --ink: #e9e6dc; + --muted: #98a39c; + --line: rgba(233, 230, 220, 0.13); + --line-strong: rgba(233, 230, 220, 0.3); + --accent: var(--lime); + --orange: #f08a63; + --hole: rgba(183, 228, 85, 0.22); + --generated: rgba(183, 228, 85, 0.11); + --generated-edge: #b7e455; + --tok-keyword: #e39acb; + --tok-string: #9bd3a4; + --tok-number: #e8b563; + --tok-type: #8cbcf0; + --tok-meta: #f59e6c; + --tok-comment: #6f7a73; + --tok-property: #d6c888; + --error: #ff8a80; + --warn: #e8c468; + color-scheme: dark; +} + +* { + box-sizing: border-box; +} + +html { + scroll-behavior: smooth; + scroll-padding-top: 84px; +} + +body { + margin: 0; + background: var(--paper); + color: var(--ink); + font-family: var(--sans); + font-size: 17px; + line-height: 1.65; + -webkit-font-smoothing: antialiased; + text-rendering: optimizeLegibility; +} + +a { + color: inherit; +} + +button, +select { + font: inherit; + color: inherit; +} + +/* Top bar */ +.topbar { + position: sticky; + top: 0; + z-index: 20; + height: 60px; + padding: 0 max(24px, calc((100vw - 1320px) / 2 + 24px)); + display: flex; + align-items: center; + justify-content: space-between; + background: color-mix(in srgb, var(--paper) 86%, transparent); + -webkit-backdrop-filter: blur(14px); + backdrop-filter: blur(14px); + border-bottom: 1px solid var(--line); +} + +.brand { + display: inline-flex; + align-items: center; + gap: 10px; + font-weight: 700; + font-size: 18px; + letter-spacing: -0.04em; + text-decoration: none; +} + +.brand svg { + width: 24px; + fill: none; + stroke: currentColor; + stroke-width: 1.65; + stroke-linejoin: round; +} + +.topbar nav { + display: flex; + align-items: center; + gap: 26px; + font-size: 13px; + font-weight: 600; +} + +.topbar nav a { + text-decoration: none; + padding: 4px 0; + border-bottom: 1px solid transparent; +} + +.topbar nav a:hover, +.topbar nav a.on { + border-bottom-color: currentColor; +} + +.theme { + width: 32px; + height: 32px; + border: 1px solid var(--line-strong); + background: transparent; + cursor: pointer; + font-size: 14px; + line-height: 1; +} + +.theme:hover { + background: var(--ink); + color: var(--paper); +} + +/* Hero */ +.hero { + max-width: 1320px; + margin: 0 auto; + padding: 88px 24px 56px; +} + +.eyebrow { + display: flex; + align-items: center; + gap: 10px; + margin: 0 0 22px; + text-transform: uppercase; + letter-spacing: 0.14em; + font-size: 11px; + font-weight: 700; +} + +.eyebrow span { + width: 25px; + height: 1px; + background: currentColor; +} + +.hero h1 { + margin: 0; + max-width: 900px; + font-size: clamp(44px, 6.4vw, 88px); + line-height: 0.95; + letter-spacing: -0.06em; + font-weight: 650; +} + +.hero h1 em { + font-family: var(--serif); + font-weight: 400; + letter-spacing: -0.04em; +} + +.lede { + max-width: 640px; + margin: 30px 0 0; + font-size: 19px; + line-height: 1.6; + color: var(--muted); +} + +.hero-meta { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-top: 30px; +} + +.chip { + padding: 5px 10px; + border: 1px solid var(--line-strong); + font-size: 12px; + font-weight: 600; + text-decoration: none; + white-space: nowrap; +} + +.chip.solid { + background: var(--ink); + color: var(--paper); + border-color: var(--ink); +} + +a.chip:hover { + background: var(--lime); + color: #18201d; + border-color: #18201d; +} + +/* Layout */ +.layout { + max-width: 1320px; + margin: 0 auto; + padding: 0 24px 120px; + display: grid; + grid-template-columns: 200px minmax(0, 1fr); + gap: 56px; +} + +.toc { + position: sticky; + top: 84px; + align-self: start; + max-height: calc(100vh - 110px); + overflow: auto; + padding: 36px 0 0; + display: flex; + flex-direction: column; + gap: 2px; + font-size: 13px; +} + +.toc-title { + text-transform: uppercase; + letter-spacing: 0.14em; + font-size: 10px; + font-weight: 700; + color: var(--muted); + margin-bottom: 10px; +} + +.toc a { + text-decoration: none; + color: var(--muted); + padding: 4px 0 4px 12px; + border-left: 1px solid var(--line); + line-height: 1.35; +} + +.toc a.sub { + padding-left: 24px; + font-size: 12px; +} + +.toc a:hover { + color: var(--ink); +} + +.toc a.on { + color: var(--ink); + border-left-color: var(--ink); + font-weight: 600; +} + +/* Prose */ +.prose { + min-width: 0; + padding-top: 20px; +} + +.prose > p, +.prose > ul, +.prose > ol, +.prose > h3, +.prose > h4, +.prose > blockquote { + max-width: 720px; +} + +.prose h2 { + margin: 88px 0 20px; + padding-top: 28px; + border-top: 1px solid var(--line); + font-family: var(--serif); + font-weight: 400; + font-size: clamp(32px, 3.6vw, 46px); + line-height: 1.08; + letter-spacing: -0.035em; +} + +.prose > h2:first-child { + margin-top: 16px; +} + +.prose h3 { + margin: 56px 0 12px; + font-size: 22px; + line-height: 1.25; + letter-spacing: -0.025em; + font-weight: 650; +} + +.prose h2, +.prose h3 { + position: relative; +} + +.anchor { + position: absolute; + left: -0.9em; + color: var(--muted); + text-decoration: none; + opacity: 0; + font-family: var(--sans); + font-weight: 400; +} + +h2:hover .anchor, +h3:hover .anchor { + opacity: 0.6; +} + +.prose p { + margin: 0 0 18px; +} + +.prose ul, +.prose ol { + margin: 0 0 18px; + padding-left: 22px; +} + +.prose li { + margin-bottom: 8px; +} + +.prose li::marker { + color: var(--muted); +} + +.prose a { + text-decoration-color: var(--line-strong); + text-underline-offset: 3px; +} + +.prose a:hover { + text-decoration-color: currentColor; +} + +.prose strong { + font-weight: 650; +} + +.prose :not(pre) > code { + font-family: var(--mono); + font-size: 0.86em; + padding: 0.12em 0.36em; + background: var(--sunken); + border: 1px solid var(--line); +} + +/* Code */ +.code { + margin: 0; + padding: 16px 18px; + font-family: var(--mono); + font-size: 13px; + line-height: 1.6; + tab-size: 2; + overflow: auto; + white-space: pre; +} + +.code code { + font: inherit; +} + +.code.lined { + padding-left: 0; + padding-right: 0; +} + +.code.lined code { + display: block; + min-width: max-content; +} + +.line { + display: block; + padding: 0 18px 0 15px; + border-left: 3px solid transparent; +} + +.line.marked { + background: var(--generated); + border-left-color: var(--generated-edge); +} + +.legend { + position: sticky; + top: 0; + z-index: 1; + display: flex; + align-items: center; + gap: 7px; + padding: 6px 18px; + font-size: 10px; + font-weight: 700; + letter-spacing: 0.12em; + text-transform: uppercase; + color: var(--muted); + background: color-mix(in srgb, var(--surface) 55%, var(--sunken)); + border-bottom: 1px solid var(--line); +} + +.legend-mark { + width: 10px; + height: 10px; + background: var(--generated); + border-left: 3px solid var(--generated-edge); +} + +.prose > .code { + margin: 0 0 22px; + max-width: 860px; + background: var(--surface); + border: 1px solid var(--line); +} + +.prose > .code.plain { + background: var(--sunken); + color: var(--muted); +} + +.tok-keyword { color: var(--tok-keyword); } +.tok-string, .tok-string2 { color: var(--tok-string); } +.tok-number { color: var(--tok-number); } +.tok-typeName, .tok-className, .tok-namespace { color: var(--tok-type); } +.tok-meta { color: var(--tok-meta); font-weight: 600; } +.tok-comment { color: var(--tok-comment); font-style: italic; } +.tok-propertyName { color: var(--tok-property); } +.tok-atom, .tok-bool { color: var(--tok-number); } +.tok-operator, .tok-punctuation { color: var(--muted); } + +/* Tables */ +.table-wrap { + margin: 0 0 26px; + max-width: 980px; + overflow-x: auto; + border: 1px solid var(--line); + background: var(--surface); +} + +table { + width: 100%; + border-collapse: collapse; + font-size: 14px; + line-height: 1.5; +} + +th { + text-align: left; + font-size: 11px; + text-transform: uppercase; + letter-spacing: 0.1em; + font-weight: 700; + color: var(--muted); + background: var(--sunken); +} + +th, +td { + padding: 11px 14px; + border-bottom: 1px solid var(--line); + vertical-align: top; +} + +tr:last-child td { + border-bottom: 0; +} + +td:first-child { + font-weight: 600; +} + +/* Examples */ +.example { + margin: 30px 0 38px; + border: 1px solid var(--line-strong); + background: var(--surface); + box-shadow: 0 18px 44px -28px rgba(24, 32, 29, 0.35); +} + +.example-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + padding: 12px 16px; + border-bottom: 1px solid var(--line); +} + +.example-title { + display: flex; + align-items: baseline; + flex-wrap: wrap; + gap: 6px 12px; + min-width: 0; + font-size: 14px; + line-height: 1.4; +} + +.example-kicker { + padding: 2px 7px; + background: var(--lime); + color: #18201d; + font-size: 10px; + font-weight: 700; + letter-spacing: 0.12em; + text-transform: uppercase; +} + +.example-summary { + color: var(--muted); + font-size: 13px; +} + +.example-actions { + display: flex; + gap: 8px; + flex-shrink: 0; +} + +.ghost { + padding: 5px 10px; + border: 1px solid var(--line-strong); + background: transparent; + font-size: 12px; + font-weight: 600; + text-decoration: none; + cursor: pointer; + white-space: nowrap; +} + +.ghost:hover { + background: var(--ink); + color: var(--paper); +} + +.example-body { + display: grid; + grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); +} + +.pane { + min-width: 0; + display: flex; + flex-direction: column; +} + +.pane-source { + border-right: 1px solid var(--line); +} + +.pane-result { + background: color-mix(in srgb, var(--surface) 55%, var(--sunken)); +} + +.tabs { + display: flex; + align-items: stretch; + min-height: 38px; + border-bottom: 1px solid var(--line); + overflow-x: auto; +} + +.tab { + padding: 0 14px; + border: 0; + border-right: 1px solid var(--line); + background: transparent; + font-size: 12.5px; + font-weight: 600; + color: var(--muted); + cursor: pointer; + white-space: nowrap; +} + +.tab:hover { + color: var(--ink); +} + +.tab.active { + color: var(--ink); + background: var(--paper); + box-shadow: inset 0 -2px var(--ink); +} + +.tabs-hint, +.focus-file { + margin-left: auto; + padding: 0 12px; + display: flex; + align-items: center; + gap: 6px; + font-size: 11px; + color: var(--muted); + white-space: nowrap; +} + +.tabs-hint { + text-transform: uppercase; + letter-spacing: 0.12em; + font-size: 9.5px; + font-weight: 700; +} + +.focus-file select { + border: 1px solid var(--line-strong); + background: var(--surface); + padding: 2px 4px; + font-size: 12px; + font-family: var(--mono); +} + +.subtabs { + display: flex; + flex-wrap: wrap; + gap: 6px; + padding: 8px 12px; + border-bottom: 1px solid var(--line); +} + +.subtab { + padding: 3px 9px; + border: 1px solid var(--line-strong); + background: transparent; + font-size: 11.5px; + font-weight: 600; + color: var(--muted); + cursor: pointer; +} + +.subtab.active { + background: var(--ink); + color: var(--paper); + border-color: var(--ink); +} + +.pane-scroll { + flex: 1; + min-height: 180px; + max-height: 520px; + overflow: auto; + transition: opacity 0.15s; +} + +.pane-scroll.stale { + opacity: 0.55; +} + +.view-note { + padding: 10px 18px 0; + font-size: 12px; + color: var(--muted); +} + +.empty { + padding: 28px 18px; + color: var(--muted); + font-size: 13px; +} + +.problems { + padding: 14px 18px; +} + +.problem { + margin: 0 0 12px; + font-family: var(--mono); + font-size: 12.5px; + line-height: 1.55; + white-space: pre-wrap; + word-break: break-word; + color: var(--error); +} + +.output { + border-top: 1px solid var(--line); + padding: 10px 18px 12px; + max-height: 190px; + overflow: auto; + background: var(--sunken); +} + +.output-label { + text-transform: uppercase; + letter-spacing: 0.12em; + font-size: 9.5px; + font-weight: 700; + color: var(--muted); + margin-bottom: 6px; +} + +.output-line { + margin: 0; + font-family: var(--mono); + font-size: 12.5px; + line-height: 1.55; + white-space: pre-wrap; + word-break: break-word; +} + +.output-line.error { + color: var(--error); +} + +.output-line.warn { + color: var(--warn); +} + +.output-empty { + font-size: 12.5px; + color: var(--muted); +} + +.example-foot { + display: flex; + align-items: center; + gap: 8px; + padding: 7px 16px; + border-top: 1px solid var(--line); + font-size: 11.5px; + color: var(--muted); +} + +.pulse { + width: 7px; + height: 7px; + border-radius: 50%; + background: var(--line-strong); + flex-shrink: 0; +} + +.pulse.live { + background: #4c9a3f; +} + +.pulse.failed { + background: var(--error); +} + +.pulse.on { + background: var(--orange); + animation: pulse 0.9s ease-in-out infinite; +} + +@keyframes pulse { + 50% { + opacity: 0.25; + } +} + +/* The editor */ +.editor .cm-editor { + background: transparent; + font-size: 13px; +} + +.editor .cm-editor.cm-focused { + outline: none; +} + +.editor .cm-scroller { + font-family: var(--mono); + line-height: 1.6; +} + +.editor .cm-content { + padding: 16px 0; + caret-color: var(--ink); +} + +.editor .cm-line { + padding: 0 18px; +} + +.editor .cm-cursor { + border-left-color: var(--ink); +} + +.editor .cm-selectionBackground, +.editor .cm-content ::selection { + background: color-mix(in srgb, var(--lime) 55%, transparent) !important; +} + +.editor .cm-matchingBracket { + background: var(--hole); + outline: 1px solid var(--line-strong); +} + +/* Internals: the trees */ +.tree-root { + padding: 12px 10px; + font-family: var(--mono); + font-size: 12px; + line-height: 1.5; +} + +.tree-node { + padding-left: 14px; + user-select: none; +} + +.tree-node-header { + display: flex; + align-items: center; + gap: 4px; + padding: 1px 4px; + cursor: pointer; +} + +.tree-node-header:hover { + background: var(--sunken); +} + +.tree-node-header.highlighted { + background: var(--hole); + outline: 1px solid var(--line-strong); +} + +.tree-toggle { + width: 14px; + display: inline-flex; + justify-content: center; + color: var(--muted); + font-size: 9px; + flex-shrink: 0; +} + +.tree-toggle.leaf { + visibility: hidden; +} + +.tree-tag { color: var(--tok-type); font-weight: 600; } +.tree-atom { color: var(--tok-property); } +.tree-string { color: var(--tok-string); } +.tree-number { color: var(--tok-number); } +.tree-keyword { color: var(--tok-keyword); } +.tree-loc { color: var(--muted); font-size: 10.5px; } +.empty-panel { padding: 28px 18px; color: var(--muted); font-size: 13px; } + +/* Diagrams */ +.flow, +.sequence, +.chart { + margin: 8px 0 30px; + max-width: 980px; + padding: 26px; + border: 1px solid var(--line); + background: var(--surface); +} + +.flow-row { + display: grid; + grid-template-columns: 1fr 120px 1fr 120px 1fr; + align-items: stretch; +} + +.flow-node { + min-width: 0; + padding: 14px 16px; + border: 1px solid var(--line-strong); + background: var(--paper); + display: flex; + flex-direction: column; + gap: 3px; + font-size: 13px; + line-height: 1.4; +} + +.flow-node b { + font-size: 14px; +} + +.flow-node span { + color: var(--muted); +} + +.flow-out { + background: var(--ink); + color: var(--paper); + border-color: var(--ink); +} + +.flow-out span { + color: color-mix(in srgb, var(--paper) 65%, transparent); +} + +.flow-accent { + background: var(--lime); + color: #18201d; + border-color: #18201d; +} + +.flow-accent span { + color: rgba(24, 32, 29, 0.7); +} + +.flow-engine { + border-style: dashed; +} + +.flow-arrow { + position: relative; + display: flex; + align-items: center; + justify-content: center; +} + +.flow-arrow::before { + content: ""; + position: absolute; + left: 6px; + right: 10px; + top: 50%; + height: 1px; + background: var(--ink); +} + +.flow-arrow::after { + content: ""; + position: absolute; + right: 4px; + top: calc(50% - 4px); + border: 4px solid transparent; + border-left-color: var(--ink); +} + +.flow-arrow em, +.flow-drop em { + position: relative; + z-index: 1; + padding: 1px 6px; + font-style: normal; + font-size: 11px; + font-weight: 600; + color: var(--muted); + text-align: center; + line-height: 1.25; + transform: translateY(-14px); +} + +/* Below the middle node of the first row. */ +.flow-drop { + height: 44px; + margin-left: 50%; + width: 0; + border-left: 1px solid var(--ink); + position: relative; +} + +.flow-drop::after { + content: ""; + position: absolute; + left: -4.5px; + bottom: -2px; + border: 4px solid transparent; + border-top-color: var(--ink); +} + +.flow-drop em { + position: absolute; + left: 10px; + top: 12px; + white-space: nowrap; + transform: none; +} + +.flow-none::before, +.flow-none::after { + display: none; +} + +.flow-notes { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 18px; + margin-top: 20px; + padding-top: 18px; + border-top: 1px solid var(--line); + font-size: 13.5px; + line-height: 1.5; + color: var(--muted); +} + +.flow-notes b { + color: var(--ink); +} + +.sequence { + overflow-x: auto; +} + +.sequence-head, +.sequence-row { + display: grid; + grid-template-columns: repeat(var(--lanes), minmax(150px, 1fr)); + min-width: 620px; +} + +.sequence-head div { + margin: 0 6px 10px; + padding: 8px 10px; + border: 1px solid var(--line-strong); + background: var(--paper); + text-align: center; + font-size: 12.5px; + font-weight: 650; +} + +.sequence-row { + padding: 6px 0; +} + +.sequence-row.in-loop { + background-color: color-mix(in srgb, var(--lime) 10%, transparent); +} + +/* From the middle of the first lane it spans to the middle of the last. */ +.sequence-message { + position: relative; + margin: 0 calc(50% / var(--span)); + padding-bottom: 5px; + border-bottom: 1px solid var(--ink); + font-size: 12px; + line-height: 1.35; + text-align: center; +} + +.sequence-message::after { + content: ""; + position: absolute; + right: -1px; + bottom: -4.5px; + border: 4px solid transparent; + border-left-color: var(--ink); +} + +.sequence-message.left::after { + right: auto; + left: -1px; + border-left-color: transparent; + border-right-color: var(--ink); +} + +.sequence-message.reply { + border-bottom-style: dashed; + color: var(--muted); +} + +.sequence-message.self { + border-bottom: 0; + margin: 0 8px; + padding: 3px 6px; + border: 1px dashed var(--line-strong); + color: var(--muted); +} + +.sequence-message.self::after { + display: none; +} + +.sequence-loop { + min-width: 620px; + margin-top: 6px; + padding: 4px 10px; + background: color-mix(in srgb, var(--lime) 26%, transparent); + font-size: 11.5px; + font-weight: 650; +} + +.chart-row { + display: grid; + grid-template-columns: minmax(180px, 280px) 1fr; + gap: 18px; + align-items: center; + padding: 9px 0; + border-bottom: 1px solid var(--line); +} + +.chart-label { + display: flex; + flex-direction: column; + font-size: 13.5px; + line-height: 1.35; +} + +.chart-label span { + color: var(--muted); + font-size: 12px; +} + +.chart-track { + display: flex; + align-items: center; + gap: 10px; +} + +.chart-bar { + height: 16px; + min-width: 3px; + background: var(--ink); +} + +.chart-bar.macro { + background: var(--lime); + outline: 1px solid var(--ink); + outline-offset: -1px; +} + +.chart-value { + font-family: var(--mono); + font-size: 12.5px; + white-space: nowrap; +} + +.chart figcaption { + margin-top: 12px; + font-size: 12px; + color: var(--muted); +} + +.colophon { + margin-top: 96px; + padding-top: 24px; + border-top: 1px solid var(--line); + font-size: 13.5px; + color: var(--muted); + max-width: 720px; +} + +/* Narrow screens */ +@media (max-width: 1020px) { + .layout { + grid-template-columns: minmax(0, 1fr); + } + + .toc { + display: none; + } +} + +@media (max-width: 820px) { + body { + font-size: 16px; + } + + .hero { + padding: 56px 20px 40px; + } + + .layout { + padding: 0 20px 80px; + } + + .topbar { + padding: 0 20px; + } + + .topbar nav { + gap: 14px; + font-size: 12px; + } + + .brand span { + display: none; + } + + .example { + margin-left: -20px; + margin-right: -20px; + border-left: 0; + border-right: 0; + } + + .example-body { + grid-template-columns: minmax(0, 1fr); + } + + .pane-source { + border-right: 0; + border-bottom: 1px solid var(--line); + } + + .pane-scroll { + max-height: 380px; + min-height: 120px; + } + + .example-head { + flex-direction: column; + align-items: flex-start; + } + + .flow, + .sequence, + .chart { + padding: 18px; + } + + .flow-row { + grid-template-columns: 1fr; + } + + .flow-spacer, + .flow-none { + display: none; + } + + .flow-arrow { + height: 38px; + } + + .flow-arrow::before { + left: 50%; + right: auto; + top: 4px; + bottom: 8px; + width: 1px; + height: auto; + } + + .flow-arrow::after { + right: auto; + left: calc(50% - 3.5px); + top: auto; + bottom: 1px; + border-left-color: transparent; + border-top-color: var(--ink); + } + + .flow-arrow em { + transform: translateX(86px); + white-space: nowrap; + } + + .flow-drop { + height: 38px; + } + + .flow-notes { + grid-template-columns: 1fr; + } + + .chart-row { + grid-template-columns: 1fr; + gap: 6px; + } + + .anchor { + display: none; + } +} diff --git a/playground/src/style.css b/playground/src/style.css index 5740811a58..5362b3c2ba 100644 --- a/playground/src/style.css +++ b/playground/src/style.css @@ -525,3 +525,17 @@ h1 { .problem.skipped { color: var(--text-muted); } + +.back { + color: var(--text-muted); + font-size: 12px; + text-decoration: none; + padding-right: 12px; + margin-right: 4px; + border-right: 1px solid var(--border); + white-space: nowrap; +} + +.back:hover { + color: inherit; +} diff --git a/playground/vite.config.js b/playground/vite.config.js index 739ecb704c..28e64cee12 100644 --- a/playground/vite.config.js +++ b/playground/vite.config.js @@ -1,4 +1,5 @@ import { defineConfig } from "vite"; +import { resolve } from "path"; import react from "@vitejs/plugin-react"; import wasm from "vite-plugin-wasm"; @@ -10,8 +11,21 @@ export default defineConfig({ format: "es", plugins: () => [wasm()], }, + server: { + // The RFC pages are rendered from docs/comptime. + fs: { allow: [".."] }, + }, build: { target: "esnext", + rollupOptions: { + input: { + // The RFC with live examples, the implementation notes, and the + // full playground. + index: resolve(import.meta.dirname, "index.html"), + implementation: resolve(import.meta.dirname, "implementation.html"), + playground: resolve(import.meta.dirname, "playground.html"), + }, + }, }, optimizeDeps: { exclude: ["rescript-playground-wasm"], From a031cae832ca9fccc251912baf35ee7b8357eed4 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 14:25:16 +0100 Subject: [PATCH 17/38] site: the source pane of an example is as tall as its result The source was limited to a fixed height while the result beside it also holds the program's output, which left an empty strip below the source. Co-authored-by: Jaap Frolich Session: https://jakes-mac-mini.tail23a77e.ts.net:8443/session/os-01a1ca09-2757-709a-bbb1-e57ccc4d104f Signed-off-by: Jaap Frolich --- playground/src/rfc/Example.jsx | 2 +- playground/src/rfc/rfc.css | 22 ++++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/playground/src/rfc/Example.jsx b/playground/src/rfc/Example.jsx index 3b5494e55d..4ded4c1f09 100644 --- a/playground/src/rfc/Example.jsx +++ b/playground/src/rfc/Example.jsx @@ -157,7 +157,7 @@ export function Example({ example, prebuilt }) { ))} editable
    -
    +
    Date: Wed, 11 Nov 2026 14:47:34 +0100 Subject: [PATCH 18/38] macros: report the error of the code, not a macro that was left When an item has an error of its own (an unknown name in the argument of a @generic, a type error in a %comptime expression), its macro use cannot be expanded, and the compilation of the expanded file stopped at that use with "macro expansion left a macro unexpanded". The compilation of an expanded file now types a use that is left as far as its declared type goes, so type checking gets to the error and reports it as for any file. A failed item generates no instances, and its failure is ordered after the problems its own macros reported. Co-authored-by: Jaap Frolich Session: https://jakes-mac-mini.tail23a77e.ts.net:8443/session/os-01a1ca09-2757-709a-bbb1-e57ccc4d104f Signed-off-by: Jaap Frolich --- compiler-rust/src/driver.rs | 23 +++-- compiler-rust/src/macros/discover.rs | 79 ++++++++++++--- compiler-rust/src/macros/edit.rs | 10 ++ compiler-rust/src/macros/expand.rs | 10 +- compiler-rust/src/parse_arena.rs | 13 +++ compiler-rust/tests/macros.rs | 113 +-------------------- compiler-rust/tests/macros_support/mod.rs | 116 ++++++++++++++++++++++ 7 files changed, 230 insertions(+), 134 deletions(-) create mode 100644 compiler-rust/tests/macros_support/mod.rs diff --git a/compiler-rust/src/driver.rs b/compiler-rust/src/driver.rs index e14814e171..63447f01fe 100644 --- a/compiler-rust/src/driver.rs +++ b/compiler-rust/src/driver.rs @@ -12701,13 +12701,6 @@ pub fn compile_source_in_process( host, )?; match compile(Some(&expanded)) { - Err(error) if error.is::() => { - Err(UserDiagnostic::new( - format!("{filename}: macro expansion left a macro unexpanded.\n"), - 2, - ) - .into()) - } Ok(mut compiled) => { compiled.expanded_source = Some(expanded.text().to_string()); Ok(compiled) @@ -13112,6 +13105,9 @@ pub(crate) fn in_process_type_check_context<'a>( frontend_warning_specs: &[ppx::WarningAttributeSpec], ) -> (TypeCheckContext<'a>, Env) { let mut tctx = TypeCheckContext::new(type_ctx, arena); + if arena.expansion().is_some() { + tctx.macro_mode = crate::macros::discover::MacroMode::Expanded { left: None }; + } tctx.experimental_let_unwrap = options.experimental_let_unwrap || file_config.let_unwrap; tctx.transparent_modules = options.transparent_modules; apply_warning_options(&mut tctx, options); @@ -13328,6 +13324,19 @@ pub fn compile_preprocessed_structure_in_process_until_js( let _phase = info_span!("compiler.type_structure").entered(); type_structure(&mut tctx, &env, arena, structure) }); + // A macro use that expansion left behind, in a file that type checks. + let typed = match (typed, &tctx.macro_mode) { + (Ok(_), crate::macros::discover::MacroMode::Expanded { left: Some(loc) }) => { + Err(TypeModError::CoreError(TypeCoreError::ExtensionError( + crate::types::typecore::BuiltinExtensionError { + loc: *loc, + message: crate::macros::discover::UNEXPANDED.to_string(), + sub: Vec::new(), + }, + ))) + } + (typed, _) => typed, + }; let (typed_structure, final_env) = match typed { Ok(result) => result, Err(e) => { diff --git a/compiler-rust/src/macros/discover.rs b/compiler-rust/src/macros/discover.rs index 210659ceee..3ac2be16af 100644 --- a/compiler-rust/src/macros/discover.rs +++ b/compiler-rust/src/macros/discover.rs @@ -45,8 +45,18 @@ pub enum MacroMode { Off, /// A discovery pass of [`super::expand`]. Discover(Box), + /// The compilation of a file after its expansion. A macro use is left + /// only where the code has an error of its own (an unknown name in the + /// argument of a `@generic`, say): the use is typed as far as its + /// declared type goes, so that type checking gets to that error and + /// reports it. `left` is the first such use. + Expanded { left: Option }, } +/// Reported if a macro use is left in a file that otherwise type checks. +pub const UNEXPANDED: &str = + "This macro use was not expanded. This is a bug in the compiler: please report it."; + /// A problem a macro reported, or one with how a macro is used. #[derive(Debug, Clone)] pub struct MacroDiagnostic { @@ -303,7 +313,8 @@ pub struct Discovery { base_dir: std::path::PathBuf, pub edits: Vec, pub errors: Vec, - /// Start of each top-level item that failed to type check. + /// Per top-level item that failed to type check: where the failure + /// counts as being, for the order of what is reported. pub failed_items: Vec, pub instances: InstanceTable, pub comptime: Vec, @@ -314,6 +325,8 @@ pub struct Discovery { item_start: u32, /// The item stopped because one of its macros was expanded. item_pending: bool, + /// How many problems were reported before the item. + item_errors: usize, /// The application whose function is being typed. apply: Option<(LocIdx, PendingCall)>, /// The instance groups in the text, by ordinal. @@ -355,6 +368,7 @@ impl Discovery { depth: 0, item_start: 0, item_pending: false, + item_errors: 0, apply: None, groups: BTreeMap::new(), added: Vec::new(), @@ -618,10 +632,25 @@ fn error_at(loc: LocIdx, message: impl Into) -> TypeCoreError { /// Stop an ordinary compilation at a macro use. fn required(tctx: &mut TypeCheckContext<'_>, loc: LocIdx) -> TypeCoreError { + if leave(tctx, loc) { + return error_at(loc, UNEXPANDED); + } tctx.macro_expansion_required = true; error_at(loc, "This file uses macros and has to be expanded first.") } +/// In the compilation of an expanded file: note the macro use at `loc` as +/// left over. Returns whether this is such a compilation. +fn leave(tctx: &mut TypeCheckContext<'_>, loc: LocIdx) -> bool { + match &mut tctx.macro_mode { + MacroMode::Expanded { left } => { + left.get_or_insert(loc); + true + } + _ => false, + } +} + /// Stop typing the current item of a discovery pass: its edit, or the /// macro's error, is recorded. fn pending(tctx: &mut TypeCheckContext<'_>, loc: LocIdx) -> TypeCoreError { @@ -641,7 +670,7 @@ fn fail(tctx: &mut TypeCheckContext<'_>, loc: LocIdx, message: impl Into discovery.error(at, message); pending(tctx, loc) } - MacroMode::Off => error_at(loc, message), + MacroMode::Off | MacroMode::Expanded { .. } => error_at(loc, message), } } @@ -915,7 +944,7 @@ pub(crate) fn expression_extension( if is_hole || quote::is_quote_name(&name) { // Quotes are lowered before a discovery pass; one that is left has // no payload. - return Some(Err(if !discovering(tctx) { + return Some(Err(if matches!(tctx.macro_mode, MacroMode::Off) { required(tctx, loc) } else if is_hole { fail(tctx, loc, HOLE_OUTSIDE_QUOTE) @@ -933,7 +962,8 @@ pub(crate) fn expression_extension( Ok(desc) => desc, Err(error) => return Some(Err(error)), }; - if !discovering(tctx) { + // After expansion a use that is left is typed as its declared result. + if !discovering(tctx) && !leave(tctx, loc) { return Some(Err(required(tctx, loc))); } let ctx = tctx.type_ctx; @@ -979,7 +1009,7 @@ fn comptime( extension: &Extension, expected_ty: TypeExprRef, ) -> TypeCoreResult { - if !discovering(tctx) { + if !discovering(tctx) && !leave(tctx, loc) { return Err(required(tctx, loc)); } let expr_idx = match payload_expressions(tctx.arena, &extension.1, 1) { @@ -1058,7 +1088,7 @@ pub(crate) fn generic_use( format!("`{name}` is a macro. Use it as `%{name}(...)` or attach it as `@{name}`."), )); } - if !discovering(tctx) { + if !discovering(tctx) && !leave(tctx, loc) { return Err(required(tctx, loc)); } let ctx = tctx.type_ctx; @@ -1125,6 +1155,7 @@ pub(crate) fn begin_item(tctx: &mut TypeCheckContext<'_>, item: &ParsedStructure let (start, end) = range(arena, item.pstr_loc); discovery.item_start = start; discovery.item_pending = false; + discovery.item_errors = discovery.errors.len(); // An instance group that an earlier pass added. if is_instance_group(arena, item) && let ParsedStructureItemDesc::Pstr_value((_, bindings)) = &item.pstr_desc @@ -1188,11 +1219,20 @@ pub(crate) fn end_item(tctx: &mut TypeCheckContext<'_>, ok: bool) { return; } discovery.apply = None; + let pending = std::mem::take(&mut discovery.pending); if !ok && !discovery.item_pending { + // The item has a type error. It comes after the problems its macros + // reported while it was typed, and before the rest of the file. let start = discovery.item_start; - discovery.failed_items.push(start); + let at = discovery.errors[discovery.item_errors..] + .iter() + .map(|error| error.end) + .max() + .unwrap_or(start); + discovery.failed_items.push(at); + // Its types are not final: no generic is generated from them. + return; } - let pending = std::mem::take(&mut discovery.pending); with_discovery(tctx, |tctx, discovery| { for generic in pending { resolve_generic(tctx, discovery, generic); @@ -1367,10 +1407,10 @@ pub(crate) fn pattern_extension( ) -> Option { let name = tctx.arena.get_string(extension.0.txt).to_string(); if name == HOLE_EXTENSION { - return Some(if discovering(tctx) { - fail(tctx, loc, HOLE_OUTSIDE_QUOTE) - } else { + return Some(if matches!(tctx.macro_mode, MacroMode::Off) { required(tctx, loc) + } else { + fail(tctx, loc, HOLE_OUTSIDE_QUOTE) }); } if !is_macro_name(&name) { @@ -1412,10 +1452,10 @@ pub(crate) fn type_extension( ) -> Option { let name = tctx.arena.get_string(extension.0.txt).to_string(); if name == HOLE_EXTENSION { - return Some(if discovering(tctx) { - fail(tctx, loc, HOLE_OUTSIDE_QUOTE) - } else { + return Some(if matches!(tctx.macro_mode, MacroMode::Off) { required(tctx, loc) + } else { + fail(tctx, loc, HOLE_OUTSIDE_QUOTE) }); } if !is_macro_name(&name) { @@ -1645,11 +1685,18 @@ pub(crate) fn type_item_requires_expansion( return None; }; let arena = tctx.arena; - inner + if !inner .1 .iter() .any(|decl| has_macro_attribute(arena, &decl.ptype_attributes)) - .then(|| required(tctx, item.pstr_loc)) + { + return None; + } + // After expansion: the type itself is checked as written. + if leave(tctx, item.pstr_loc) { + return None; + } + Some(required(tctx, item.pstr_loc)) } /// `@M.f type t = ...`, after the declaration is type checked in `env`: the diff --git a/compiler-rust/src/macros/edit.rs b/compiler-rust/src/macros/edit.rs index 787927bb50..93fa64e050 100644 --- a/compiler-rust/src/macros/edit.rs +++ b/compiler-rust/src/macros/edit.rs @@ -138,6 +138,16 @@ impl SourceText { } } +/// What the compilation of an expanded file keeps of the expansion. +#[derive(Debug)] +pub struct Expansion { + /// The expanded text. + pub text: SourceText, + /// Per position of the parse, by index: its offset in the expanded + /// text. The positions themselves point into the source as written. + pub offsets: Vec, +} + fn char_offsets(text: &str) -> Vec { let mut offsets: Vec = text.char_indices().map(|(byte, _)| byte as u32).collect(); offsets.push(text.len() as u32); diff --git a/compiler-rust/src/macros/expand.rs b/compiler-rust/src/macros/expand.rs index da70b0ab0c..996113d92a 100644 --- a/compiler-rust/src/macros/expand.rs +++ b/compiler-rust/src/macros/expand.rs @@ -145,7 +145,9 @@ pub fn expand_source( let _ = type_structure(&mut tctx, &env, arena, &structure); match std::mem::replace(&mut tctx.macro_mode, MacroMode::Off) { MacroMode::Discover(discovery) => discovery.finish(), - MacroMode::Off => unreachable!("the discovery pass state was taken"), + MacroMode::Off | MacroMode::Expanded { .. } => { + unreachable!("the discovery pass state was taken") + } } }; drop(parser); @@ -203,7 +205,9 @@ pub fn remap_positions(arena: &mut crate::parse_arena::ParseArena, text: &Source .chars() .any(|ch| ch.len_utf16() > 1) .then(|| original.chars().collect()); + let mut offsets = Vec::with_capacity(arena.position_count()); arena.remap_positions(|position| { + offsets.push(position.cnum.max(0) as u32); if position.cnum < 0 { return; } @@ -220,6 +224,10 @@ pub fn remap_positions(arena: &mut crate::parse_arena::ParseArena, text: &Source position.bol = bol as i32; position.cnum = (bol + column) as i32; }); + arena.set_expansion(Arc::new(super::edit::Expansion { + text: text.clone(), + offsets, + })); } fn unwrap_text(text: Arc) -> SourceText { diff --git a/compiler-rust/src/parse_arena.rs b/compiler-rust/src/parse_arena.rs index 06fb550c0f..57686572a8 100644 --- a/compiler-rust/src/parse_arena.rs +++ b/compiler-rust/src/parse_arena.rs @@ -490,6 +490,9 @@ pub struct ParseArena { position_file_names: HashSet, /// Most recent file name recorded in `position_file_names`. last_position_file_name: Option, + /// Set when this is the parse of a macro-expanded text: what diagnostics + /// need to say where generated code comes from. + expansion: Option>, /// Arena of locations (returns LocIdx). locations: Arena, /// Arena of longidents (returns LidentIdx). @@ -986,6 +989,7 @@ impl Default for ParseArena { positions: Arena::default(), position_file_names: HashSet::new(), last_position_file_name: None, + expansion: None, locations: Arena::default(), longidents, synthetic_longidents: SyntheticVec::default(), @@ -2709,6 +2713,15 @@ impl ParseArena { } } + /// The expansion this parse is the result of, if any. + pub fn expansion(&self) -> Option<&crate::macros::edit::Expansion> { + self.expansion.as_deref() + } + + pub fn set_expansion(&mut self, expansion: std::sync::Arc) { + self.expansion = Some(expansion); + } + pub fn get_expr(&self, idx: ExprIdx) -> &Expression { let raw = idx.0; if raw < SHARED_EXPRESSION_BASE { diff --git a/compiler-rust/tests/macros.rs b/compiler-rust/tests/macros.rs index f15d49220e..6e6333a0ea 100644 --- a/compiler-rust/tests/macros.rs +++ b/compiler-rust/tests/macros.rs @@ -1,118 +1,11 @@ //! End-to-end tests of compile-time macros: each test compiles a small //! project in memory, with the standard library type-checked from source. -use std::collections::HashMap; -use std::path::PathBuf; -use std::sync::{Arc, Mutex}; - -use rescript_compiler::cmi::persistent_env::ModuleRegistry; -use rescript_compiler::driver::{self, CompilerOptions}; -use rescript_compiler::macros::MacroHost; -use rescript_compiler::macros::quickjs::QuickJsHost; - -fn runtime_dir() -> PathBuf { - PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../packages/@rescript/runtime") -} - +mod macros_support; -struct Project { - registry: ModuleRegistry, - /// Compiled JavaScript of the project's modules, for the macro engine. - javascript: Arc>>, - host: Arc, - /// The expanded source of the last compiled file, when it uses macros. - expanded: Option, - /// The warnings of the last compiled file. - warnings: String, -} - -impl Project { - fn new() -> Self { - let mut registry = ModuleRegistry::new(); - let mut modules: ahash::AHashMap = Default::default(); - for entry in std::fs::read_dir(runtime_dir()).unwrap() { - let path = entry.unwrap().path(); - let Some(ext) = path.extension().and_then(|e| e.to_str()) else { - continue; - }; - if ext != "res" && ext != "resi" { - continue; - } - let name = path.file_stem().unwrap().to_str().unwrap().to_string(); - if ext == "resi" || !modules.contains_key(&name) { - modules.insert(name, path); - } - } - registry.set_source_fallback_paths(modules); - registry.set_source_fallback_is_runtime(true); - let javascript: Arc>> = Default::default(); - let sources = javascript.clone(); - let host = Arc::new(QuickJsHost::new(Arc::new(move |name: &str| { - if let Some(source) = sources.lock().unwrap().get(name) { - return Some(source.clone()); - } - std::fs::read_to_string(runtime_dir().join(format!("lib/js/{name}.cjs"))).ok() - }))); - let mut project = Project { - registry, - javascript, - host, - expanded: None, - warnings: String::new(), - }; - // The macro API, compiled from source like the rest of the project. - let macro_source = std::fs::read_to_string(runtime_dir().join("Macro.res")).unwrap(); - project.compile("Macro.res", ¯o_source).unwrap(); - project - } +use std::path::PathBuf; - fn compile(&mut self, filename: &str, source: &str) -> Result { - let module_name = driver::module_name_from_source_filename(filename); - let host: Arc = self.host.clone(); - let options = CompilerOptions { - source_filename: Some(filename.to_string()), - module_name: Some(module_name.clone()), - macro_host: Some(host), - ..Default::default() - }; - // As the compiler reads a file: one `char` per byte. - let source: String = source.bytes().map(char::from).collect(); - let source = source.as_str(); - match driver::compile_source_in_process( - source, - filename, - &module_name, - &options, - &self.registry, - false, - ) { - Ok(compiled) => { - if let Some(ps) = compiled.pers_struct { - self.registry.register_module( - &module_name, - ps, - rescript_compiler::cmi::persistent_env::InMemoryModuleInfo::new( - PathBuf::from(filename), - false, - Default::default(), - module_name == "Macro", - ), - ); - } - let text = |text: &str| { - rescript_compiler::source_text::decode_internal_utf8(text).into_owned() - }; - let js = text(&compiled.js_output); - self.javascript.lock().unwrap().insert(module_name, js.clone()); - self.host.invalidate(); - self.expanded = compiled.expanded_source.as_deref().map(text); - self.warnings = text(&compiled.warnings); - Ok(js) - } - Err(e) => Err(rescript_compiler::source_text::decode_internal_utf8(&format!("{e:#}")).into_owned()), - } - } -} +use macros_support::Project; #[test] fn plain_module_compiles() { diff --git a/compiler-rust/tests/macros_support/mod.rs b/compiler-rust/tests/macros_support/mod.rs new file mode 100644 index 0000000000..93e7a52ada --- /dev/null +++ b/compiler-rust/tests/macros_support/mod.rs @@ -0,0 +1,116 @@ +//! A small in-memory project for the macro tests: the standard library is +//! type checked from source, and macros run in QuickJS. +#![allow(dead_code)] + +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; + +use rescript_compiler::cmi::persistent_env::ModuleRegistry; +use rescript_compiler::driver::{self, CompilerOptions}; +use rescript_compiler::macros::MacroHost; +use rescript_compiler::macros::quickjs::QuickJsHost; + +pub fn runtime_dir() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../packages/@rescript/runtime") +} + + +pub struct Project { + registry: ModuleRegistry, + /// Compiled JavaScript of the project's modules, for the macro engine. + javascript: Arc>>, + host: Arc, + /// The expanded source of the last compiled file, when it uses macros. + pub expanded: Option, + /// The warnings of the last compiled file. + pub warnings: String, +} + +impl Project { + pub fn new() -> Self { + let mut registry = ModuleRegistry::new(); + let mut modules: ahash::AHashMap = Default::default(); + for entry in std::fs::read_dir(runtime_dir()).unwrap() { + let path = entry.unwrap().path(); + let Some(ext) = path.extension().and_then(|e| e.to_str()) else { + continue; + }; + if ext != "res" && ext != "resi" { + continue; + } + let name = path.file_stem().unwrap().to_str().unwrap().to_string(); + if ext == "resi" || !modules.contains_key(&name) { + modules.insert(name, path); + } + } + registry.set_source_fallback_paths(modules); + registry.set_source_fallback_is_runtime(true); + let javascript: Arc>> = Default::default(); + let sources = javascript.clone(); + let host = Arc::new(QuickJsHost::new(Arc::new(move |name: &str| { + if let Some(source) = sources.lock().unwrap().get(name) { + return Some(source.clone()); + } + std::fs::read_to_string(runtime_dir().join(format!("lib/js/{name}.cjs"))).ok() + }))); + let mut project = Project { + registry, + javascript, + host, + expanded: None, + warnings: String::new(), + }; + // The macro API, compiled from source like the rest of the project. + let macro_source = std::fs::read_to_string(runtime_dir().join("Macro.res")).unwrap(); + project.compile("Macro.res", ¯o_source).unwrap(); + project + } + + pub fn compile(&mut self, filename: &str, source: &str) -> Result { + let module_name = driver::module_name_from_source_filename(filename); + let host: Arc = self.host.clone(); + let options = CompilerOptions { + source_filename: Some(filename.to_string()), + module_name: Some(module_name.clone()), + macro_host: Some(host), + ..Default::default() + }; + // As the compiler reads a file: one `char` per byte. + let source: String = source.bytes().map(char::from).collect(); + let source = source.as_str(); + match driver::compile_source_in_process( + source, + filename, + &module_name, + &options, + &self.registry, + false, + ) { + Ok(compiled) => { + if let Some(ps) = compiled.pers_struct { + self.registry.register_module( + &module_name, + ps, + rescript_compiler::cmi::persistent_env::InMemoryModuleInfo::new( + PathBuf::from(filename), + false, + Default::default(), + module_name == "Macro", + ), + ); + } + let text = |text: &str| { + rescript_compiler::source_text::decode_internal_utf8(text).into_owned() + }; + let js = text(&compiled.js_output); + self.javascript.lock().unwrap().insert(module_name, js.clone()); + self.host.invalidate(); + self.expanded = compiled.expanded_source.as_deref().map(text); + self.warnings = text(&compiled.warnings); + Ok(js) + } + Err(e) => Err(rescript_compiler::source_text::decode_internal_utf8(&format!("{e:#}")).into_owned()), + } + } +} From 26e9b4b1ebbc888d9d3eb2b381d922375ecb832a Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 15:13:28 +0100 Subject: [PATCH 19/38] macros: an error in generated code says where the code was written Every character of an expanded file now knows where it comes from: its place in the file as written, or the macro use it was generated for and, for code written in a quote, the file, line and column of that quote. Code values carry that through the macro: a quote's pieces come with their position, an argument with its place in the file, and `Macro` keeps both when it builds code from parts. With that: - an error in an argument of a macro points at the argument, not at the whole use; - an error or warning in generated code is reported at the use, as a range, followed by the lines of the quote it is in; code that is not from a quote is shown as it is in the expanded source; - an error in a function generated for a @generic says which one: "generated by `Json.encode` for `t`"; - a macro that keeps generating a use of itself is reported at that use; - generated code that does not parse is reported at the use, with the expanded source; - an exception in a macro and a message from `Macro.error` read as such, and a %comptime expression that uses the file's own values says so without a second report inside the first. The tests write their files to a directory, so the diagnostics show code frames, and tests/macro_errors.rs compares the diagnostics of 21 broken programs with tests/macro_errors/*.txt. Co-authored-by: Jaap Frolich Session: https://jakes-mac-mini.tail23a77e.ts.net:8443/session/os-01a1ca09-2757-709a-bbb1-e57ccc4d104f Signed-off-by: Jaap Frolich --- compiler-rust/src/driver.rs | 21 +- compiler-rust/src/macros/discover.rs | 599 ++++++++++++++---- compiler-rust/src/macros/edit.rs | 569 +++++++++++++++-- compiler-rust/src/macros/expand.rs | 258 ++++++-- compiler-rust/src/macros/host.js | 34 +- compiler-rust/src/macros/mod.rs | 1 + compiler-rust/src/macros/quote.rs | 101 ++- compiler-rust/src/macros/reflect.rs | 34 +- compiler-rust/src/macros/report.rs | 85 +++ compiler-rust/src/parse_arena.rs | 36 +- compiler-rust/tests/macro_errors.rs | 216 +++++++ .../tests/macro_errors/argumentType.txt | 14 + .../tests/macro_errors/argumentUnbound.txt | 11 + .../tests/macro_errors/builtCode.txt | 16 + .../tests/macro_errors/comptimeFunction.txt | 11 + .../tests/macro_errors/comptimeLocal.txt | 15 + .../tests/macro_errors/comptimeThrows.txt | 12 + .../tests/macro_errors/comptimeType.txt | 14 + .../tests/macro_errors/errorBesideAUse.txt | 18 + .../macro_errors/expansionWithoutEnd.txt | 12 + .../tests/macro_errors/generatedSyntax.txt | 22 + .../macro_errors/genericArgumentUnbound.txt | 17 + .../tests/macro_errors/macroReports.txt | 13 + .../macro_errors/macroReportsInAnInstance.txt | 23 + .../tests/macro_errors/macroThrows.txt | 12 + .../tests/macro_errors/macroThrowsJs.txt | 12 + .../tests/macro_errors/quotedDeclarations.txt | 22 + .../tests/macro_errors/quotedInGeneric.txt | 22 + .../tests/macro_errors/quotedType.txt | 24 + .../tests/macro_errors/quotedUnbound.txt | 20 + .../tests/macro_errors/quotedWarning.txt | 25 + .../tests/macro_errors/unknownMacro.txt | 11 + compiler-rust/tests/macros.rs | 13 - compiler-rust/tests/macros_support/mod.rs | 46 +- packages/@rescript/runtime/Macro.res | 126 +++- packages/@rescript/runtime/lib/es6/Macro.mjs | 191 +++++- packages/@rescript/runtime/lib/js/Macro.cjs | 191 +++++- 37 files changed, 2504 insertions(+), 363 deletions(-) create mode 100644 compiler-rust/src/macros/report.rs create mode 100644 compiler-rust/tests/macro_errors.rs create mode 100644 compiler-rust/tests/macro_errors/argumentType.txt create mode 100644 compiler-rust/tests/macro_errors/argumentUnbound.txt create mode 100644 compiler-rust/tests/macro_errors/builtCode.txt create mode 100644 compiler-rust/tests/macro_errors/comptimeFunction.txt create mode 100644 compiler-rust/tests/macro_errors/comptimeLocal.txt create mode 100644 compiler-rust/tests/macro_errors/comptimeThrows.txt create mode 100644 compiler-rust/tests/macro_errors/comptimeType.txt create mode 100644 compiler-rust/tests/macro_errors/errorBesideAUse.txt create mode 100644 compiler-rust/tests/macro_errors/expansionWithoutEnd.txt create mode 100644 compiler-rust/tests/macro_errors/generatedSyntax.txt create mode 100644 compiler-rust/tests/macro_errors/genericArgumentUnbound.txt create mode 100644 compiler-rust/tests/macro_errors/macroReports.txt create mode 100644 compiler-rust/tests/macro_errors/macroReportsInAnInstance.txt create mode 100644 compiler-rust/tests/macro_errors/macroThrows.txt create mode 100644 compiler-rust/tests/macro_errors/macroThrowsJs.txt create mode 100644 compiler-rust/tests/macro_errors/quotedDeclarations.txt create mode 100644 compiler-rust/tests/macro_errors/quotedInGeneric.txt create mode 100644 compiler-rust/tests/macro_errors/quotedType.txt create mode 100644 compiler-rust/tests/macro_errors/quotedUnbound.txt create mode 100644 compiler-rust/tests/macro_errors/quotedWarning.txt create mode 100644 compiler-rust/tests/macro_errors/unknownMacro.txt diff --git a/compiler-rust/src/driver.rs b/compiler-rust/src/driver.rs index 63447f01fe..8d35e05ab4 100644 --- a/compiler-rust/src/driver.rs +++ b/compiler-rust/src/driver.rs @@ -4514,6 +4514,24 @@ fn push_compiler_error_report_header( push_compiler_report_location(output, &location); output.push_str(&code_frame::print(source, start_pos, end_pos)); output.push('\n'); + push_generated_code_note(output, arena, loc, false); + } +} + +/// For a diagnostic in code a macro generated: what +/// [`crate::macros::report`] says about that code. +fn push_generated_code_note(output: &mut String, arena: &ParseArena, loc: LocIdx, warning: bool) { + let Some(expansion) = arena.expansion() else { + return; + }; + let location = arena.get_location(loc); + if let Some(generated) = expansion.generated_code(location.loc_start.0, location.loc_end.0) { + output.push_str(&crate::macros::report::generated_code_note( + &expansion.text, + &generated, + warning, + read_in_process_source, + )); } } @@ -5491,6 +5509,7 @@ fn format_compiler_warning_report( code_frame::print_warning(source, start_pos, end_pos) }); output.push('\n'); + push_generated_code_note(&mut output, arena, warning.loc, !warning.is_error); } let indent_after_blank = !matches!( @@ -5591,7 +5610,7 @@ fn format_type_warnings( /// The source text an in-process compile reports diagnostics against. Like /// OCaml's code frames (location.ml), it is read back from the source file. -fn read_in_process_source(filename: &str) -> String { +pub(crate) fn read_in_process_source(filename: &str) -> String { #[cfg(target_arch = "wasm32")] { if let Some(content) = crate::wasm_vfs::read_file(filename) { diff --git a/compiler-rust/src/macros/discover.rs b/compiler-rust/src/macros/discover.rs index 3ac2be16af..3e9415bfd2 100644 --- a/compiler-rust/src/macros/discover.rs +++ b/compiler-rust/src/macros/discover.rs @@ -35,7 +35,7 @@ use crate::types::typecore::{ }; use crate::types::typedtree::{Expression, ExpressionDesc as TypedExpressionDesc}; -use super::edit::{Edit, SourceText}; +use super::edit::{Code, Edit, Segment, SourceText, Span, SpanSource}; use super::reflect::{self, TypeTable}; use super::{MacroHost, is_macro_name, quote}; @@ -124,11 +124,155 @@ struct Group { const GROUP_SEPARATOR: &str = "\nand "; -fn render_group(functions: &[String]) -> String { - format!( - "@{INSTANCES_ATTRIBUTE} @warning(\"-39\") let rec {}", - functions.join(GROUP_SEPARATOR) - ) +/// A function of an instance group, `name = (...) => body`. +struct Function { + /// The call the function was generated for, in the text being edited, + /// and what the function is. `None` for a function that is in the text + /// already. + generated_for: Option<((u32, u32), Arc)>, + segments: Vec, +} + +impl Function { + /// The function at `start..end` of the text. + fn in_text(start: u32, end: u32) -> Self { + Function { + generated_for: None, + segments: vec![Segment::Copy(start, end)], + } + } + + /// The function after `before`: the start of a group, or the separator. + fn render(self, before: &str, out: &mut Vec) { + if let Some(((start, end), description)) = self.generated_for { + out.push(Segment::For(start, end, Some(description))); + } + out.push(Segment::Text(before.to_string())); + out.extend(self.segments); + } +} + +fn render_group(functions: Vec) -> Vec { + let mut segments = Vec::new(); + for (index, function) in functions.into_iter().enumerate() { + if index == 0 { + function.render( + &format!("@{INSTANCES_ATTRIBUTE} @warning(\"-39\") let rec "), + &mut segments, + ); + } else { + function.render(GROUP_SEPARATOR, &mut segments); + } + } + segments +} + +/// Why a macro did not return code. +struct Failure { + message: String, + by: FailedBy, +} + +enum FailedBy { + /// The macro reported a problem, with `Macro.error`. + Report, + /// The macro raised an exception. + Exception, + /// The engine could not run the macro. + Engine, +} + +impl Failure { + fn engine(message: impl Into) -> Self { + Failure { + message: message.into(), + by: FailedBy::Engine, + } + } + + /// The message of the diagnostic at the use of the macro `name`. + fn report(&self, name: &str) -> String { + match self.by { + FailedBy::Report => format!( + "{}\n\nThis is reported by the macro `{name}`.", + self.message + ), + FailedBy::Exception => { + format!("The macro `{name}` raised an exception:\n{}", self.message) + } + FailedBy::Engine => self.message.clone(), + } + } +} + +/// The code a macro returned: its text, and the parts of it the engine says +/// are an argument or a quote. The engine counts in UTF-16 code units. +fn returned_code(text: &str, spans: Option<&Value>, origins: &[(u32, u32)]) -> Code { + let mut code = Code::plain(text); + let Some(spans) = spans.and_then(Value::as_array) else { + return code; + }; + // The text is one `char` per byte of its UTF-8 encoding. + let units: Option> = (!text.is_ascii()).then(|| { + let decoded = crate::source_text::decode_internal_utf8(text); + let mut offsets = Vec::with_capacity(decoded.len() + 1); + let mut bytes = 0u32; + for ch in decoded.chars() { + for _ in 0..ch.len_utf16() { + offsets.push(bytes); + } + bytes += ch.len_utf8() as u32; + } + offsets.push(bytes); + offsets + }); + let length = text.chars().count() as u32; + let offset = |unit: u64| -> Option { + match &units { + Some(units) => units.get(unit as usize).copied(), + None => (unit <= length as u64).then_some(unit as u32), + } + }; + for span in spans { + let Some(parts) = span.as_array() else { + continue; + }; + let (Some(start), Some(len)) = ( + parts.first().and_then(Value::as_u64), + parts.get(1).and_then(Value::as_u64), + ) else { + continue; + }; + let (Some(from), Some(to)) = (offset(start), offset(start + len)) else { + continue; + }; + let source = match &parts[2..] { + [origin] => match origin.as_u64().and_then(|id| origins.get(id as usize)) { + Some((at, _)) => SpanSource::Text(*at), + None => continue, + }, + [file, line, column] => { + let (Some(file), Some(line), Some(column)) = + (file.as_str(), line.as_u64(), column.as_u64()) + else { + continue; + }; + SpanSource::Quote { + file: file.into(), + line: line as u32, + column: column as u32, + } + } + _ => continue, + }; + code.spans.push(Span { + start: from, + len: to - from, + from: source, + }); + } + code.spans.sort_by_key(|span| span.start); + code } #[derive(Clone, Copy, PartialEq, Eq, Debug)] @@ -170,16 +314,18 @@ fn is_open(ctx: &TypeContext, ty: TypeExprRef) -> bool { fn macro_type_name(ctx: &TypeContext, ty: TypeExprRef) -> Option<(String, Vec)> { match &*ctx.get_desc(ctx.repr(ty)) { - TypeDesc::Tconstr { path, args, .. } => Some(( - path.name(), - ctx.type_list(*args).iter().collect(), - )), + TypeDesc::Tconstr { path, args, .. } => { + Some((path.name(), ctx.type_list(*args).iter().collect())) + } _ => None, } } fn param_kind(ctx: &TypeContext, ty: TypeExprRef) -> ParamKind { - match macro_type_name(ctx, ty).as_ref().map(|(name, _)| name.as_str()) { + match macro_type_name(ctx, ty) + .as_ref() + .map(|(name, _)| name.as_str()) + { Some("Macro.code") | Some("Macro.decls") => ParamKind::Code, Some("Macro.typ") => ParamKind::Typ, Some("Macro.Type.decl") => ParamKind::Decl, @@ -189,7 +335,10 @@ fn param_kind(ctx: &TypeContext, ty: TypeExprRef) -> ParamKind { } fn result_kind(ctx: &TypeContext, ty: TypeExprRef) -> ResultKind { - match macro_type_name(ctx, ty).as_ref().map(|(name, _)| name.as_str()) { + match macro_type_name(ctx, ty) + .as_ref() + .map(|(name, _)| name.as_str()) + { Some("Macro.code") => ResultKind::Code, Some("Macro.decls") => ResultKind::Decls, Some("Macro.typ") => ResultKind::Typ, @@ -333,7 +482,7 @@ pub struct Discovery { groups: BTreeMap, /// Instances this pass generated: the ordinal of the item that needs /// the instance, the offset of that item, and the function. - added: Vec<(u32, u32, String)>, + added: Vec<(u32, u32, Function)>, /// Instances an earlier item turned out to need as well: name, ordinal /// and offset of that item. They move to its group. moved: Vec<(String, u32, u32)>, @@ -382,14 +531,21 @@ impl Discovery { let mut targets: BTreeMap = BTreeMap::new(); let mut queue: VecDeque<(String, u32, u32)> = std::mem::take(&mut self.moved).into(); while let Some((name, ordinal, at)) = queue.pop_front() { - let Some((home, function)) = self.function_in_text(&name) else { + let Some((home, (start, end))) = self.function_in_text(&name) else { continue; }; - if home <= ordinal || targets.get(&name).is_some_and(|(target, _)| *target <= ordinal) { + if home <= ordinal + || targets + .get(&name) + .is_some_and(|(target, _)| *target <= ordinal) + { continue; } targets.insert(name, (ordinal, at)); - for word in function.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '$')) { + let function = self.text.slice(start, end); + for word in + function.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '$')) + { if word.contains('$') && self.instances.names.contains(word) { queue.push_back((word.to_string(), ordinal, at)); } @@ -403,46 +559,61 @@ impl Discovery { // What each group gains, by ordinal: the offset to start a new group // at, and the functions. - let mut gains: BTreeMap)> = BTreeMap::new(); + let mut gains: BTreeMap)> = BTreeMap::new(); for (name, (ordinal, at)) in &targets { - if let Some((_, function)) = self.function_in_text(name) { - gains.entry(*ordinal).or_insert((*at, Vec::new())).1.push(function); + if let Some((_, (start, end))) = self.function_in_text(name) { + gains + .entry(*ordinal) + .or_insert((*at, Vec::new())) + .1 + .push(Function::in_text(start, end)); } } let removed: HashSet<&String> = targets.keys().collect(); for (ordinal, at, function) in std::mem::take(&mut self.added) { - gains.entry(ordinal).or_insert((at, Vec::new())).1.push(function); + gains + .entry(ordinal) + .or_insert((at, Vec::new())) + .1 + .push(function); } for (ordinal, group) in &self.groups { - let gained = gains.remove(ordinal).map(|(_, functions)| functions).unwrap_or_default(); - let loses = group.functions.iter().any(|(name, _, _)| removed.contains(name)); + let gained = gains + .remove(ordinal) + .map(|(_, functions)| functions) + .unwrap_or_default(); + let loses = group + .functions + .iter() + .any(|(name, _, _)| removed.contains(name)); if !loses { if !gained.is_empty() { - let text: String = gained - .iter() - .map(|function| format!("{GROUP_SEPARATOR}{function}")) - .collect(); - self.edits.push(Edit::insert(group.item.1, text)); + let mut segments = Vec::new(); + for function in gained { + function.render(GROUP_SEPARATOR, &mut segments); + } + self.edits + .push(Edit::with(group.item.1, group.item.1, segments)); } continue; } - let mut functions: Vec = group + let mut functions: Vec = group .functions .iter() .filter(|(name, _, _)| !removed.contains(name)) - .map(|(_, start, end)| self.text.slice(*start, *end).to_string()) + .map(|(_, start, end)| Function::in_text(*start, *end)) .collect(); functions.extend(gained); - let text = if functions.is_empty() { - String::new() - } else { - render_group(&functions) - }; - self.edits.push(Edit::replace(group.item.0, group.item.1, text)); + self.edits.push(Edit::with( + group.item.0, + group.item.1, + render_group(functions), + )); } for (_, (at, functions)) in gains { - self.edits - .push(Edit::insert(at, format!("{}\n", render_group(&functions)))); + let mut segments = render_group(functions); + segments.push(Segment::Text("\n".into())); + self.edits.push(Edit::with(at, at, segments)); } PassResult { edits: self.edits, @@ -461,14 +632,14 @@ impl Discovery { }); } - /// The group an instance is defined in, and its text. - fn function_in_text(&self, name: &str) -> Option<(u32, String)> { + /// The group an instance is defined in, and where its function is. + fn function_in_text(&self, name: &str) -> Option<(u32, (u32, u32))> { self.groups.iter().find_map(|(home, group)| { group .functions .iter() .find(|(function, _, _)| function == name) - .map(|(_, start, end)| (*home, self.text.slice(*start, *end).to_string())) + .map(|(_, start, end)| (*home, (*start, *end))) }) } @@ -479,12 +650,13 @@ impl Discovery { let instance = self.instances.by_key.get_mut(key)?; if instance.ordinal > ordinal { instance.ordinal = ordinal; - self.moved.push((instance.name.clone(), ordinal, self.item_start)); + self.moved + .push((instance.name.clone(), ordinal, self.item_start)); } Some(instance.name.clone()) } - fn add_instance(&mut self, function: String) { + fn add_instance(&mut self, function: Function) { let ordinal = self.text.origin(self.item_start); self.added.push((ordinal, self.item_start, function)); } @@ -496,31 +668,58 @@ impl Discovery { env: &Env, table: &mut TypeTable, mut request: Value, - ) -> Result)> { + ) -> Result { let mut answers = serde_json::Map::new(); for _ in 0..4096 { request["answers"] = Value::Object(answers.clone()); - let response = super::call_host(&*self.host, &request.to_string()) - .map_err(|message| (format!("The macro engine failed: {message}"), None))?; - let response: Value = serde_json::from_str(&response) - .map_err(|error| (format!("The macro engine returned invalid JSON: {error}"), None))?; + let response = + super::call_host(&*self.host, &request.to_string()).map_err(|message| { + Failure::engine(format!("The macro engine failed: {message}")) + })?; + let response: Value = serde_json::from_str(&response).map_err(|error| { + Failure::engine(format!("The macro engine returned invalid JSON: {error}")) + })?; if let Some(code) = response.get("ok").and_then(Value::as_str) { - return Ok(code.to_string()); + let mut code = returned_code(code, response.get("spans"), table.origins()); + // A quote names its file without directories: find the file. + let mut paths: HashMap, Arc> = HashMap::new(); + for span in &mut code.spans { + if let SpanSource::Quote { file, .. } = &mut span.from { + let path = paths.entry(file.clone()).or_insert_with(|| { + let module = crate::driver::module_name_from_source_filename(file); + tctx.persistent_env + .as_ref() + .and_then(|env| env.resolve_module_source_path(&module)) + .map(|path| Arc::from(path.to_string_lossy().as_ref())) + .unwrap_or_else(|| file.clone()) + }); + *file = path.clone(); + } + } + return Ok(code); } if let Some(message) = response.get("error").and_then(Value::as_str) { - let offset = response - .get("offset") - .and_then(Value::as_u64) - .map(|offset| offset as u32); - return Err((message.to_string(), offset)); + let is = |key: &str| response.get(key).and_then(Value::as_bool) == Some(true); + return Err(Failure { + message: message.to_string(), + by: if is("exception") { + FailedBy::Exception + } else if is("engine") { + FailedBy::Engine + } else { + FailedBy::Report + }, + }); } let Some(question) = response.get("need").and_then(Value::as_str) else { - return Err(("The macro engine returned an unknown response.".into(), None)); + return Err(Failure::engine( + "The macro engine returned an unknown response.", + )); }; let answer = self.answer(tctx, env, table, question); answers.insert(question.to_string(), answer); } - Err(("The macro asked more than 4096 questions.".into(), None)) + Err(Failure::engine("The macro asked more than 4096 questions.")) } fn answer( @@ -570,9 +769,9 @@ pub(crate) fn answer_input(base_dir: &std::path::Path, question: &str) -> Option None => json!({ "__error": format!("readFile: cannot read `{rest}`.") }), }), "env" => Some(match std::env::var(rest) { - Ok(value) => { - Value::String(crate::source_text::latin1_bytes_to_string(value.into_bytes())) - } + Ok(value) => Value::String(crate::source_text::latin1_bytes_to_string( + value.into_bytes(), + )), Err(_) => Value::Null, }), _ => None, @@ -687,7 +886,8 @@ fn with_discovery( tctx: &mut TypeCheckContext<'_>, f: impl FnOnce(&mut TypeCheckContext<'_>, &mut Discovery) -> R, ) -> Option { - let MacroMode::Discover(mut discovery) = std::mem::replace(&mut tctx.macro_mode, MacroMode::Off) + let MacroMode::Discover(mut discovery) = + std::mem::replace(&mut tctx.macro_mode, MacroMode::Off) else { return None; }; @@ -719,7 +919,12 @@ fn lookup_value( name: &str, ) -> Option<(Path, Arc)> { let longident = longident_of(tctx.arena, name)?; - env.lookup_value_by_lid(&longident, tctx.arena, &mut tctx.persistent_env, tctx.type_ctx) + env.lookup_value_by_lid( + &longident, + tctx.arena, + &mut tctx.persistent_env, + tctx.type_ctx, + ) } /// `Json.encode` → (`Json`, `encode`): the file whose JavaScript the engine @@ -737,12 +942,18 @@ fn literal(arena: &ParseArena, expr: ExprIdx) -> Option { match &expr.pexp_desc { ExpressionDesc::Pexp_constant(constant) => match constant { Constant::String(text) => Some(Value::String(text.semantic(arena).to_string())), - Constant::Integer(text, None) => { - arena.get_string(*text).replace('_', "").parse::().ok().map(Value::from) - } - Constant::Float(text, None) => { - arena.get_string(*text).replace('_', "").parse::().ok().map(Value::from) - } + Constant::Integer(text, None) => arena + .get_string(*text) + .replace('_', "") + .parse::() + .ok() + .map(Value::from), + Constant::Float(text, None) => arena + .get_string(*text) + .replace('_', "") + .parse::() + .ok() + .map(Value::from), _ => None, }, ExpressionDesc::Pexp_construct(lid, args) if arena.expr_list(args.txt).is_empty() => { @@ -772,7 +983,10 @@ fn literal(arena: &ParseArena, expr: ExprIdx) -> Option { if field.opt { return None; } - object.insert(arena.get_string(*name).to_string(), literal(arena, field.expr)?); + object.insert( + arena.get_string(*name).to_string(), + literal(arena, field.expr)?, + ); } Some(Value::Object(object)) } @@ -781,7 +995,11 @@ fn literal(arena: &ParseArena, expr: ExprIdx) -> Option { } /// The argument expressions of `%M.f(a, b)`. -fn payload_expressions(arena: &ParseArena, payload: &Payload, arity: usize) -> Result, String> { +fn payload_expressions( + arena: &ParseArena, + payload: &Payload, + arity: usize, +) -> Result, String> { let Payload::PStr(items) = payload else { return Err("The arguments of a macro are expressions here.".into()); }; @@ -792,7 +1010,9 @@ fn payload_expressions(arena: &ParseArena, payload: &Payload, arity: usize) -> R return Err("The arguments of a macro are expressions here.".into()); }; match &arena.get_expr(eval.0).pexp_desc { - ExpressionDesc::Pexp_tuple(elements) if arity != 1 => Ok(arena.expr_list(*elements).to_vec()), + ExpressionDesc::Pexp_tuple(elements) if arity != 1 => { + Ok(arena.expr_list(*elements).to_vec()) + } _ => Ok(vec![eval.0]), } } @@ -826,12 +1046,15 @@ fn call_arguments( let at = range(tctx.arena, expr.pexp_loc); match kind { ParamKind::Code => { - let mut code = json!({ "c": discovery.text.slice(at.0, at.1) }); + let mut code = + json!({ "c": discovery.text.slice(at.0, at.1), "$o": table.origin(at) }); // The type as far as it is known here. An argument that // does not type check on its own has none. let ctx = tctx.type_ctx; let expected = ctx.new_var(None); - if let Ok(typed) = crate::types::typecore::type_expect(tctx, env, expr, expected, None) { + if let Ok(typed) = + crate::types::typecore::type_expect(tctx, env, expr, expected, None) + { code["t"] = reflect::type_ref(ctx, table, typed.exp_type); } args.push(code); @@ -905,7 +1128,7 @@ fn run_call( name: &str, args: Result, String>, expected: Option, -) -> Option { +) -> Option { let args = match args { Ok(args) => args, Err(message) => { @@ -923,13 +1146,23 @@ fn run_call( }); match discovery.run(tctx, env, table, request) { Ok(code) => Some(code), - Err((message, _offset)) => { - discovery.error(at, format!("{name}: {message}")); + Err(failure) => { + discovery.error(at, failure.report(name)); None } } } +/// `(code)`: generated code where an expression, a pattern or a type is +/// expected. +fn parenthesized(code: Code) -> Vec { + vec![ + Segment::Text("(".into()), + Segment::Code(code), + Segment::Text(")".into()), + ] +} + /// `%name(...)` where an expression is expected. `None`: not a macro, the /// type checker handles the extension as before. pub(crate) fn expression_extension( @@ -949,7 +1182,11 @@ pub(crate) fn expression_extension( } else if is_hole { fail(tctx, loc, HOLE_OUTSIDE_QUOTE) } else { - fail(tctx, loc, format!("The quote `%{name}` needs a payload: `%{name}(...)`.")) + fail( + tctx, + loc, + format!("The quote `%{name}` needs a payload: `%{name}(...)`."), + ) })); } if name == "comptime" { @@ -974,14 +1211,26 @@ pub(crate) fn expression_extension( return Some(Err(fail( tctx, loc, - format!("The macro `{name}` does not return an expression, so it cannot be used as one."), + format!( + "The macro `{name}` does not return an expression, so it cannot be used as one." + ), ))); } let mut table = TypeTable::default(); with_discovery(tctx, |tctx, discovery| { - let args = call_arguments(tctx, env, discovery, &mut table, &name, &signature, &extension.1); + let args = call_arguments( + tctx, + env, + discovery, + &mut table, + &name, + &signature, + &extension.1, + ); if let Some(code) = run_call(tctx, env, discovery, &mut table, at, &name, args, None) { - discovery.edits.push(Edit::replace(at.0, at.1, format!("({code})"))); + discovery + .edits + .push(Edit::with(at.0, at.1, parenthesized(code))); } }); // Type the call as its declared result, `code` as `string`, so @@ -1014,7 +1263,13 @@ fn comptime( } let expr_idx = match payload_expressions(tctx.arena, &extension.1, 1) { Ok(exprs) if exprs.len() == 1 => exprs[0], - _ => return Err(fail(tctx, loc, "%comptime takes one expression: `%comptime(expr)`.")), + _ => { + return Err(fail( + tctx, + loc, + "%comptime takes one expression: `%comptime(expr)`.", + )); + } }; let expr = tctx.arena.get_expr(expr_idx); let typed = crate::types::typecore::type_expect(tctx, env, expr, expected_ty, None)?; @@ -1096,7 +1351,9 @@ pub(crate) fn generic_use( let Some(erased) = erased_type(ctx, instance) else { return Err(error_at( loc, - format!("`{name}` is marked @generic, so it has to be a function that returns `code<...>`."), + format!( + "`{name}` is marked @generic, so it has to be a function that returns `code<...>`." + ), )); }; let (signature, _, _) = signature(ctx, instance); @@ -1177,7 +1434,11 @@ pub(crate) fn begin_item(tctx: &mut TypeCheckContext<'_>, item: &ParsedStructure Some(next) => next.saturating_sub(GROUP_SEPARATOR.len() as u32), None => end, }; - Some((arena.get_string(name.txt).to_string(), starts[index], function_end)) + Some(( + arena.get_string(name.txt).to_string(), + starts[index], + function_end, + )) }) .collect(); let ordinal = discovery.text.origin(start); @@ -1240,7 +1501,11 @@ pub(crate) fn end_item(tctx: &mut TypeCheckContext<'_>, ok: bool) { }); } -fn resolve_generic(tctx: &mut TypeCheckContext<'_>, discovery: &mut Discovery, generic: PendingGeneric) { +fn resolve_generic( + tctx: &mut TypeCheckContext<'_>, + discovery: &mut Discovery, + generic: PendingGeneric, +) { let ctx = tctx.type_ctx; let full_name = format!("{}.{}", generic.module, generic.name); let TypeDesc::Tarrow { args, ret } = &*ctx.get_desc(ctx.repr(generic.ty)) else { @@ -1313,7 +1578,9 @@ fn resolve_generic(tctx: &mut TypeCheckContext<'_>, discovery: &mut Discovery, g _ => { discovery.error( generic.callee, - format!("`{full_name}`: a @generic takes `code<...>` and compile-time values only."), + format!( + "`{full_name}`: a @generic takes `code<...>` and compile-time values only." + ), ); return; } @@ -1321,6 +1588,12 @@ fn resolve_generic(tctx: &mut TypeCheckContext<'_>, discovery: &mut Discovery, g } let has_values = generic.signature.params.contains(&ParamKind::Value); let result = reflect::print_type(ctx, ret); + // What an instance is of, for a diagnostic in its code. + let described: Vec = if name_parts.is_empty() { + vec![result.clone()] + } else { + name_parts.clone() + }; let key = format!("{full_name}({})->{result}", key_parts.join(",")); let ordinal = discovery.text.origin(discovery.item_start); @@ -1337,36 +1610,43 @@ fn resolve_generic(tctx: &mut TypeCheckContext<'_>, discovery: &mut Discovery, g }); let body = match discovery.run(tctx, &generic.env, &mut table, request) { Ok(body) => body, - Err((message, _)) => { - discovery.error(generic.callee, format!("{full_name}: {message}")); + Err(failure) => { + discovery.error(generic.callee, failure.report(&full_name)); return; } }; if generic.signature.open_result || name_parts.is_empty() { name_parts.push(result.clone()); } - let name = discovery - .instances - .add(key, &instance_name(&generic.name, &name_parts), ordinal); + let name = + discovery + .instances + .add(key, &instance_name(&generic.name, &name_parts), ordinal); let annotation = if result.contains("'_") || reflect::is_unknown(ctx, ret) { String::new() } else { format!(": {result}") }; - discovery.add_instance(format!( - "{name} = ({}){annotation} => {body}", - params - .iter() - .map(|(param, ty)| { - // A parameter the macro's code does not mention. - let used = body - .split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '$')) - .any(|word| word == param); - format!("{}: {ty}", if used { param } else { "_" }) - }) - .collect::>() - .join(", ") - )); + let params = params + .iter() + .map(|(param, ty)| { + // A parameter the macro's code does not mention. + let used = body + .text + .split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '$')) + .any(|word| word == param); + format!("{}: {ty}", if used { param } else { "_" }) + }) + .collect::>() + .join(", "); + let description = format!("`{full_name}` for `{}`", described.join(", ")); + discovery.add_instance(Function { + generated_for: Some((generic.callee, description.into())), + segments: vec![ + Segment::Text(format!("{name} = ({params}){annotation} => ")), + Segment::Code(body), + ], + }); name } }; @@ -1382,7 +1662,9 @@ fn resolve_generic(tctx: &mut TypeCheckContext<'_>, discovery: &mut Discovery, g )), None => discovery.error( generic.callee, - format!("`{full_name}` takes compile-time values, so it has to be called directly."), + format!( + "`{full_name}` takes compile-time values, so it has to be called directly." + ), ), } } else { @@ -1429,15 +1711,27 @@ pub(crate) fn pattern_extension( return Some(fail( tctx, loc, - format!("The macro `{name}` does not return a pattern (`pat`), so it cannot be used as one."), + format!( + "The macro `{name}` does not return a pattern (`pat`), so it cannot be used as one." + ), )); } let at = range(tctx.arena, loc); let mut table = TypeTable::default(); with_discovery(tctx, |tctx, discovery| { - let args = call_arguments(tctx, env, discovery, &mut table, &name, &signature, &extension.1); + let args = call_arguments( + tctx, + env, + discovery, + &mut table, + &name, + &signature, + &extension.1, + ); if let Some(code) = run_call(tctx, env, discovery, &mut table, at, &name, args, None) { - discovery.edits.push(Edit::replace(at.0, at.1, format!("({code})"))); + discovery + .edits + .push(Edit::with(at.0, at.1, parenthesized(code))); } }); Some(pending(tctx, loc)) @@ -1480,7 +1774,9 @@ pub(crate) fn type_extension( let arena = tctx.arena; let types: Vec = match &extension.1 { Payload::PTyp(idx) => match &arena.get_core_type(*idx).ptyp_desc { - crate::parser::ast::CoreTypeDesc::Ptyp_tuple(elements) if signature.params.len() != 1 => { + crate::parser::ast::CoreTypeDesc::Ptyp_tuple(elements) + if signature.params.len() != 1 => + { arena.type_list(*elements).to_vec() } _ => vec![*idx], @@ -1503,14 +1799,19 @@ pub(crate) fn type_extension( let styp = arena.get_core_type(*idx); let type_range = range(arena, styp.ptyp_loc); if *kind != ParamKind::Typ { - args = Err(format!("The macro `{name}` takes arguments that are not types.")); + args = Err(format!( + "The macro `{name}` takes arguments that are not types." + )); break; } match crate::types::typecore::transl_type(tctx, env, styp) { Ok((_, ty)) => { let mut value = reflect::type_ref(ctx, &mut table, ty); + value["$o"] = json!(table.origin(type_range)); with_discovery(tctx, |_, discovery| { - value["c"] = Value::String(discovery.text.slice(type_range.0, type_range.1).to_string()); + value["c"] = Value::String( + discovery.text.slice(type_range.0, type_range.1).to_string(), + ); }); values.push(value); } @@ -1522,12 +1823,12 @@ pub(crate) fn type_extension( if let Some(code) = run_call(tctx, env, discovery, &mut table, at, &name, args, None) { // A record or variant body is the right-hand side of a type // declaration, which takes no parentheses. - let text = if code.trim_start().starts_with(['{', '|']) { - code + let segments = if code.text.trim_start().starts_with(['{', '|']) { + vec![Segment::Code(code)] } else { - format!("({code})") + parenthesized(code) }; - discovery.edits.push(Edit::replace(at.0, at.1, text)); + discovery.edits.push(Edit::with(at.0, at.1, segments)); } }); Some(pending(tctx, loc)) @@ -1559,20 +1860,34 @@ pub(crate) fn declarations_extension( return Some(fail( tctx, loc, - format!("The macro `{name}` does not return declarations (`decls`), so it cannot be used here."), + format!( + "The macro `{name}` does not return declarations (`decls`), so it cannot be used here." + ), )); } let at = range(tctx.arena, loc); let mut table = TypeTable::default(); with_discovery(tctx, |tctx, discovery| { - let args = call_arguments(tctx, env, discovery, &mut table, &name, &signature, &extension.1); + let args = call_arguments( + tctx, + env, + discovery, + &mut table, + &name, + &signature, + &extension.1, + ); if let Some(code) = run_call(tctx, env, discovery, &mut table, at, &name, args, None) { - let text = if as_module { - format!("{{\n{code}\n}}") + let segments = if as_module { + vec![ + Segment::Text("{\n".into()), + Segment::Code(code), + Segment::Text("\n}".into()), + ] } else { - code + vec![Segment::Code(code)] }; - discovery.edits.push(Edit::replace(at.0, at.1, text)); + discovery.edits.push(Edit::with(at.0, at.1, segments)); } }); Some(pending(tctx, loc)) @@ -1607,9 +1922,11 @@ pub(crate) fn has_macro_attribute( fn retire_attribute(discovery: &mut Discovery, arena: &ParseArena, name: &str, loc: LocIdx) { let at = range(arena, loc); let text = discovery.text.slice(at.0, at.1).to_string(); - discovery - .edits - .push(Edit::replace(at.0, at.1, text.replacen(name, &format!("expanded.{name}"), 1))); + discovery.edits.push(Edit::replace( + at.0, + at.1, + text.replacen(name, &format!("expanded.{name}"), 1), + )); } /// `@M.f let x = ...`: the macro gets the binding as syntax and its result @@ -1639,7 +1956,11 @@ pub(crate) fn value_item( return Some(required(tctx, loc)); } if bindings.len() != 1 { - return Some(fail(tctx, attr_loc, format!("`@{name}` works on a `let` with one binding."))); + return Some(fail( + tctx, + attr_loc, + format!("`@{name}` works on a `let` with one binding."), + )); } let ctx = tctx.type_ctx; let (signature, _, _) = signature(ctx, crate::types::instance(ctx, desc.val_type)); @@ -1647,7 +1968,9 @@ pub(crate) fn value_item( return Some(fail( tctx, attr_loc, - format!("A macro on a `let` has the type `Decl.value => decls`, and `{name}` does not."), + format!( + "A macro on a `let` has the type `Decl.value => decls`, and `{name}` does not." + ), )); } let pat = arena.get_pat(binding.pvb_pat); @@ -1662,11 +1985,13 @@ pub(crate) fn value_item( with_discovery(tctx, |tctx, discovery| { let args = Ok(vec![json!({ "name": bound, - "pat": { "c": discovery.text.slice(pat_range.0, pat_range.1) }, - "expr": { "c": discovery.text.slice(expr_range.0, expr_range.1) }, + "pat": { "c": discovery.text.slice(pat_range.0, pat_range.1), "$o": table.origin(pat_range) }, + "expr": { "c": discovery.text.slice(expr_range.0, expr_range.1), "$o": table.origin(expr_range) }, })]); if let Some(code) = run_call(tctx, env, discovery, &mut table, at, &name, args, None) { - discovery.edits.push(Edit::replace(at.0, at.1, code)); + discovery + .edits + .push(Edit::with(at.0, at.1, vec![Segment::Code(code)])); } }); Some(pending(tctx, loc)) @@ -1752,11 +2077,21 @@ pub(crate) fn type_item(tctx: &mut TypeCheckContext<'_>, env: &Env, item: &Parse .map(|attr| json!({ "name": arena.get_string(attr.0.txt) })) .collect(); with_discovery(tctx, |tctx, discovery| { - let args = Ok(vec![json!({ "name": type_name, "typ": type_value, "attrs": attrs })]); - if let Some(code) = run_call(tctx, env, discovery, &mut table, at, &name, args, None) { - discovery - .edits - .push(Edit::insert(item_range.1, format!("\n{code}"))); + let args = Ok(vec![ + json!({ "name": type_name, "typ": type_value, "attrs": attrs }), + ]); + if let Some(code) = + run_call(tctx, env, discovery, &mut table, at, &name, args, None) + { + discovery.edits.push(Edit::with( + item_range.1, + item_range.1, + vec![ + Segment::For(at.0, at.1, None), + Segment::Text("\n".into()), + Segment::Code(code), + ], + )); retire_attribute(discovery, arena, &name, attr_loc); } }); diff --git a/compiler-rust/src/macros/edit.rs b/compiler-rust/src/macros/edit.rs index 93fa64e050..fd29437bae 100644 --- a/compiler-rust/src/macros/edit.rs +++ b/compiler-rust/src/macros/edit.rs @@ -2,21 +2,73 @@ //! //! Macro expansion edits the source text of a file: a macro call is replaced //! by the code the macro returned, a generated function is inserted before -//! the item that needs it. Every character of the edited text remembers the -//! offset it has in the file as written, so that diagnostics, source maps and -//! editor tooling keep pointing at what the person wrote. Generated text -//! takes the offset of the place it was generated for. +//! the item that needs it. Every character of the edited text remembers +//! where it comes from, so that diagnostics, source maps and editor tooling +//! keep pointing at what the person wrote: +//! +//! - a character of the file as written has its offset in that file; +//! - a generated character has the macro use it was generated for, and, when +//! it was written in a quote, the file, line and column of that quote. //! //! Offsets are in characters, like `Position::cnum`. +use std::sync::Arc; + +/// Code a macro returned: its text, and which parts of it are text from +/// elsewhere. +#[derive(Debug, Clone, Default)] +pub struct Code { + pub text: String, + /// In order of `start`, not overlapping. + pub spans: Vec, +} + +/// The characters `start..start + len` of a [`Code`]. +#[derive(Debug, Clone)] +pub struct Span { + pub start: u32, + pub len: u32, + pub from: SpanSource, +} + +#[derive(Debug, Clone)] +pub enum SpanSource { + /// The characters at this offset of the text being edited: an argument + /// of the macro that it put in its result. + Text(u32), + /// A quote, `%code(...)`, in the macro's file. `line` counts from 1, + /// `column` from 0. + Quote { + file: Arc, + line: u32, + column: u32, + }, +} + +impl Code { + pub fn plain(text: impl Into) -> Self { + Code { + text: text.into(), + spans: Vec::new(), + } + } +} + /// One part of an edit's replacement. #[derive(Debug, Clone)] pub enum Segment { /// Generated text. Text(String), - /// The characters `start..end` of the text being edited, kept with their - /// origins. + /// Generated text with what is known of where it comes from. + Code(Code), + /// The characters `start..end` of the text being edited, kept with + /// where they come from. Copy(u32, u32), + /// The generated text that follows in this edit was generated for the + /// macro use at `start..end` of the text being edited. Without it, it + /// was generated for what the edit replaces. With a description, a + /// diagnostic in that text says what it is: "`Json.encode` for `user`". + For(u32, u32, Option>), } /// Replace the characters `start..end` by `segments`. An insertion has @@ -26,20 +78,66 @@ pub struct Edit { pub start: u32, pub end: u32, pub segments: Vec, + /// The generated text is the compiler's own rewriting (a lowered quote): + /// a diagnostic in it does not show it. + pub internal: bool, } impl Edit { pub fn replace(start: u32, end: u32, text: impl Into) -> Self { + Edit::with(start, end, vec![Segment::Text(text.into())]) + } + + pub fn insert(at: u32, text: impl Into) -> Self { + Edit::replace(at, at, text) + } + + pub fn with(start: u32, end: u32, segments: Vec) -> Self { Edit { start, end, - segments: vec![Segment::Text(text.into())], + segments, + internal: false, } } +} - pub fn insert(at: u32, text: impl Into) -> Self { - Edit::replace(at, at, text) - } +/// The macro use some text was generated for: its range in the source as +/// written. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct Use { + start: u32, + end: u32, + /// Whether a diagnostic in the generated text shows that text. + shown: bool, + /// Index + 1 into `descriptions`; 0 for none. + description: u32, +} + +/// Where a character comes from, besides its offset in the source. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +struct Mark { + /// Index + 1 into `uses`; 0 for a character of the source as written. + use_id: u32, + /// Index + 1 into `files`; 0 for a character that is not from a quote. + file: u32, + line: u32, + column: u32, +} + +/// Where a generated character comes from. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Generated { + /// The macro use, in the source as written. + pub use_start: u32, + pub use_end: u32, + /// Whether a diagnostic shows the generated text. + pub shown: bool, + /// What the text is, when it is more than the result of the use. + pub description: Option>, + /// The quote the character was written in: file, line (from 1) and + /// column (from 0). + pub quote: Option<(Arc, u32, u32)>, } /// A file's text during macro expansion. @@ -48,8 +146,14 @@ pub struct SourceText { text: String, /// Byte offset of each character, and of the end of the text. char_to_byte: Vec, - /// Offset in the original text of each character, and of the end. + /// Offset in the original text of each character, and of the end. For a + /// generated character: where its macro use starts. origin: Vec, + /// Per character, and for the end. + marks: Vec, + uses: Vec, + files: Vec>, + descriptions: Vec>, /// Whether any edit was applied. edited: bool, } @@ -62,6 +166,10 @@ impl SourceText { text: text.to_string(), char_to_byte, origin: (0..=chars).collect(), + marks: vec![Mark::default(); chars as usize + 1], + uses: Vec::new(), + files: Vec::new(), + descriptions: Vec::new(), edited: false, } } @@ -83,58 +191,326 @@ impl SourceText { let len = self.len(); let start = start.min(len); let end = end.clamp(start, len); - &self.text[self.char_to_byte[start as usize] as usize..self.char_to_byte[end as usize] as usize] + &self.text + [self.char_to_byte[start as usize] as usize..self.char_to_byte[end as usize] as usize] } - /// The offset in the original text of the character at `offset`. + /// The offset in the original text of the character at `offset`: for a + /// generated character, the start of its macro use. pub fn origin(&self, offset: u32) -> u32 { self.origin[(offset as usize).min(self.origin.len() - 1)] } + /// The offset in the original text where a range that ends before + /// `offset` ends: for a generated character, the end of its macro use. + pub fn origin_end(&self, offset: u32) -> u32 { + if offset == 0 { + return self.origin(0); + } + let last = (offset as usize - 1).min(self.origin.len() - 1); + match self.marks[last].use_id { + 0 => self.origin[last] + 1, + id => self.uses[id as usize - 1].end, + } + } + + /// Where the character at `offset` comes from, if it is generated. + pub fn generated(&self, offset: u32) -> Option { + let mark = self.marks[(offset as usize).min(self.marks.len() - 1)]; + if mark.use_id == 0 { + return None; + } + let used = self.uses[mark.use_id as usize - 1]; + Some(Generated { + use_start: used.start, + use_end: used.end, + shown: used.shown, + description: (used.description != 0) + .then(|| self.descriptions[used.description as usize - 1].clone()), + quote: (mark.file != 0).then(|| { + ( + self.files[mark.file as usize - 1].clone(), + mark.line, + mark.column, + ) + }), + }) + } + + /// Where the characters `from..to` are in the original text. A range + /// that starts or ends in generated code covers the macro use the code + /// was generated for. + pub fn original_range(&self, from: u32, to: u32) -> (u32, u32) { + if to <= from { + let at = self.origin(from); + return (at, at); + } + let first = self.generated(from); + let last = self.generated(to - 1); + let mut range = (self.origin(from), self.origin_end(to)); + // The rest of a range that is partly in generated code is an + // argument of the same use. + if let Some(last) = &last + && (first.is_some() || (last.use_start..last.use_end).contains(&range.0)) + { + range.0 = last.use_start; + } + if let Some(first) = &first + && (last.is_some() + || (first.use_start..first.use_end).contains(&range.1.saturating_sub(1))) + { + range.1 = first.use_end; + } + (range.0, range.1.max(range.0)) + } + + /// The generated code that the characters `from..to` are in: `None` for + /// a range that starts and ends in the source as written, also when it + /// has a macro use inside it, and for the compiler's own rewriting. + pub fn generated_code(&self, from: u32, to: u32) -> Option { + let to = to.clamp(from + 1, self.len().max(from + 1)); + let shown = |offset: u32| self.generated(offset).filter(|generated| generated.shown); + let description = shown(from).or_else(|| shown(to - 1))?.description; + let mut quote: Option = None; + for offset in from..to { + let Some((file, line, column)) = + self.generated(offset).and_then(|generated| generated.quote) + else { + continue; + }; + match &mut quote { + None => { + quote = Some(QuoteRange { + file, + start: (line, column), + end: (line, column + 1), + }); + } + Some(range) if range.file == file && (line, column) >= range.start => { + range.end = (line, column + 1); + } + Some(_) => {} + } + } + Some(GeneratedCode { + start: from, + end: to, + description, + quote, + }) + } + /// Apply `edits`. Of two edits that overlap, the one that starts first /// wins (the outer of two nested macro calls); the next pass finds what /// the other covered again. Insertions at one offset keep their order. pub fn apply(&self, mut edits: Vec) -> SourceText { - edits.sort_by_key(|edit| (edit.start, edit.end != edit.start, std::cmp::Reverse(edit.end))); + edits.sort_by_key(|edit| { + ( + edit.start, + edit.end != edit.start, + std::cmp::Reverse(edit.end), + ) + }); let len = self.len(); - let mut text = String::with_capacity(self.text.len() + 256); - let mut origin = Vec::with_capacity(self.origin.len() + 256); + let mut out = Builder { + text: String::with_capacity(self.text.len() + 256), + origin: Vec::with_capacity(self.origin.len() + 256), + marks: Vec::with_capacity(self.marks.len() + 256), + uses: self.uses.clone(), + files: self.files.clone(), + descriptions: self.descriptions.clone(), + }; let mut cursor = 0u32; for edit in &edits { if edit.start < cursor || edit.end > len || edit.end < edit.start { continue; } - self.copy_into(cursor, edit.start, &mut text, &mut origin); - let generated_origin = self.origin(edit.start); + self.copy_into(cursor, edit.start, &mut out); + let mut use_id = self.use_of(&mut out, edit.start, edit.end, !edit.internal, None); for segment in &edit.segments { match segment { - Segment::Text(generated) => { - text.push_str(generated); - origin.extend(generated.chars().map(|_| generated_origin)); + Segment::Text(generated) => out.generate(generated, use_id, Mark::default()), + Segment::Code(code) => self.code_into(code, use_id, &mut out), + Segment::Copy(start, end) => self.copy_into(*start, *end, &mut out), + Segment::For(start, end, description) => { + use_id = self.use_of( + &mut out, + *start, + *end, + !edit.internal, + description.as_ref(), + ); } - Segment::Copy(start, end) => self.copy_into(*start, *end, &mut text, &mut origin), } } cursor = edit.end; } - self.copy_into(cursor, len, &mut text, &mut origin); - origin.push(self.origin(len)); - let char_to_byte = char_offsets(&text); - debug_assert_eq!(char_to_byte.len(), origin.len()); + self.copy_into(cursor, len, &mut out); + out.origin.push(self.origin(len)); + out.marks.push(Mark::default()); + let char_to_byte = char_offsets(&out.text); + debug_assert_eq!(char_to_byte.len(), out.origin.len()); + debug_assert_eq!(char_to_byte.len(), out.marks.len()); SourceText { - text, + text: out.text, char_to_byte, - origin, + origin: out.origin, + marks: out.marks, + uses: out.uses, + files: out.files, + descriptions: out.descriptions, edited: true, } } - fn copy_into(&self, start: u32, end: u32, text: &mut String, origin: &mut Vec) { + /// The macro use that text put in place of `start..end` is generated + /// for. Code generated inside generated code belongs to the use that + /// generated the outer code: that is the one in the source. + fn use_of( + &self, + out: &mut Builder, + start: u32, + end: u32, + shown: bool, + description: Option<&Arc>, + ) -> u32 { + let description = description.map(|description| out.description_id(description)); + let inherited = self.marks[(start as usize).min(self.marks.len() - 1)].use_id; + if inherited != 0 && start < self.len() { + let outer = out.uses[inherited as usize - 1]; + return out.use_id(Use { + shown, + description: description.unwrap_or(outer.description), + ..outer + }); + } + let use_start = self.origin(start); + let use_end = if end > start { + self.origin_end(end) + } else { + use_start + }; + out.use_id(Use { + start: use_start, + end: use_end.max(use_start), + shown, + description: description.unwrap_or(0), + }) + } + + fn copy_into(&self, start: u32, end: u32, out: &mut Builder) { if start >= end { return; } - text.push_str(self.slice(start, end)); - origin.extend_from_slice(&self.origin[start as usize..end as usize]); + out.text.push_str(self.slice(start, end)); + out.origin + .extend_from_slice(&self.origin[start as usize..end as usize]); + out.marks + .extend_from_slice(&self.marks[start as usize..end as usize]); + } + + fn code_into(&self, code: &Code, use_id: u32, out: &mut Builder) { + let chars = char_offsets(&code.text); + let len = chars.len() as u32 - 1; + let slice = |start: u32, end: u32| { + &code.text[chars[start as usize] as usize..chars[end as usize] as usize] + }; + let mut cursor = 0u32; + for span in &code.spans { + let end = span.start.saturating_add(span.len); + if span.start < cursor || end > len { + continue; + } + out.generate(slice(cursor, span.start), use_id, Mark::default()); + let text = slice(span.start, end); + match &span.from { + // The argument as the person wrote it: its characters keep + // their place in the source. + SpanSource::Text(at) if self.slice(*at, at + span.len) == text => { + self.copy_into(*at, at + span.len, out); + } + SpanSource::Text(_) => out.generate(text, use_id, Mark::default()), + SpanSource::Quote { file, line, column } => { + let file = out.file_id(file); + out.generate( + text, + use_id, + Mark { + use_id, + file, + line: *line, + column: *column, + }, + ); + } + } + cursor = end; + } + out.generate(slice(cursor, len), use_id, Mark::default()); + } +} + +/// The text an [`SourceText::apply`] builds. +struct Builder { + text: String, + origin: Vec, + marks: Vec, + uses: Vec, + files: Vec>, + descriptions: Vec>, +} + +impl Builder { + fn description_id(&mut self, description: &Arc) -> u32 { + if let Some(index) = self + .descriptions + .iter() + .position(|known| known == description) + { + return index as u32 + 1; + } + self.descriptions.push(description.clone()); + self.descriptions.len() as u32 + } + + fn use_id(&mut self, used: Use) -> u32 { + // A use is looked up among the latest: an edit and the ones after it. + if let Some(index) = self.uses.iter().rposition(|known| *known == used) { + return index as u32 + 1; + } + self.uses.push(used); + self.uses.len() as u32 + } + + fn file_id(&mut self, file: &Arc) -> u32 { + if let Some(index) = self.files.iter().position(|known| known == file) { + return index as u32 + 1; + } + self.files.push(file.clone()); + self.files.len() as u32 + } + + /// Add generated text. `first` is the mark of its first character when + /// the text is from a quote: line and column advance from there. + fn generate(&mut self, text: &str, use_id: u32, first: Mark) { + if text.is_empty() { + return; + } + let origin = self.uses[use_id as usize - 1].start; + let mut mark = Mark { use_id, ..first }; + for ch in text.chars() { + self.origin.push(origin); + self.marks.push(mark); + if mark.file != 0 { + if ch == '\n' { + mark.line += 1; + mark.column = 0; + } else { + mark.column += 1; + } + } + } + self.text.push_str(text); } } @@ -148,6 +524,37 @@ pub struct Expansion { pub offsets: Vec, } +/// Generated code a diagnostic is in. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct GeneratedCode { + /// Its characters in the expanded text. + pub start: u32, + pub end: u32, + /// What the code is, when it is more than the result of the macro use. + pub description: Option>, + /// The part of a quote it was written in, when it is from one. + pub quote: Option, +} + +/// A range of a macro's file. Lines count from 1, columns from 0; `end` is +/// after the last character. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct QuoteRange { + pub file: Arc, + pub start: (u32, u32), + pub end: (u32, u32), +} + +impl Expansion { + /// The generated code that a location with the positions `start` and + /// `end` (by index) is in. + pub fn generated_code(&self, start: u32, end: u32) -> Option { + let from = *self.offsets.get(start as usize)?; + let to = *self.offsets.get(end as usize)?; + self.text.generated_code(from, to) + } +} + fn char_offsets(text: &str) -> Vec { let mut offsets: Vec = text.char_indices().map(|(byte, _)| byte as u32).collect(); offsets.push(text.len() as u32); @@ -171,6 +578,11 @@ impl LineTable { LineTable { starts } } + /// The offset of the first character of the 1-based `line`. + pub fn line_start(&self, line: u32) -> Option { + self.starts.get((line as usize).checked_sub(1)?).copied() + } + /// The 1-based line of `offset` and the offset of that line's start. pub fn line_of(&self, offset: u32) -> (i32, u32) { let line = match self.starts.binary_search(&offset) { @@ -214,15 +626,15 @@ mod tests { #[test] fn copies_keep_their_origin_inside_generated_text() { let source = SourceText::new("%code(a + ${b})"); - let edited = source.apply(vec![Edit { - start: 0, - end: 15, - segments: vec![ + let edited = source.apply(vec![Edit::with( + 0, + 15, + vec![ Segment::Text("q([".into()), Segment::Copy(12, 13), Segment::Text("])".into()), ], - }]); + )]); assert_eq!(edited.text(), "q([b])"); assert_eq!(edited.origin(3), 12); assert_eq!(edited.origin(0), 0); @@ -242,4 +654,89 @@ mod tests { assert_eq!(lines.line_of(3), (2, 3)); assert_eq!(lines.line_of(4), (2, 3)); } + + #[test] + fn generated_text_knows_its_use_and_its_quote() { + let source = SourceText::new("let a = %M.f(x + 1)\nlet b = 2\n"); + // The macro returned `{\n (x + 1) * 2\n}`: the argument, in a quote. + let code = Code { + text: "{\n (x + 1) * 2\n}".into(), + spans: vec![ + Span { + start: 0, + len: 5, + from: SpanSource::Quote { + file: "M.res".into(), + line: 4, + column: 8, + }, + }, + Span { + start: 5, + len: 5, + from: SpanSource::Text(13), + }, + Span { + start: 10, + len: 7, + from: SpanSource::Quote { + file: "M.res".into(), + line: 5, + column: 8, + }, + }, + ], + }; + let edited = source.apply(vec![Edit::with(8, 19, vec![Segment::Code(code)])]); + assert_eq!(edited.text(), "let a = {\n (x + 1) * 2\n}\nlet b = 2\n"); + // The argument is the person's own text. + assert_eq!(edited.slice(13, 18), "x + 1"); + assert_eq!(edited.origin(13), 13); + assert_eq!(edited.generated(13), None); + // The rest is generated for the whole use. + let brace = edited.generated(8).unwrap(); + assert_eq!((brace.use_start, brace.use_end), (8, 19)); + assert_eq!(brace.quote, Some(("M.res".into(), 4, 8))); + // After the newline in the quote: the next line, column 2. + assert_eq!( + edited.generated(12).unwrap().quote, + Some(("M.res".into(), 5, 2)) + ); + assert_eq!( + edited.generated(19).unwrap().quote, + Some(("M.res".into(), 5, 9)) + ); + // A range that ends in generated text ends where the use ends. + assert_eq!(edited.origin_end(22), 19); + assert_eq!(edited.origin_end(4), 4); + // What follows is the source as written. + assert_eq!(edited.slice(26, 31), "let b"); + assert_eq!(edited.origin(26), 20); + + // Code generated inside generated code belongs to the outer use. + let again = edited.apply(vec![Edit::replace(8, 9, "(")]); + let inner = again.generated(8).unwrap(); + assert_eq!((inner.use_start, inner.use_end), (8, 19)); + } + + #[test] + fn an_insertion_is_generated_for_the_use_it_names() { + let source = SourceText::new("let j = Json.encode(alice)\n"); + let edited = source.apply(vec![Edit::with( + 0, + 0, + vec![ + Segment::For(8, 19, Some("`Json.encode` for `user`".into())), + Segment::Text("let rec f = 1\n".into()), + ], + )]); + let function = edited.generated(4).unwrap(); + assert_eq!((function.use_start, function.use_end), (8, 19)); + assert_eq!( + function.description.as_deref(), + Some("`Json.encode` for `user`") + ); + assert_eq!(edited.origin(4), 8); + assert_eq!(edited.origin(14), 0); + } } diff --git a/compiler-rust/src/macros/expand.rs b/compiler-rust/src/macros/expand.rs index 996113d92a..c8562b81ff 100644 --- a/compiler-rust/src/macros/expand.rs +++ b/compiler-rust/src/macros/expand.rs @@ -34,36 +34,86 @@ use super::quote; const MAX_PASSES: usize = 64; /// A diagnostic at characters `start..end` of `text`, reported against the -/// source as written. +/// source as written. One in generated code is reported at the macro use, +/// with a note about the generated code; `in_expansion` asks for that note +/// wherever the diagnostic is. fn diagnostic( + intro: &str, original: &str, text: &SourceText, filename: &str, - start: u32, - end: u32, + (start, end): (u32, u32), + in_expansion: bool, + message: &str, +) -> anyhow::Error { + let generated = text.generated_code(start, end).or_else(|| { + (in_expansion && text.is_edited()).then(|| super::edit::GeneratedCode { + start, + end: end.max(start + 1), + description: None, + quote: None, + }) + }); + let note = generated + .map(|generated| { + super::report::generated_code_note( + text, + &generated, + false, + driver::read_in_process_source, + ) + }) + .unwrap_or_default(); + let (start, end) = text.original_range(start, end.max(start + 1)); + original_diagnostic(intro, original, filename, (start, end), ¬e, message) +} + +/// A diagnostic at characters `start..end` of the source as written. +/// `note` goes between the code frame and the message. +fn original_diagnostic( + intro: &str, + original: &str, + filename: &str, + (start, end): (u32, u32), + note: &str, message: &str, ) -> anyhow::Error { let lines = LineTable::new(original); - let start = text.origin(start); - let end = text.origin(end).max(start + 1); let position = |offset: u32| { let (line, bol) = lines.line_of(offset); - Position::new(crate::intern::StrIdx::from_raw(0), line, bol as i32, offset as i32) + Position::new( + crate::intern::StrIdx::from_raw(0), + line, + bol as i32, + offset as i32, + ) }; + // Every line of the message is indented like the first. + let mut body = String::from(note.strip_prefix(" ").unwrap_or(note)); + for (index, line) in message.lines().enumerate() { + if index > 0 || !body.is_empty() { + body.push_str(if line.is_empty() { "\n" } else { "\n " }); + } + body.push_str(line); + } + // A note ends with the blank line after its frame. + let body = body.replace("\n\n\n", "\n\n"); UserDiagnostic::new( code_frame::format_error_with_intro( - "We've found a bug for you!", + intro, filename, original, &position(start), - &position(end), - message, + &position(end.max(start + 1)), + &body, ), 2, ) .into() } +const BUG: &str = "We've found a bug for you!"; + /// Expand the macros of a file. Returns the expanded text; it is the source /// unchanged ([`SourceText::is_edited`] false) when the file has a problem /// the ordinary compilation reports better (a syntax error, a type error @@ -78,6 +128,7 @@ pub fn expand_source( ) -> Result { let mut text = Arc::new(SourceText::new(source)); let mut instances = InstanceTable::default(); + let mut unfinished: Option<(u32, u32)> = None; let base_dir = std::path::Path::new(filename) .parent() .map(|dir| dir.to_path_buf()) @@ -90,10 +141,17 @@ pub fn expand_source( if !text.is_edited() { return Ok(SourceText::new(source)); } - return Err(generated_syntax_error(&parser, &text, filename)); + return Err(generated_syntax_error(&parser, &text, source, filename)); } - let quote_edits = quote::lowering_edits(parser.arena(), &structure, &text, module_name); + let quote_edits = quote::lowering_edits( + parser.arena(), + &structure, + &text, + source, + filename, + module_name, + ); if !quote_edits.is_empty() { text = Arc::new(text.apply(quote_edits)); continue; @@ -156,8 +214,18 @@ pub fn expand_source( let mut errors = pass.errors; for site in &pass.comptime { - match evaluate_comptime(site, &opens, filename, module_name, options, registry, &host) { - Ok(literal) => edits.push(Edit::replace(site.start, site.end, format!("({literal})"))), + match evaluate_comptime( + site, + &opens, + filename, + module_name, + options, + registry, + &host, + ) { + Ok(literal) => { + edits.push(Edit::replace(site.start, site.end, format!("({literal})"))) + } Err(message) => errors.push(MacroDiagnostic { start: site.start, end: site.end, @@ -173,31 +241,49 @@ pub fn expand_source( // A type error comes first: the ordinary compilation reports it. (Some(error), Some(failed)) if failed < error.start => Ok(unwrap_text(text)), (Some(error), _) => Err(diagnostic( + BUG, source, &text, filename, - error.start, - error.end, + (error.start, error.end), + false, &error.message, )), (None, _) => Ok(unwrap_text(text)), }; } + // The macro use that is still expanding when the passes run out. + if let Some(edit) = edits + .iter() + .filter(|edit| edit.end > edit.start) + .min_by_key(|edit| edit.start) + { + unfinished = Some(text.original_range(edit.start, edit.end)); + } text = Arc::new(text.apply(edits)); } - Err(UserDiagnostic::new( - format!( - "{filename}: macro expansion did not finish after {MAX_PASSES} passes. A macro probably generates a call to itself.\n" - ), - 2, - ) - .into()) + let message = format!( + "Macro expansion did not finish after {MAX_PASSES} passes.\nA macro probably generates a use of itself." + ); + Err(original_diagnostic( + BUG, + source, + filename, + unfinished.unwrap_or((0, 0)), + "", + &message, + )) } /// Move every position of a parse of the expanded text to where it is in /// the source as written. Generated code takes the position of the macro -/// use it was generated for. -pub fn remap_positions(arena: &mut crate::parse_arena::ParseArena, text: &SourceText, original: &str) { +/// use it was generated for: a location that starts or ends in generated +/// code covers that use. +pub fn remap_positions( + arena: &mut crate::parse_arena::ParseArena, + text: &SourceText, + original: &str, +) { let lines = LineTable::new(original); // An ordinary parse counts a column in UTF-16 code units; only text // with characters outside the BMP makes that differ from characters. @@ -205,13 +291,7 @@ pub fn remap_positions(arena: &mut crate::parse_arena::ParseArena, text: &Source .chars() .any(|ch| ch.len_utf16() > 1) .then(|| original.chars().collect()); - let mut offsets = Vec::with_capacity(arena.position_count()); - arena.remap_positions(|position| { - offsets.push(position.cnum.max(0) as u32); - if position.cnum < 0 { - return; - } - let offset = text.origin(position.cnum as u32); + let place = |position: &mut Position, offset: u32| { let (line, bol) = lines.line_of(offset); let column = match &wide { Some(chars) => chars[bol as usize..offset as usize] @@ -223,7 +303,34 @@ pub fn remap_positions(arena: &mut crate::parse_arena::ParseArena, text: &Source position.line = line; position.bol = bol as i32; position.cnum = (bol + column) as i32; - }); + }; + let mut offsets = Vec::with_capacity(arena.position_count()); + let added = arena.remap_positions( + |position| { + offsets.push(position.cnum.max(0) as u32); + if position.cnum >= 0 { + place(position, text.origin(position.cnum as u32)); + } + }, + |start, end| { + if start.cnum < 0 || end.cnum <= start.cnum { + return None; + } + let (from, to) = (start.cnum as u32, end.cnum as u32); + let range = text.original_range(from, to); + if range == (text.origin(from), text.origin(to)) { + return None; + } + let (mut new_start, mut new_end) = (*start, *end); + place(&mut new_start, range.0); + place(&mut new_end, range.1); + Some((new_start, new_end)) + }, + ); + for (index, from) in added { + debug_assert_eq!(index as usize, offsets.len()); + offsets.push(offsets[from as usize]); + } arena.set_expansion(Arc::new(super::edit::Expansion { text: text.clone(), offsets, @@ -234,20 +341,31 @@ fn unwrap_text(text: Arc) -> SourceText { Arc::try_unwrap(text).unwrap_or_else(|shared| (*shared).clone()) } -fn generated_syntax_error(parser: &Parser<'_>, text: &SourceText, filename: &str) -> anyhow::Error { - let mut output = String::from( - "A macro generated code with a syntax error. The frame shows the expanded source.\n\n", - ); - for diagnostic in parser.diagnostics().iter().take(1) { - output.push_str(&code_frame::format_error( - filename, - text.text(), - &diagnostic.start_pos, - &diagnostic.end_pos, - &diagnostic.explain_with_source(Some(text.text())), - )); - } - UserDiagnostic::new(output, 2).into() +fn generated_syntax_error( + parser: &Parser<'_>, + text: &SourceText, + original: &str, + filename: &str, +) -> anyhow::Error { + let Some(error) = parser.diagnostics().first() else { + return UserDiagnostic::new( + format!("{filename}: a macro generated code that does not parse.\n"), + 2, + ) + .into(); + }; + diagnostic( + "Syntax error!", + original, + text, + filename, + ( + error.start_pos.cnum.max(0) as u32, + error.end_pos.cnum.max(0) as u32, + ), + true, + &error.explain_with_source(Some(text.text())), + ) } /// The `open` statements at the top level of the file, as source text: @@ -262,8 +380,11 @@ fn top_level_opens( .filter(|item| matches!(item.pstr_desc, StructureItemDesc::Pstr_open(_))) .map(|item| { let location = parser.arena().to_location(item.pstr_loc); - text.slice(location.loc_start.cnum.max(0) as u32, location.loc_end.cnum.max(0) as u32) - .to_string() + text.slice( + location.loc_start.cnum.max(0) as u32, + location.loc_end.cnum.max(0) as u32, + ) + .to_string() }) .collect() } @@ -282,7 +403,10 @@ fn evaluate_comptime( if site.shape.get("k") == Some(&json!("other")) { return Err(format!( "%comptime: a value of type {} cannot be written as a literal. Supported: int, float, string, bool, unit, arrays, tuples, options, dicts and records of those.", - site.shape.get("name").and_then(Value::as_str).unwrap_or("this type"), + site.shape + .get("name") + .and_then(Value::as_str) + .unwrap_or("this type"), )); } let source = format!("{}\nlet value = {}\n", opens.join("\n"), site.expression); @@ -306,8 +430,24 @@ fn evaluate_comptime( false, ) .map_err(|error| { + // What the report of the expression's own compilation says, without + // its header: the expression is in this file, not in one of its own. + let report = format!("{error:#}"); + let said = report + .find(&comptime_file) + .and_then(|at| report[at..].find("\n\n").map(|blank| &report[at + blank..])) + .unwrap_or(&report); + let said: Vec<&str> = said.trim_matches('\n').lines().map(str::trim_end).collect(); + let indent = said + .iter() + .filter(|line| !line.is_empty()) + .map(|line| line.len() - line.trim_start().len()) + .min() + .unwrap_or(0); + let said: Vec<&str> = said.iter().map(|line| line.get(indent..).unwrap_or("")).collect(); format!( - "%comptime: the expression is compiled on its own, before this file, so it can only use other modules.\n{error:#}" + "{}\n\n%comptime compiles its expression on its own, before the rest of this file: it can use other modules, not what this file defines.", + said.join("\n") ) })?; @@ -325,19 +465,27 @@ fn evaluate_comptime( }); let response = super::call_host(&**host, &request.to_string()) .map_err(|message| format!("%comptime: the macro engine failed: {message}"))?; - let response: Value = serde_json::from_str(&response) - .map_err(|error| format!("%comptime: the macro engine returned invalid JSON: {error}"))?; + let response: Value = serde_json::from_str(&response).map_err(|error| { + format!("%comptime: the macro engine returned invalid JSON: {error}") + })?; if let Some(literal) = response.get("ok").and_then(Value::as_str) { return Ok(literal.to_string()); } if let Some(message) = response.get("error").and_then(Value::as_str) { - return Err(format!("%comptime: {message}")); + return Err( + if response.get("exception").and_then(Value::as_bool) == Some(true) { + format!("The expression of %comptime raised an exception:\n{message}") + } else { + format!("%comptime: {message}") + }, + ); } let Some(question) = response.get("need").and_then(Value::as_str) else { return Err("%comptime: the macro engine returned an unknown response.".into()); }; - let answer = super::discover::answer_input(&base_dir, question) - .unwrap_or_else(|| json!({ "__error": format!("`{question}` cannot be answered in %comptime.") })); + let answer = super::discover::answer_input(&base_dir, question).unwrap_or_else( + || json!({ "__error": format!("`{question}` cannot be answered in %comptime.") }), + ); answers.insert(question.to_string(), answer); } Err("%comptime: the expression asked more than 1024 questions.".into()) diff --git a/compiler-rust/src/macros/host.js b/compiler-rust/src/macros/host.js index 189acfc058..6de8e6619b 100644 --- a/compiler-rust/src/macros/host.js +++ b/compiler-rust/src/macros/host.js @@ -169,6 +169,23 @@ } } + // An argument that is code comes with `$o`, the compiler's name for where + // its text is in the file: the whole of its text is from there. + function withOrigin(value, depth) { + if (value === null || typeof value !== "object" || depth > 4) return value; + if (Array.isArray(value)) { + return value.map(function (item) { return withOrigin(item, depth + 1); }); + } + var isCode = typeof value.c === "string" && typeof value.$o === "number"; + var out = {}; + Object.keys(value).forEach(function (key) { + if (isCode && key === "$o") return; + out[key] = key === "t" ? value[key] : withOrigin(value[key], depth + 1); + }); + if (isCode) out.m = [[0, value.c.length, value.$o]]; + return out; + } + function describe(error) { if (error && typeof error === "object") { if (error.RE_EXN_ID !== undefined) { @@ -203,19 +220,24 @@ return value === null || value === undefined ? undefined : value[key]; }, load(request.module)); if (typeof macro !== "function") { - throw { __macro_error: "`" + request.module + "." + request.name + "` is not a function, so it cannot run as a macro." }; + throw { __macro_error: "`" + request.module + "." + request.name + "` is not a function, so it cannot run as a macro.", engine: true }; } - var result = macro.apply(null, request.args); + var result = macro.apply(null, request.args.map(function (arg) { return withOrigin(arg, 0); })); if (result === null || typeof result !== "object" || typeof result.c !== "string") { - throw { __macro_error: "The macro `" + request.module + "." + request.name + "` did not return code." }; + throw { __macro_error: "The macro `" + request.module + "." + request.name + "` did not return code.", engine: true }; } - return JSON.stringify({ ok: result.c }); + return JSON.stringify({ ok: result.c, spans: result.m || [] }); } catch (error) { if (error && error.__macro_need !== undefined) return JSON.stringify({ need: error.__macro_need }); if (error && error.__macro_error !== undefined) { - return JSON.stringify({ error: error.__macro_error, offset: error.offset === undefined ? null : error.offset }); + return JSON.stringify({ + error: error.__macro_error, + offset: error.offset === undefined ? null : error.offset, + // Said by the engine, not by the macro. + engine: error.engine === true, + }); } - return JSON.stringify({ error: "The macro raised an exception: " + describe(error) }); + return JSON.stringify({ error: describe(error), exception: true }); } }; })(); diff --git a/compiler-rust/src/macros/mod.rs b/compiler-rust/src/macros/mod.rs index 971e284a0a..0a9f4f0286 100644 --- a/compiler-rust/src/macros/mod.rs +++ b/compiler-rust/src/macros/mod.rs @@ -25,6 +25,7 @@ pub mod expand; pub mod quickjs; pub mod quote; pub mod reflect; +pub mod report; /// The engine-side script: module loader and call entry point. pub const HOST_JS: &str = include_str!("host.js"); diff --git a/compiler-rust/src/macros/quote.rs b/compiler-rust/src/macros/quote.rs index 2d717e7888..a5ccfc3500 100644 --- a/compiler-rust/src/macros/quote.rs +++ b/compiler-rust/src/macros/quote.rs @@ -3,14 +3,20 @@ //! `%code(JSON.Encode.string(${value}))` becomes //! //! ```text -//! Macro.__quoteCode(["JSON.Encode.string(", ")"], [Macro.__holeCode(value)]) +//! Macro.__quoteCode( +//! [[("JSON.Encode.string(", 9, 20)], [(")", 9, 48)]], +//! [Macro.__holeCode(value)], +//! "Json.res", +//! ) //! ``` //! //! The pieces are the quote's source text between the holes, so a quote is //! parsed and reported on where it is written and the macro's compiled -//! JavaScript carries it as string literals. The hole expressions stay -//! ordinary code of the macro: they are type checked, and a quote nested in a -//! hole is lowered by the next pass. +//! JavaScript carries it as string literals. Each piece comes with the line +//! and column it has in the macro's file: the code a macro returns keeps +//! them, and an error in generated code says which line of which quote it +//! is in. The hole expressions stay ordinary code of the macro: they are +//! type checked, and a quote nested in a hole is lowered by the next pass. //! //! Hygiene, as far as syntax decides it: a name the quote uses that the //! macro's file defines at its top level is written with the module's name @@ -28,7 +34,7 @@ use crate::parser::ast::{ use crate::parser::longident::Longident; use crate::parser::module::HOLE_EXTENSION; -use super::edit::{Edit, Segment, SourceText}; +use super::edit::{Edit, LineTable, Segment, SourceText}; /// The extension names that are quotes. pub fn is_quote_name(name: &str) -> bool { @@ -261,6 +267,10 @@ impl AstIter for QuoteScan<'_> { struct QuoteFinder<'a> { text: &'a SourceText, module_name: &'a str, + /// The name of the file, as an error names it. + file: &'a str, + /// Lines of the file as written. + lines: &'a LineTable, top_level: &'a TopLevel, edits: Vec, } @@ -295,7 +305,11 @@ impl QuoteFinder<'_> { value_uses: Vec::new(), module_roots: Vec::new(), bound: HashSet::new(), - item_exprs: if single_expression { &no_items } else { &item_exprs }, + item_exprs: if single_expression { + &no_items + } else { + &item_exprs + }, }; scan.payload(arena, &extension.1); @@ -306,54 +320,77 @@ impl QuoteFinder<'_> { _ => "__quoteDecls", }; - // Qualify the names the file defines. - let mut substitutions: Vec<((u32, u32), String)> = Vec::new(); + // Qualify the names the file defines: where the module's name goes + // in front. + let mut substitutions: Vec<(u32, u32)> = Vec::new(); for (at, used) in &scan.value_uses { if self.top_level.values.contains(used) && !scan.bound.contains(used) { - substitutions.push((*at, format!("{}.{}", self.module_name, used))); + substitutions.push(*at); } } for (at, root) in &scan.module_roots { if self.top_level.modules.contains(root) { - substitutions.push(( - *at, - format!("{}.{}", self.module_name, self.text.slice(at.0, at.1)), - )); + substitutions.push(*at); } } scan.holes.sort_by_key(|hole| hole.outer.0); - substitutions.sort_by_key(|(at, _)| at.0); + substitutions.sort_by_key(|at| at.0); let in_hole = |at: (u32, u32)| { scan.holes .iter() .any(|hole| at.0 >= hole.outer.0 && at.1 <= hole.outer.1) }; - substitutions.retain(|(at, _)| at.0 >= payload.0 && at.1 <= payload.1 && !in_hole(*at)); + substitutions.retain(|at| at.0 >= payload.0 && at.1 <= payload.1 && !in_hole(*at)); - // The text between two holes, with the substitutions applied. + // The text between two holes, as the parts of it that are text of + // the file, each with its line and column there, and the names that + // were qualified in between. + let fragment = |from: u32, to: u32| -> String { + if from >= to { + return String::new(); + } + // Text a macro generated has no place in the file. + let (line, column) = match self.text.generated(from) { + Some(_) => (0, 0), + None => { + let offset = self.text.origin(from); + let (line, line_start) = self.lines.line_of(offset); + (line, offset - line_start) + } + }; + format!( + "({}, {line}, {column})", + string_literal(self.text.slice(from, to)) + ) + }; let piece = |from: u32, to: u32| -> String { - let mut out = String::new(); + let mut fragments = Vec::new(); let mut cursor = from; - for (at, replacement) in &substitutions { + let qualifier = format!( + "({}, 0, 0)", + string_literal(&format!("{}.", self.module_name)) + ); + for at in &substitutions { if at.0 < cursor || at.1 > to { continue; } - out.push_str(self.text.slice(cursor, at.0)); - out.push_str(replacement); - cursor = at.1; + fragments.push(fragment(cursor, at.0)); + fragments.push(qualifier.clone()); + cursor = at.0; } - out.push_str(self.text.slice(cursor, to)); - out + fragments.push(fragment(cursor, to)); + fragments.retain(|fragment| !fragment.is_empty()); + format!("[{}]", fragments.join(", ")) }; let mut pieces = Vec::with_capacity(scan.holes.len() + 1); let mut cursor = payload.0; for hole in &scan.holes { - pieces.push(string_literal(&piece(cursor, hole.outer.0))); + pieces.push(piece(cursor, hole.outer.0)); cursor = hole.outer.1; } - pieces.push(string_literal(&piece(cursor, payload.1))); + pieces.push(piece(cursor, payload.1)); let mut segments = vec![Segment::Text(format!( "(Macro.{function}([{}], [", @@ -373,11 +410,12 @@ impl QuoteFinder<'_> { segments.push(Segment::Copy(hole.inner.0, hole.inner.1)); segments.push(Segment::Text(")".into())); } - segments.push(Segment::Text("]))".into())); + segments.push(Segment::Text(format!("], {}))", string_literal(self.file)))); self.edits.push(Edit { start, end, segments, + internal: true, }); } } @@ -395,17 +433,26 @@ impl AstIter for QuoteFinder<'_> { } } -/// The edits that lower the outermost quotes of `structure`. +/// The edits that lower the outermost quotes of `structure`. `original` is +/// the file as written and `filename` its name. pub fn lowering_edits( arena: &ParseArena, structure: &[StructureItem], text: &SourceText, + original: &str, + filename: &str, module_name: &str, ) -> Vec { let top_level = top_level(arena, structure); + let lines = LineTable::new(original); + // The name without its directories: the compiled macro is the same + // wherever the project is checked out. + let file = filename.rsplit(['/', '\\']).next().unwrap_or(filename); let mut finder = QuoteFinder { text, module_name, + file, + lines: &lines, top_level: &top_level, edits: Vec::new(), }; diff --git a/compiler-rust/src/macros/reflect.rs b/compiler-rust/src/macros/reflect.rs index 9032add786..af8a5be645 100644 --- a/compiler-rust/src/macros/reflect.rs +++ b/compiler-rust/src/macros/reflect.rs @@ -23,10 +23,12 @@ use crate::types::predef; use crate::types::type_expr::{RowField, TypeDesc, TypeExprRef}; use crate::types::variant_runtime::LiteralTag; -/// The types a running expansion has handed to the macro. +/// What a running expansion has handed to the macro: the types, and the +/// ranges of the text being expanded that it got as code. #[derive(Default)] pub struct TypeTable { types: Vec, + origins: Vec<(u32, u32)>, } impl TypeTable { @@ -34,6 +36,16 @@ impl TypeTable { self.types.get(id).copied() } + /// The id of the text at `range`, for the `$o` of a code argument. + pub fn origin(&mut self, range: (u32, u32)) -> usize { + self.origins.push(range); + self.origins.len() - 1 + } + + pub fn origins(&self) -> &[(u32, u32)] { + &self.origins + } + fn add(&mut self, ctx: &TypeContext, ty: TypeExprRef) -> usize { let repr = ctx.repr(ty); if let Some(index) = self.types.iter().position(|known| ctx.repr(*known) == repr) { @@ -136,7 +148,10 @@ fn field( label: &LabelDeclaration, ) -> Value { let name = label.ld_id.name().to_string(); - let js_name = label.ld_runtime_name.clone().unwrap_or_else(|| name.clone()); + let js_name = label + .ld_runtime_name + .clone() + .unwrap_or_else(|| name.clone()); let ty = member_type(ctx, params, args, label.ld_type); json!({ "name": name, @@ -202,7 +217,9 @@ fn type_info_at( json!({ "params": params, "result": type_ref(ctx, table, *ret) }), ) } - TypeDesc::Tpoly { body, .. } if depth < 8 => type_info_at(ctx, env, table, *body, depth + 1), + TypeDesc::Tpoly { body, .. } if depth < 8 => { + type_info_at(ctx, env, table, *body, depth + 1) + } TypeDesc::Tvariant(row) => { let row = ctx.row_desc(*row); let constructors: Vec = row @@ -301,9 +318,7 @@ fn constructor_info( ConstructorArguments::CstrTuple(types) => ( types .iter() - .map(|ty| { - type_ref(ctx, table, member_type(ctx, params, args, *ty)) - }) + .map(|ty| type_ref(ctx, table, member_type(ctx, params, args, *ty))) .collect::>(), Vec::new(), ), @@ -376,11 +391,14 @@ pub fn value_shape(ctx: &TypeContext, env: &Env, ty: TypeExprRef, depth: usize) .iter() .map(|label| { let name = label.ld_id.name().to_string(); - let field_type = member_type(ctx, &decl.type_params, &args, label.ld_type); + let field_type = + member_type(ctx, &decl.type_params, &args, label.ld_type); // An optional field holds the value itself, not an option. let shape = value_shape(ctx, env, field_type, depth + 1); let shape = match (&shape, label.ld_optional) { - (Value::Object(object), true) if object.get("k") == Some(&json!("option")) => { + (Value::Object(object), true) + if object.get("k") == Some(&json!("option")) => + { object.get("of").cloned().unwrap_or(shape.clone()) } _ => shape, diff --git a/compiler-rust/src/macros/report.rs b/compiler-rust/src/macros/report.rs new file mode 100644 index 0000000000..d6e086a615 --- /dev/null +++ b/compiler-rust/src/macros/report.rs @@ -0,0 +1,85 @@ +//! What a diagnostic says about code a macro generated. +//! +//! A diagnostic in generated code is reported at the macro use it was +//! generated for: that is the code the person has. After the frame of that +//! use comes a note with the lines of the quote the code was written in, +//! or, for code that is not from a quote, the generated code itself. + +use crate::location::Position; +use crate::parser::code_frame; + +use super::edit::{GeneratedCode, LineTable, SourceText}; + +/// The note for a diagnostic in `generated`, a part of the expanded `text`. +/// `read` gives the text of a macro's file. +pub fn generated_code_note( + text: &SourceText, + generated: &GeneratedCode, + warning: bool, + read: impl Fn(&str) -> String, +) -> String { + let frame = |text: &str, lines: &LineTable, start: (u32, u32), end: (u32, u32)| { + let position = |(line, offset): (u32, u32)| { + let bol = lines.line_start(line).unwrap_or(0); + Position::new( + crate::intern::StrIdx::from_raw(0), + line as i32, + bol as i32, + offset as i32, + ) + }; + let (start, end) = (position(start), position(end)); + if warning { + code_frame::print_warning(text, &start, &end) + } else { + code_frame::print(text, &start, &end) + } + }; + let by = match &generated.description { + Some(description) => format!("generated by {description}"), + None => "the macro generated".to_string(), + }; + let mut output = String::new(); + + if let Some(quote) = &generated.quote { + let position = |(line, column): (u32, u32)| { + Position::new( + crate::intern::StrIdx::from_raw(0), + line as i32, + 0, + column as i32, + ) + }; + let place = + code_frame::format_location("e.file, &position(quote.start), &position(quote.end)); + output.push_str(&format!(" This is in the code {by}, written at ")); + output.push_str(&code_frame::colorize_location(&place)); + output.push_str("\n\n"); + let source = read("e.file); + let lines = LineTable::new(&source); + let offset = + |(line, column): (u32, u32)| lines.line_start(line).map(|start| (line, start + column)); + if let (false, Some(start), Some(end)) = + (source.is_empty(), offset(quote.start), offset(quote.end)) + { + output.push_str(&frame(&source, &lines, start, end)); + output.push('\n'); + } + return output; + } + + let expanded = text.text(); + let lines = LineTable::new(expanded); + let place = |offset: u32| (lines.line_of(offset).0 as u32, offset); + output.push_str(&format!( + " This is in the code {by}. In the expanded source:\n\n" + )); + output.push_str(&frame( + expanded, + &lines, + place(generated.start), + place(generated.end), + )); + output.push('\n'); + output +} diff --git a/compiler-rust/src/parse_arena.rs b/compiler-rust/src/parse_arena.rs index 57686572a8..23e5fb6c13 100644 --- a/compiler-rust/src/parse_arena.rs +++ b/compiler-rust/src/parse_arena.rs @@ -2707,10 +2707,44 @@ impl ParseArena { /// Rewrite every position recorded so far. Macro expansion parses the /// expanded text and then moves each position to where it is in the /// source as written. - pub fn remap_positions(&mut self, mut remap: impl FnMut(&mut Position)) { + /// + /// `range` is asked about each location, with the positions it has in + /// the expanded text: it answers when the location does not start and + /// end where its two positions go by themselves (a location that ends in + /// generated code ends where the macro use ends, not where it starts). + /// Such a location gets positions of its own. Returned: for each + /// position added, the index of the one it was made from. + pub fn remap_positions( + &mut self, + mut remap: impl FnMut(&mut Position), + mut range: impl FnMut(&Position, &Position) -> Option<(Position, Position)>, + ) -> Vec<(u32, u32)> { + let mut added = Vec::new(); + let mut moved = Vec::new(); + for (index, location) in self.locations.iter() { + let start = self.positions.get(location.loc_start); + let end = self.positions.get(location.loc_end); + if let Some(range) = range(start, end) { + moved.push((index, range)); + } + } for position in self.positions.iter_mut() { remap(position); } + for (index, (start, end)) in moved { + let (old_start, old_end) = { + let location = self.locations.get(index); + (location.loc_start, location.loc_end) + }; + let new_start = self.positions.push(start); + let new_end = self.positions.push(end); + added.push((new_start.0, old_start.0)); + added.push((new_end.0, old_end.0)); + let location = self.locations.get_mut(index); + location.loc_start = new_start; + location.loc_end = new_end; + } + added } /// The expansion this parse is the result of, if any. diff --git a/compiler-rust/tests/macro_errors.rs b/compiler-rust/tests/macro_errors.rs new file mode 100644 index 0000000000..4a24f8691f --- /dev/null +++ b/compiler-rust/tests/macro_errors.rs @@ -0,0 +1,216 @@ +//! What the compiler says when a file that uses macros has a problem. +//! +//! Each case compiles a file and compares the diagnostics with +//! `tests/macro_errors/.txt`. Run with `UPDATE_EXPECTED=1` to write +//! those files, then read the difference. + +mod macros_support; +use macros_support::Project; + +const JSON: &str = include_str!("../../playground/examples/json/Json.res"); +const DEBUG: &str = include_str!("../../playground/examples/debug/Debug.res"); + +const USER: &str = "type user = {name: string, age: int}\nlet alice = {name: \"Alice\", age: 30}\n"; + +const QUOTED: &str = r#"open Macro + +@macro +let twice = (e: code): code => + %code({ + let v = ${e} + v + "two" + }) + +@macro +let unbound = (e: code<'a>): code<'a> => %code(notDefinedAnywhere(${e})) + +@macro +let shadow = (e: code): code => %code({ + let unused = 1 + ${e} +}) + +@generic +let show = (value: code<'a>): code => + switch Type.info(typeOf(value)) { + | Int => %code(Int.toString(${value}) + 1) + | _ => error("only int") + } + +@macro +let decl = (): decls => %code(let made: int = "x") + +// Code that is not written in a quote. +@macro +let built = (e: code): code => Code.call(Code.raw("notDefinedAnywhere"), [e]) +"#; + +const THROWS: &str = r#"open Macro + +exception Boom(string) + +@macro +let exn = (): code => throw(Boom("bang")) + +@macro +let js = (): code => { + let xs: array = [] + Code.int(xs->Array.getUnsafe(3)->Int.toString->String.length) +} + +@macro +let syntax = (): code => Code.raw("let = 1 +") + +@macro +let rec loop = (): code => %code(%Throws.loop()) +"#; + +/// The diagnostics of a file that does not compile, or the warnings of one +/// that does. +fn diagnostics(project: &mut Project, filename: &str, source: &str) -> String { + match project.compile(filename, source) { + Ok(_) => format!("(compiles)\n{}", project.warnings), + Err(error) => error, + } +} + +fn check(project: &mut Project, case: &str, source: &str) { + let filename = format!("{}.res", case[..1].to_uppercase() + &case[1..]); + let actual = format!("{source}----\n{}", diagnostics(project, &filename, source)); + // Lines without trailing spaces: the compiler prints some. + let actual: String = actual + .lines() + .map(|line| format!("{}\n", line.trim_end())) + .collect(); + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/macro_errors") + .join(format!("{case}.txt")); + if std::env::var_os("UPDATE_EXPECTED").is_some() { + std::fs::write(&path, &actual).unwrap(); + return; + } + let expected = std::fs::read_to_string(&path).unwrap_or_default(); + assert!( + actual == expected, + "{case}: the diagnostics differ from {}.\n---- expected\n{expected}\n---- actual\n{actual}", + path.display() + ); +} + +fn on_a_big_stack(test: fn()) { + std::thread::Builder::new() + .stack_size(512 << 20) + .spawn(test) + .unwrap() + .join() + .unwrap(); +} + +#[test] +fn an_error_in_an_argument_points_at_the_argument() { + on_a_big_stack(|| { + let mut project = Project::new(); + project.compile("Json.res", JSON).unwrap(); + project.compile("Debug.res", DEBUG).unwrap(); + check( + &mut project, + "argumentType", + "let x = %Debug.log(1 + \"a\")\n", + ); + check( + &mut project, + "argumentUnbound", + "let x = %Debug.log(nope)\n", + ); + check( + &mut project, + "genericArgumentUnbound", + &format!("{USER}let j = Json.encode(alicia)\n"), + ); + // An error elsewhere in the item of a use is the error reported. + check( + &mut project, + "errorBesideAUse", + &format!("{USER}Console.log(JSON.stringify(Json.encode(alice), ~space=\"x\"))\n"), + ); + }); +} + +#[test] +fn an_error_in_generated_code_shows_where_it_was_written() { + on_a_big_stack(|| { + let mut project = Project::new(); + project.compile("Quoted.res", QUOTED).unwrap(); + check( + &mut project, + "quotedType", + "let a = 1\nlet x = %Quoted.twice(a + 1)\n", + ); + check( + &mut project, + "quotedUnbound", + "let x = %Quoted.unbound(1)\n", + ); + check(&mut project, "quotedWarning", "let x = %Quoted.shadow(1)\n"); + check(&mut project, "quotedInGeneric", "let s = Quoted.show(1)\n"); + check(&mut project, "quotedDeclarations", "%%Quoted.decl()\n"); + check(&mut project, "builtCode", "let x = %Quoted.built(1)\n"); + }); +} + +#[test] +fn an_error_of_a_macro_is_reported_at_its_use() { + on_a_big_stack(|| { + let mut project = Project::new(); + project.compile("Json.res", JSON).unwrap(); + project.compile("Quoted.res", QUOTED).unwrap(); + project.compile("Throws.res", THROWS).unwrap(); + check(&mut project, "macroReports", "let s = Quoted.show(\"a\")\n"); + check(&mut project, "macroThrows", "let x = %Throws.exn()\n"); + check(&mut project, "macroThrowsJs", "let x = %Throws.js()\n"); + // A use in generated code: the error says what generated that code. + check( + &mut project, + "macroReportsInAnInstance", + "type t = {name: string, f: int => int}\nlet enc = (t: t) => Json.encode(t)\n", + ); + check( + &mut project, + "generatedSyntax", + "let a = 1\nlet x = %Throws.syntax()\nlet b = 2\n", + ); + check( + &mut project, + "expansionWithoutEnd", + "let x = %Throws.loop()\n", + ); + check(&mut project, "unknownMacro", "let x = %Throws.exm()\n"); + }); +} + +#[test] +fn comptime_errors() { + on_a_big_stack(|| { + let mut project = Project::new(); + check( + &mut project, + "comptimeLocal", + "let n = 3\nlet x = %comptime(n + 1)\n", + ); + check( + &mut project, + "comptimeThrows", + "let x = %comptime(Option.getOrThrow((None: option)))\n", + ); + check( + &mut project, + "comptimeType", + "let x = %comptime(1 + \"a\")\n", + ); + check( + &mut project, + "comptimeFunction", + "let x = %comptime((a: int) => a)\n", + ); + }); +} diff --git a/compiler-rust/tests/macro_errors/argumentType.txt b/compiler-rust/tests/macro_errors/argumentType.txt new file mode 100644 index 0000000000..53396f03f5 --- /dev/null +++ b/compiler-rust/tests/macro_errors/argumentType.txt @@ -0,0 +1,14 @@ +let x = %Debug.log(1 + "a") +---- + + We've found a bug for you! + ArgumentType.res:1:24-26 + + 1 │ let x = %Debug.log(1 + "a") + 2 │ + + This has type: string + But it's expected to have type: int + + You can convert string to int with Int.fromString. + diff --git a/compiler-rust/tests/macro_errors/argumentUnbound.txt b/compiler-rust/tests/macro_errors/argumentUnbound.txt new file mode 100644 index 0000000000..9eb3a33c7b --- /dev/null +++ b/compiler-rust/tests/macro_errors/argumentUnbound.txt @@ -0,0 +1,11 @@ +let x = %Debug.log(nope) +---- + + We've found a bug for you! + ArgumentUnbound.res:1:20-23 + + 1 │ let x = %Debug.log(nope) + 2 │ + + The value nope can't be found + diff --git a/compiler-rust/tests/macro_errors/builtCode.txt b/compiler-rust/tests/macro_errors/builtCode.txt new file mode 100644 index 0000000000..64369d511e --- /dev/null +++ b/compiler-rust/tests/macro_errors/builtCode.txt @@ -0,0 +1,16 @@ +let x = %Quoted.built(1) +---- + + We've found a bug for you! + BuiltCode.res:1:9-24 + + 1 │ let x = %Quoted.built(1) + 2 │ + + This is in the code the macro generated. In the expanded source: + + 1 │ let x = (notDefinedAnywhere(1)) + 2 │ + + The value notDefinedAnywhere can't be found + diff --git a/compiler-rust/tests/macro_errors/comptimeFunction.txt b/compiler-rust/tests/macro_errors/comptimeFunction.txt new file mode 100644 index 0000000000..d3a1963cf4 --- /dev/null +++ b/compiler-rust/tests/macro_errors/comptimeFunction.txt @@ -0,0 +1,11 @@ +let x = %comptime((a: int) => a) +---- + + We've found a bug for you! + ComptimeFunction.res:1:9-32 + + 1 │ let x = %comptime((a: int) => a) + 2 │ + + %comptime: a value of type int => int cannot be written as a literal. Supported: int, float, string, bool, unit, arrays, tuples, options, dicts and records of those. + diff --git a/compiler-rust/tests/macro_errors/comptimeLocal.txt b/compiler-rust/tests/macro_errors/comptimeLocal.txt new file mode 100644 index 0000000000..2226dab745 --- /dev/null +++ b/compiler-rust/tests/macro_errors/comptimeLocal.txt @@ -0,0 +1,15 @@ +let n = 3 +let x = %comptime(n + 1) +---- + + We've found a bug for you! + ComptimeLocal.res:2:9-24 + + 1 │ let n = 3 + 2 │ let x = %comptime(n + 1) + 3 │ + + The value n can't be found + + %comptime compiles its expression on its own, before the rest of this file: it can use other modules, not what this file defines. + diff --git a/compiler-rust/tests/macro_errors/comptimeThrows.txt b/compiler-rust/tests/macro_errors/comptimeThrows.txt new file mode 100644 index 0000000000..924f48d06f --- /dev/null +++ b/compiler-rust/tests/macro_errors/comptimeThrows.txt @@ -0,0 +1,12 @@ +let x = %comptime(Option.getOrThrow((None: option))) +---- + + We've found a bug for you! + ComptimeThrows.res:1:9-57 + + 1 │ let x = %comptime(Option.getOrThrow((None: option))) + 2 │ + + The expression of %comptime raised an exception: + Panic! Option.getOrThrow called for None value + diff --git a/compiler-rust/tests/macro_errors/comptimeType.txt b/compiler-rust/tests/macro_errors/comptimeType.txt new file mode 100644 index 0000000000..165557a508 --- /dev/null +++ b/compiler-rust/tests/macro_errors/comptimeType.txt @@ -0,0 +1,14 @@ +let x = %comptime(1 + "a") +---- + + We've found a bug for you! + ComptimeType.res:1:23-25 + + 1 │ let x = %comptime(1 + "a") + 2 │ + + This has type: string + But it's expected to have type: int + + You can convert string to int with Int.fromString. + diff --git a/compiler-rust/tests/macro_errors/errorBesideAUse.txt b/compiler-rust/tests/macro_errors/errorBesideAUse.txt new file mode 100644 index 0000000000..88c8e2e60b --- /dev/null +++ b/compiler-rust/tests/macro_errors/errorBesideAUse.txt @@ -0,0 +1,18 @@ +type user = {name: string, age: int} +let alice = {name: "Alice", age: 30} +Console.log(JSON.stringify(Json.encode(alice), ~space="x")) +---- + + We've found a bug for you! + ErrorBesideAUse.res:3:55-57 + + 1 │ type user = {name: string, age: int} + 2 │ let alice = {name: "Alice", age: 30} + 3 │ Console.log(JSON.stringify(Json.encode(alice), ~space="x")) + 4 │ + + This has type: string + But this optional function argument ~space is expecting: int + + You can convert string to int with Int.fromString. + diff --git a/compiler-rust/tests/macro_errors/expansionWithoutEnd.txt b/compiler-rust/tests/macro_errors/expansionWithoutEnd.txt new file mode 100644 index 0000000000..e9171014cf --- /dev/null +++ b/compiler-rust/tests/macro_errors/expansionWithoutEnd.txt @@ -0,0 +1,12 @@ +let x = %Throws.loop() +---- + + We've found a bug for you! + ExpansionWithoutEnd.res:1:9-22 + + 1 │ let x = %Throws.loop() + 2 │ + + Macro expansion did not finish after 64 passes. + A macro probably generates a use of itself. + diff --git a/compiler-rust/tests/macro_errors/generatedSyntax.txt b/compiler-rust/tests/macro_errors/generatedSyntax.txt new file mode 100644 index 0000000000..1dd0025e53 --- /dev/null +++ b/compiler-rust/tests/macro_errors/generatedSyntax.txt @@ -0,0 +1,22 @@ +let a = 1 +let x = %Throws.syntax() +let b = 2 +---- + + Syntax error! + GeneratedSyntax.res:2:9-24 + + 1 │ let a = 1 + 2 │ let x = %Throws.syntax() + 3 │ let b = 2 + 4 │ + + This is in the code the macro generated. In the expanded source: + + 1 │ let a = 1 + 2 │ let x = (let = 1 +) + 3 │ let b = 2 + 4 │ + + I'm not sure what to parse here when looking at "let". + diff --git a/compiler-rust/tests/macro_errors/genericArgumentUnbound.txt b/compiler-rust/tests/macro_errors/genericArgumentUnbound.txt new file mode 100644 index 0000000000..120c3b5ce6 --- /dev/null +++ b/compiler-rust/tests/macro_errors/genericArgumentUnbound.txt @@ -0,0 +1,17 @@ +type user = {name: string, age: int} +let alice = {name: "Alice", age: 30} +let j = Json.encode(alicia) +---- + + We've found a bug for you! + GenericArgumentUnbound.res:3:21-26 + + 1 │ type user = {name: string, age: int} + 2 │ let alice = {name: "Alice", age: 30} + 3 │ let j = Json.encode(alicia) + 4 │ + + The value alicia can't be found + + Hint: Did you mean alice? + diff --git a/compiler-rust/tests/macro_errors/macroReports.txt b/compiler-rust/tests/macro_errors/macroReports.txt new file mode 100644 index 0000000000..c90d4525bd --- /dev/null +++ b/compiler-rust/tests/macro_errors/macroReports.txt @@ -0,0 +1,13 @@ +let s = Quoted.show("a") +---- + + We've found a bug for you! + MacroReports.res:1:9-19 + + 1 │ let s = Quoted.show("a") + 2 │ + + only int + + This is reported by the macro `Quoted.show`. + diff --git a/compiler-rust/tests/macro_errors/macroReportsInAnInstance.txt b/compiler-rust/tests/macro_errors/macroReportsInAnInstance.txt new file mode 100644 index 0000000000..b1c87e0c3c --- /dev/null +++ b/compiler-rust/tests/macro_errors/macroReportsInAnInstance.txt @@ -0,0 +1,23 @@ +type t = {name: string, f: int => int} +let enc = (t: t) => Json.encode(t) +---- + + We've found a bug for you! + MacroReportsInAnInstance.res:2:21-31 + + 1 │ type t = {name: string, f: int => int} + 2 │ let enc = (t: t) => Json.encode(t) + 3 │ + + This is in the code generated by `Json.encode` for `t`, written at Json.res:25:35-40 + + 23 ┆ // @Json.key("...") on a field renames it. + 24 ┆ let key = f.attrs->Attr.string("Json.key")->Option.getOr(f.jsName) + 25 ┆ %code((${Code.string(key)}, encode(${value->Code.field(f.name)}))) + 26 ┆ }) + 27 ┆ %code(JSON.Encode.object(Dict.fromArray(${Code.array(entries)}))) + + Json.encode cannot encode the type int => int + + This is reported by the macro `Json.encode`. + diff --git a/compiler-rust/tests/macro_errors/macroThrows.txt b/compiler-rust/tests/macro_errors/macroThrows.txt new file mode 100644 index 0000000000..1b730956b0 --- /dev/null +++ b/compiler-rust/tests/macro_errors/macroThrows.txt @@ -0,0 +1,12 @@ +let x = %Throws.exn() +---- + + We've found a bug for you! + MacroThrows.res:1:9-21 + + 1 │ let x = %Throws.exn() + 2 │ + + The macro `Throws.exn` raised an exception: + Throws.Boom: bang + diff --git a/compiler-rust/tests/macro_errors/macroThrowsJs.txt b/compiler-rust/tests/macro_errors/macroThrowsJs.txt new file mode 100644 index 0000000000..b79edf4f57 --- /dev/null +++ b/compiler-rust/tests/macro_errors/macroThrowsJs.txt @@ -0,0 +1,12 @@ +let x = %Throws.js() +---- + + We've found a bug for you! + MacroThrowsJs.res:1:9-20 + + 1 │ let x = %Throws.js() + 2 │ + + The macro `Throws.js` raised an exception: + cannot read property 'toString' of undefined + diff --git a/compiler-rust/tests/macro_errors/quotedDeclarations.txt b/compiler-rust/tests/macro_errors/quotedDeclarations.txt new file mode 100644 index 0000000000..945a1c7b16 --- /dev/null +++ b/compiler-rust/tests/macro_errors/quotedDeclarations.txt @@ -0,0 +1,22 @@ +%%Quoted.decl() +---- + + We've found a bug for you! + QuotedDeclarations.res:1:1-15 + + 1 │ %%Quoted.decl() + 2 │ + + This is in the code the macro generated, written at Quoted.res:27:47-49 + + 25 │ + 26 │ @macro + 27 │ let decl = (): decls => %code(let made: int = "x") + 28 │ + 29 │ // Code that is not written in a quote. + + This has type: string + But it's expected to have type: int + + You can convert string to int with Int.fromString. + diff --git a/compiler-rust/tests/macro_errors/quotedInGeneric.txt b/compiler-rust/tests/macro_errors/quotedInGeneric.txt new file mode 100644 index 0000000000..3e4ef4e491 --- /dev/null +++ b/compiler-rust/tests/macro_errors/quotedInGeneric.txt @@ -0,0 +1,22 @@ +let s = Quoted.show(1) +---- + + We've found a bug for you! + QuotedInGeneric.res:1:9-19 + + 1 │ let s = Quoted.show(1) + 2 │ + + This is in the code generated by `Quoted.show` for `int`, written at Quoted.res:22:43 + + 20 │ let show = (value: code<'a>): code => + 21 │ switch Type.info(typeOf(value)) { + 22 │ | Int => %code(Int.toString(${value}) + 1) + 23 │ | _ => error("only int") + 24 │ } + + This has type: int + But it's expected to have type: string + + You can convert int to string with Int.toString. + diff --git a/compiler-rust/tests/macro_errors/quotedType.txt b/compiler-rust/tests/macro_errors/quotedType.txt new file mode 100644 index 0000000000..41c0718e36 --- /dev/null +++ b/compiler-rust/tests/macro_errors/quotedType.txt @@ -0,0 +1,24 @@ +let a = 1 +let x = %Quoted.twice(a + 1) +---- + + We've found a bug for you! + QuotedType.res:2:9-28 + + 1 │ let a = 1 + 2 │ let x = %Quoted.twice(a + 1) + 3 │ + + This is in the code the macro generated, written at Quoted.res:7:9-13 + + 5 ┆ %code({ + 6 ┆ let v = ${e} + 7 ┆ v + "two" + 8 ┆ }) + 9 ┆ + + This has type: string + But it's expected to have type: int + + You can convert string to int with Int.fromString. + diff --git a/compiler-rust/tests/macro_errors/quotedUnbound.txt b/compiler-rust/tests/macro_errors/quotedUnbound.txt new file mode 100644 index 0000000000..74c35ec44f --- /dev/null +++ b/compiler-rust/tests/macro_errors/quotedUnbound.txt @@ -0,0 +1,20 @@ +let x = %Quoted.unbound(1) +---- + + We've found a bug for you! + QuotedUnbound.res:1:9-26 + + 1 │ let x = %Quoted.unbound(1) + 2 │ + + This is in the code the macro generated, written at Quoted.res:11:48-65 + + 9 │ + 10 │ @macro + 11 │ let unbound = (e: code<'a>): code<'a> => %code(notDefinedAnywhere(${e}) + │ ) + 12 │ + 13 │ @macro + + The value notDefinedAnywhere can't be found + diff --git a/compiler-rust/tests/macro_errors/quotedWarning.txt b/compiler-rust/tests/macro_errors/quotedWarning.txt new file mode 100644 index 0000000000..e48106f0c2 --- /dev/null +++ b/compiler-rust/tests/macro_errors/quotedWarning.txt @@ -0,0 +1,25 @@ +let x = %Quoted.shadow(1) +---- +(compiles) + + Warning number 26 + QuotedWarning.res:1:9-25 + + 1 │ let x = %Quoted.shadow(1) + 2 │ + + This is in the code the macro generated, written at Quoted.res:15:7-12 + + 13 │ @macro + 14 │ let shadow = (e: code): code => %code({ + 15 │ let unused = 1 + 16 │ ${e} + 17 │ }) + + unused variable unused. + +Fix this by: +- Deleting the variable if it's not used anymore. +- Prepending the variable name with `_` (like `_unused`) to ignore that the variable is unused. +- Using the variable somewhere. + diff --git a/compiler-rust/tests/macro_errors/unknownMacro.txt b/compiler-rust/tests/macro_errors/unknownMacro.txt new file mode 100644 index 0000000000..db472b52bc --- /dev/null +++ b/compiler-rust/tests/macro_errors/unknownMacro.txt @@ -0,0 +1,11 @@ +let x = %Throws.exm() +---- + + We've found a bug for you! + UnknownMacro.res:1:9-21 + + 1 │ let x = %Throws.exm() + 2 │ + + The macro `Throws.exm` cannot be found. + diff --git a/compiler-rust/tests/macros.rs b/compiler-rust/tests/macros.rs index 6e6333a0ea..c9e6194aa7 100644 --- a/compiler-rust/tests/macros.rs +++ b/compiler-rust/tests/macros.rs @@ -548,19 +548,6 @@ fn macro_code_has_no_clock_and_no_random_numbers() { assert!(error.contains("Date.now is not available at compile time"), "{error}"); } -#[test] -fn generated_syntax_errors_show_the_generated_code() { - let mut project = Project::new(); - compile_ok( - &mut project, - "Bad.res", - "open Macro\n@macro\nlet bad = (): code => Code.raw(\"1 +\")\n", - ); - let error = compile_err(&mut project, "UseBad.res", "let x = %Bad.bad()\n"); - assert!(error.contains("A macro generated code with a syntax error"), "{error}"); - assert!(error.contains("let x = (1 +)"), "{error}"); -} - #[test] fn pattern_macro() { let mut project = Project::new(); diff --git a/compiler-rust/tests/macros_support/mod.rs b/compiler-rust/tests/macros_support/mod.rs index 93e7a52ada..b05887a4b6 100644 --- a/compiler-rust/tests/macros_support/mod.rs +++ b/compiler-rust/tests/macros_support/mod.rs @@ -1,5 +1,7 @@ -//! A small in-memory project for the macro tests: the standard library is -//! type checked from source, and macros run in QuickJS. +//! A small project for the macro tests: the standard library is type +//! checked from source, and macros run in QuickJS. Its files are written to +//! a directory of its own, so that a diagnostic can show the code it is +//! about; that directory is left out of the diagnostics the tests see. #![allow(dead_code)] use std::collections::HashMap; @@ -15,8 +17,9 @@ pub fn runtime_dir() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../packages/@rescript/runtime") } - pub struct Project { + /// Where the files given by a relative name are written. + dir: PathBuf, registry: ModuleRegistry, /// Compiled JavaScript of the project's modules, for the macro engine. javascript: Arc>>, @@ -54,7 +57,15 @@ impl Project { } std::fs::read_to_string(runtime_dir().join(format!("lib/js/{name}.cjs"))).ok() }))); + static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let dir = std::env::temp_dir().join(format!( + "rescript-macro-tests-{}-{}", + std::process::id(), + NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + )); + std::fs::create_dir_all(&dir).unwrap(); let mut project = Project { + dir, registry, javascript, host, @@ -69,6 +80,12 @@ impl Project { pub fn compile(&mut self, filename: &str, source: &str) -> Result { let module_name = driver::module_name_from_source_filename(filename); + let path = self.dir.join(filename); + if std::path::Path::new(filename).is_relative() { + std::fs::write(&path, source).unwrap(); + } + let filename = path.to_str().unwrap(); + let prefix = format!("{}/", self.dir.display()); let host: Arc = self.host.clone(); let options = CompilerOptions { source_filename: Some(filename.to_string()), @@ -101,16 +118,33 @@ impl Project { ); } let text = |text: &str| { - rescript_compiler::source_text::decode_internal_utf8(text).into_owned() + rescript_compiler::source_text::decode_internal_utf8(text).replace(&prefix, "") }; let js = text(&compiled.js_output); - self.javascript.lock().unwrap().insert(module_name, js.clone()); + self.javascript + .lock() + .unwrap() + .insert(module_name, js.clone()); self.host.invalidate(); self.expanded = compiled.expanded_source.as_deref().map(text); self.warnings = text(&compiled.warnings); Ok(js) } - Err(e) => Err(rescript_compiler::source_text::decode_internal_utf8(&format!("{e:#}")).into_owned()), + Err(e) => Err( + rescript_compiler::source_text::decode_internal_utf8(&format!("{e:#}")) + .replace(&prefix, ""), + ), + } + } +} + +impl Drop for Project { + fn drop(&mut self) { + if let Ok(entries) = std::fs::read_dir(&self.dir) { + for entry in entries.flatten() { + let _ = std::fs::remove_file(entry.path()); + } } + let _ = std::fs::remove_dir(&self.dir); } } diff --git a/packages/@rescript/runtime/Macro.res b/packages/@rescript/runtime/Macro.res index b4cb45ab15..1e05fb6e0d 100644 --- a/packages/@rescript/runtime/Macro.res +++ b/packages/@rescript/runtime/Macro.res @@ -26,8 +26,11 @@ type declarations type decls = code /* The representation the compiler and the engine share: the source text, - and for a type the compiler's handle of it. */ -type rec node = {c: string, id?: int, t?: node, raw?: bool} + and for a type the compiler's handle of it. `m` says which parts of the + text are text from elsewhere, an argument of the macro or a quote: the + compiler reports an error in generated code with it. */ +type span +type rec node = {c: string, m?: array, id?: int, t?: node, raw?: bool} external toNode: 'a => node = "%identity" external ofNode: node => 'a = "%identity" @@ -35,6 +38,39 @@ external ofNode: node => 'a = "%identity" let make = (source: string): 'a => ofNode({c: source}) let source = (value: 'a): string => toNode(value).c +/* One node of several, in order. A span is `[start, length, ...origin]`. */ +let cat: array => node = %raw(`function (parts) { + var c = "", m; + for (var i = 0; i < parts.length; i++) { + var part = parts[i]; + if (part.m !== undefined) { + if (m === undefined) m = []; + for (var j = 0; j < part.m.length; j++) { + var span = part.m[j].slice(); + span[0] += c.length; + m.push(span); + } + } + c += part.c; + } + return m === undefined ? {c: c} : {c: c, m: m}; +}`) + +let text = (source: string): node => {c: source} +let build = (parts: array): 'a => ofNode(cat(parts)) + +/* The nodes with `separator` between them. */ +let join = (nodes: array, separator: string): node => { + let parts = [] + nodes->Array.forEachWithIndex((node, index) => { + if index > 0 { + parts->Array.push(text(separator)) + } + parts->Array.push(node) + }) + cat(parts) +} + type host @val external host: host = "__rescript_macro" @send external ask: (host, string) => 'a = "ask" @@ -74,27 +110,48 @@ type hole external __holeCode: code<'a> => hole = "%identity" external __holeType: typ => hole = "%identity" external __holePat: pat => hole = "%identity" -let __holeItem = (value: code<'a>): hole => ofNode({c: source(value), raw: true}) - -let quote = (pieces: array, holes: array): node => { - let text = ref(pieces->Array.getUnsafe(0)) - holes->Array.forEachWithIndex((hole, index) => { - let hole = toNode(hole) - let filled = hole.raw == Some(true) ? hole.c : "(" ++ hole.c ++ ")" - text := text.contents ++ filled ++ pieces->Array.getUnsafe(index + 1) - }) - {c: text.contents} -} +let __holeItem = (value: code<'a>): hole => ofNode({...toNode(value), raw: true}) + +/* A piece is the text between two holes: parts of the macro's file, each + with its line and column there (line 0: text that is not from the file). */ +type piece = array<(string, int, int)> + +let quote: (array, array, string) => node = %raw(`function (pieces, holes, file) { + var parts = []; + function add(piece) { + for (var i = 0; i < piece.length; i++) { + var fragment = piece[i]; + parts.push( + fragment[1] > 0 + ? {c: fragment[0], m: [[0, fragment[0].length, file, fragment[1], fragment[2]]]} + : {c: fragment[0]} + ); + } + } + add(pieces[0]); + for (var i = 0; i < holes.length; i++) { + var hole = holes[i]; + if (hole.raw === true) { + parts.push(hole); + } else { + parts.push({c: "("}, hole, {c: ")"}); + } + add(pieces[i + 1]); + } + return cat(parts); +}`) -let __quoteCode = (pieces, holes): code<'a> => ofNode(quote(pieces, holes)) -let __quoteDecls = (pieces, holes): decls => ofNode(quote(pieces, holes)) -let __quoteType = (pieces, holes): typ => ofNode(quote(pieces, holes)) -let __quotePat = (pieces, holes): pat => ofNode(quote(pieces, holes)) +let __quoteCode = (pieces, holes, file): code<'a> => ofNode(quote(pieces, holes, file)) +let __quoteDecls = (pieces, holes, file): decls => ofNode(quote(pieces, holes, file)) +let __quoteType = (pieces, holes, file): typ => ofNode(quote(pieces, holes, file)) +let __quotePat = (pieces, holes, file): pat => ofNode(quote(pieces, holes, file)) let isSimple: string => bool = %raw(`function (text) { return /^[A-Za-z_][A-Za-z0-9_$.]*$/.test(text) }`) let atom = (text: string) => isSimple(text) ? text : "(" ++ text ++ ")" +/* `node` where an operand is expected: in parentheses unless it is a name. */ +let atomNode = (node: node): node => isSimple(node.c) ? node : cat([text("("), node, text(")")]) module Attr = { /** An attribute: `@Json.key("user_age")` has the name `Json.key` and the payload `user_age`. */ @@ -266,31 +323,40 @@ module Code = { let ident = (name: string): code<'a> => make(name) /** `value.name` */ - let field = (value: code<'a>, name: string): code<'b> => make(atom(source(value)) ++ "." ++ name) + let field = (value: code<'a>, name: string): code<'b> => build([atomNode(toNode(value)), text("." ++ name)]) /** `[a, b, c]` */ let array = (items: array>): code> => - make("[" ++ items->Array.map(source)->Array.join(", ") ++ "]") + build([text("["), join(items->Array.map(toNode), ", "), text("]")]) /** `(a, b, c)` */ - let tuple = (items: array>): code<'b> => make("(" ++ items->Array.map(source)->Array.join(", ") ++ ")") + let tuple = (items: array>): code<'b> => + build([text("("), join(items->Array.map(toNode), ", "), text(")")]) /** `{name: value, ...}` */ let record = (fields: array<(string, code<'a>)>): code<'b> => - make("{" ++ fields->Array.map(((name, value)) => name ++ ": " ++ source(value))->Array.join(", ") ++ "}") + build([ + text("{"), + join(fields->Array.map(((name, value)) => cat([text(name ++ ": "), toNode(value)])), ", "), + text("}"), + ]) /** `f(a, b)` */ let call = (f: code<'a>, args: array>): code<'c> => - make(atom(source(f)) ++ "(" ++ args->Array.map(source)->Array.join(", ") ++ ")") + build([atomNode(toNode(f)), text("("), join(args->Array.map(toNode), ", "), text(")")]) /** `switch value { | pattern => body ... }` */ let switch_ = (value: code<'a>, arms: array<(pat, code<'b>)>): code<'b> => - make( - "switch " ++ - atom(source(value)) ++ - " {\n" ++ - arms->Array.map(((pattern, body)) => "| " ++ source(pattern) ++ " => " ++ source(body))->Array.join("\n") ++ "\n}", - ) + build([ + text("switch "), + atomNode(toNode(value)), + text(" {\n"), + join( + arms->Array.map(((pattern, body)) => cat([text("| "), toNode(pattern), text(" => "), toNode(body)])), + "\n", + ), + text("\n}"), + ]) /** A parameter of `fn`. */ type param = string @@ -303,10 +369,10 @@ module Code = { /** `(params) => body` */ let fn = (params: array, body: code<'a>): code<'f> => - make("(" ++ params->Array.join(", ") ++ ") => " ++ source(body)) + build([text("(" ++ params->Array.join(", ") ++ ") => "), toNode(body)]) /** Several declarations, one after the other. */ - let decls = (items: array): decls => make(items->Array.map(source)->Array.join("\n")) + let decls = (items: array): decls => build([join(items->Array.map(toNode), "\n")]) } module Pat = { diff --git a/packages/@rescript/runtime/lib/es6/Macro.mjs b/packages/@rescript/runtime/lib/es6/Macro.mjs index f8f932ccd2..e689b651aa 100644 --- a/packages/@rescript/runtime/lib/es6/Macro.mjs +++ b/packages/@rescript/runtime/lib/es6/Macro.mjs @@ -1,7 +1,6 @@ import * as Stdlib_Type from "./Stdlib_Type.mjs"; -import * as Primitive_object from "./Primitive_object.mjs"; import * as Primitive_option from "./Primitive_option.mjs"; function make(source) { @@ -14,6 +13,44 @@ function source(value) { return value.c; } +let cat = (function (parts) { + var c = "", m; + for (var i = 0; i < parts.length; i++) { + var part = parts[i]; + if (part.m !== undefined) { + if (m === undefined) m = []; + for (var j = 0; j < part.m.length; j++) { + var span = part.m[j].slice(); + span[0] += c.length; + m.push(span); + } + } + c += part.c; + } + return m === undefined ? {c: c} : {c: c, m: m}; +}); + +function text(source) { + return { + c: source + }; +} + +function build(parts) { + return cat(parts); +} + +function join(nodes, separator) { + let parts = []; + nodes.forEach((node, index) => { + if (index > 0) { + parts.push(text(separator)); + } + parts.push(node); + }); + return cat(parts); +} + function error(message) { return __rescript_macro.fail(message, undefined); } @@ -50,29 +87,51 @@ function env(name) { function __holeItem(value) { return { - c: value.c, + ...value, raw: true }; } -function quote(pieces, holes) { - let text = pieces[0]; - holes.forEach((hole, index) => { - let filled = Primitive_object.equal(hole.raw, true) ? hole.c : "(" + hole.c + ")"; - text = text + filled + pieces[index + 1 | 0]; - }); - return { - c: text - }; -} +let quote = (function (pieces, holes, file) { + var parts = []; + function add(piece) { + for (var i = 0; i < piece.length; i++) { + var fragment = piece[i]; + parts.push( + fragment[1] > 0 + ? {c: fragment[0], m: [[0, fragment[0].length, file, fragment[1], fragment[2]]]} + : {c: fragment[0]} + ); + } + } + add(pieces[0]); + for (var i = 0; i < holes.length; i++) { + var hole = holes[i]; + if (hole.raw === true) { + parts.push(hole); + } else { + parts.push({c: "("}, hole, {c: ")"}); + } + add(pieces[i + 1]); + } + return cat(parts); +}); -let __quoteCode = quote; +function __quoteCode(pieces, holes, file) { + return quote(pieces, holes, file); +} -let __quoteDecls = quote; +function __quoteDecls(pieces, holes, file) { + return quote(pieces, holes, file); +} -let __quoteType = quote; +function __quoteType(pieces, holes, file) { + return quote(pieces, holes, file); +} -let __quotePat = quote; +function __quotePat(pieces, holes, file) { + return quote(pieces, holes, file); +} let isSimple = (function (text) { return /^[A-Za-z_][A-Za-z0-9_$.]*$/.test(text) @@ -86,6 +145,22 @@ function atom(text) { } } +function atomNode(node) { + if (isSimple(node.c)) { + return node; + } else { + return cat([ + { + c: "(" + }, + node, + { + c: ")" + } + ]); + } +} + function find(attrs, name) { return attrs.find(attr => attr.name === name); } @@ -228,27 +303,87 @@ let raw = make; let ident = make; function field$1(value, name) { - return make(atom(value.c) + "." + name); + return cat([ + atomNode(value), + text("." + name) + ]); } function array(items) { - return make("[" + items.map(source).join(", ") + "]"); + return cat([ + { + c: "[" + }, + join(items.map(prim => prim), ", "), + { + c: "]" + } + ]); } function tuple(items) { - return make("(" + items.map(source).join(", ") + ")"); + return cat([ + { + c: "(" + }, + join(items.map(prim => prim), ", "), + { + c: ")" + } + ]); } function record$1(fields) { - return make("{" + fields.map(param => param[0] + ": " + param[1].c).join(", ") + "}"); + return cat([ + { + c: "{" + }, + join(fields.map(param => cat([ + text(param[0] + ": "), + param[1] + ])), ", "), + { + c: "}" + } + ]); } function call(f, args) { - return make(atom(f.c) + "(" + args.map(source).join(", ") + ")"); + return cat([ + atomNode(f), + { + c: "(" + }, + join(args.map(prim => prim), ", "), + { + c: ")" + } + ]); } function switch_(value, arms) { - return make("switch " + atom(value.c) + " {\n" + arms.map(param => "| " + param[0].c + " => " + param[1].c).join("\n") + "\n}"); + return cat([ + { + c: "switch " + }, + atomNode(value), + { + c: " {\n" + }, + join(arms.map(param => cat([ + { + c: "| " + }, + param[0], + { + c: " => " + }, + param[1] + ])), "\n"), + { + c: "\n}" + } + ]); } function param(name, typ) { @@ -260,11 +395,14 @@ function labelled(name, typ) { } function fn(params, body) { - return make("(" + params.join(", ") + ") => " + body.c); + return cat([ + text("(" + params.join(", ") + ") => "), + body + ]); } function decls(items) { - return make(items.map(source).join("\n")); + return cat([join(items.map(prim => prim), "\n")]); } let Code = { @@ -340,6 +478,10 @@ let Decl = {}; export { make, source, + cat, + text, + build, + join, error, errorAt, typeOf, @@ -354,6 +496,7 @@ export { __quotePat, isSimple, atom, + atomNode, Attr, Type, Code, diff --git a/packages/@rescript/runtime/lib/js/Macro.cjs b/packages/@rescript/runtime/lib/js/Macro.cjs index 95b35608ae..2bcca5c0d7 100644 --- a/packages/@rescript/runtime/lib/js/Macro.cjs +++ b/packages/@rescript/runtime/lib/js/Macro.cjs @@ -1,7 +1,6 @@ 'use strict'; let Stdlib_Type = require("./Stdlib_Type.cjs"); -let Primitive_object = require("./Primitive_object.cjs"); let Primitive_option = require("./Primitive_option.cjs"); function make(source) { @@ -14,6 +13,44 @@ function source(value) { return value.c; } +let cat = (function (parts) { + var c = "", m; + for (var i = 0; i < parts.length; i++) { + var part = parts[i]; + if (part.m !== undefined) { + if (m === undefined) m = []; + for (var j = 0; j < part.m.length; j++) { + var span = part.m[j].slice(); + span[0] += c.length; + m.push(span); + } + } + c += part.c; + } + return m === undefined ? {c: c} : {c: c, m: m}; +}); + +function text(source) { + return { + c: source + }; +} + +function build(parts) { + return cat(parts); +} + +function join(nodes, separator) { + let parts = []; + nodes.forEach((node, index) => { + if (index > 0) { + parts.push(text(separator)); + } + parts.push(node); + }); + return cat(parts); +} + function error(message) { return __rescript_macro.fail(message, undefined); } @@ -50,29 +87,51 @@ function env(name) { function __holeItem(value) { return { - c: value.c, + ...value, raw: true }; } -function quote(pieces, holes) { - let text = pieces[0]; - holes.forEach((hole, index) => { - let filled = Primitive_object.equal(hole.raw, true) ? hole.c : "(" + hole.c + ")"; - text = text + filled + pieces[index + 1 | 0]; - }); - return { - c: text - }; -} +let quote = (function (pieces, holes, file) { + var parts = []; + function add(piece) { + for (var i = 0; i < piece.length; i++) { + var fragment = piece[i]; + parts.push( + fragment[1] > 0 + ? {c: fragment[0], m: [[0, fragment[0].length, file, fragment[1], fragment[2]]]} + : {c: fragment[0]} + ); + } + } + add(pieces[0]); + for (var i = 0; i < holes.length; i++) { + var hole = holes[i]; + if (hole.raw === true) { + parts.push(hole); + } else { + parts.push({c: "("}, hole, {c: ")"}); + } + add(pieces[i + 1]); + } + return cat(parts); +}); -let __quoteCode = quote; +function __quoteCode(pieces, holes, file) { + return quote(pieces, holes, file); +} -let __quoteDecls = quote; +function __quoteDecls(pieces, holes, file) { + return quote(pieces, holes, file); +} -let __quoteType = quote; +function __quoteType(pieces, holes, file) { + return quote(pieces, holes, file); +} -let __quotePat = quote; +function __quotePat(pieces, holes, file) { + return quote(pieces, holes, file); +} let isSimple = (function (text) { return /^[A-Za-z_][A-Za-z0-9_$.]*$/.test(text) @@ -86,6 +145,22 @@ function atom(text) { } } +function atomNode(node) { + if (isSimple(node.c)) { + return node; + } else { + return cat([ + { + c: "(" + }, + node, + { + c: ")" + } + ]); + } +} + function find(attrs, name) { return attrs.find(attr => attr.name === name); } @@ -228,27 +303,87 @@ let raw = make; let ident = make; function field$1(value, name) { - return make(atom(value.c) + "." + name); + return cat([ + atomNode(value), + text("." + name) + ]); } function array(items) { - return make("[" + items.map(source).join(", ") + "]"); + return cat([ + { + c: "[" + }, + join(items.map(prim => prim), ", "), + { + c: "]" + } + ]); } function tuple(items) { - return make("(" + items.map(source).join(", ") + ")"); + return cat([ + { + c: "(" + }, + join(items.map(prim => prim), ", "), + { + c: ")" + } + ]); } function record$1(fields) { - return make("{" + fields.map(param => param[0] + ": " + param[1].c).join(", ") + "}"); + return cat([ + { + c: "{" + }, + join(fields.map(param => cat([ + text(param[0] + ": "), + param[1] + ])), ", "), + { + c: "}" + } + ]); } function call(f, args) { - return make(atom(f.c) + "(" + args.map(source).join(", ") + ")"); + return cat([ + atomNode(f), + { + c: "(" + }, + join(args.map(prim => prim), ", "), + { + c: ")" + } + ]); } function switch_(value, arms) { - return make("switch " + atom(value.c) + " {\n" + arms.map(param => "| " + param[0].c + " => " + param[1].c).join("\n") + "\n}"); + return cat([ + { + c: "switch " + }, + atomNode(value), + { + c: " {\n" + }, + join(arms.map(param => cat([ + { + c: "| " + }, + param[0], + { + c: " => " + }, + param[1] + ])), "\n"), + { + c: "\n}" + } + ]); } function param(name, typ) { @@ -260,11 +395,14 @@ function labelled(name, typ) { } function fn(params, body) { - return make("(" + params.join(", ") + ") => " + body.c); + return cat([ + text("(" + params.join(", ") + ") => "), + body + ]); } function decls(items) { - return make(items.map(source).join("\n")); + return cat([join(items.map(prim => prim), "\n")]); } let Code = { @@ -339,6 +477,10 @@ let Decl = {}; exports.make = make; exports.source = source; +exports.cat = cat; +exports.text = text; +exports.build = build; +exports.join = join; exports.error = error; exports.errorAt = errorAt; exports.typeOf = typeOf; @@ -353,6 +495,7 @@ exports.__quoteType = __quoteType; exports.__quotePat = __quotePat; exports.isSimple = isSimple; exports.atom = atom; +exports.atomNode = atomNode; exports.Attr = Attr; exports.Type = Type; exports.Code = Code; From baef1b0f7c014fe7f3912bf90217aa2daabdb7cd Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 15:16:55 +0100 Subject: [PATCH 20/38] macros: a range across two macro uses keeps both ends A range that starts in the code of one use and ends in the code of another took the start of the second. Each end now maps by itself, and only a range with one end in an argument is widened to the use. Co-authored-by: Jaap Frolich Session: https://jakes-mac-mini.tail23a77e.ts.net:8443/session/os-01a1ca09-2757-709a-bbb1-e57ccc4d104f Signed-off-by: Jaap Frolich --- compiler-rust/src/macros/edit.rs | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/compiler-rust/src/macros/edit.rs b/compiler-rust/src/macros/edit.rs index fd29437bae..6db5d78643 100644 --- a/compiler-rust/src/macros/edit.rs +++ b/compiler-rust/src/macros/edit.rs @@ -245,25 +245,31 @@ impl SourceText { let at = self.origin(from); return (at, at); } - let first = self.generated(from); - let last = self.generated(to - 1); + // For a generated character these are the start and the end of its + // macro use. let mut range = (self.origin(from), self.origin_end(to)); // The rest of a range that is partly in generated code is an // argument of the same use. - if let Some(last) = &last - && (first.is_some() || (last.use_start..last.use_end).contains(&range.0)) - { - range.0 = last.use_start; - } - if let Some(first) = &first - && (last.is_some() - || (first.use_start..first.use_end).contains(&range.1.saturating_sub(1))) - { - range.1 = first.use_end; + match (self.use_at(from), self.use_at(to - 1)) { + (None, Some(last)) if (last.start..last.end).contains(&range.0) => range.0 = last.start, + (Some(first), None) + if (first.start..first.end).contains(&range.1.saturating_sub(1)) => + { + range.1 = first.end; + } + _ => {} } (range.0, range.1.max(range.0)) } + /// The macro use the character at `offset` was generated for. + fn use_at(&self, offset: u32) -> Option { + match self.marks[(offset as usize).min(self.marks.len() - 1)].use_id { + 0 => None, + id => Some(self.uses[id as usize - 1]), + } + } + /// The generated code that the characters `from..to` are in: `None` for /// a range that starts and ends in the source as written, also when it /// has a macro use inside it, and for the compiler's own rewriting. From bec767fb69264416efa39a0cf1a6a6282a1c5f76 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 15:17:59 +0100 Subject: [PATCH 21/38] docs: what macro errors say The RFC's section on errors shows the diagnostics as they are now, and the implementation notes describe where a character of an expanded file comes from and how a diagnostic uses it. Checking a quote where it is written replaces positions in generated code among the next steps. Co-authored-by: Jaap Frolich Session: https://jakes-mac-mini.tail23a77e.ts.net:8443/session/os-01a1ca09-2757-709a-bbb1-e57ccc4d104f Signed-off-by: Jaap Frolich --- docs/comptime/IMPLEMENTATION.md | 81 +++++++++++++++++++++++------ docs/comptime/README.md | 91 +++++++++++++++++++++++++++++---- 2 files changed, 145 insertions(+), 27 deletions(-) diff --git a/docs/comptime/IMPLEMENTATION.md b/docs/comptime/IMPLEMENTATION.md index 1a527602bc..6632f54615 100644 --- a/docs/comptime/IMPLEMENTATION.md +++ b/docs/comptime/IMPLEMENTATION.md @@ -12,12 +12,14 @@ compiler. Read that first. | `compiler-rust/src/macros/discover.rs` | The type checker's hooks: recognizing macro uses, running the macro, recording edits, instances of generics. | | `compiler-rust/src/macros/quote.rs` | Lowering `%code`, `%type` and `%pat` in a macro's own file. | | `compiler-rust/src/macros/reflect.rs` | Answers about types: `Type.info`, printing a type as source, the literal shape of a `%comptime` value. | -| `compiler-rust/src/macros/edit.rs` | `SourceText`: text with a map back to the original, and edits on it. | +| `compiler-rust/src/macros/edit.rs` | `SourceText`: text that knows where each character comes from, and edits on it. | +| `compiler-rust/src/macros/report.rs` | What a diagnostic says about generated code. | | `compiler-rust/src/macros/host.js` | The engine side: module loader, sandbox, call entry point. The same script in QuickJS and in the browser. | | `compiler-rust/src/macros/quickjs.rs` | The engine of native builds (feature `macro-quickjs`, part of `native`). | | `packages/@rescript/runtime/Macro.res` | The API macros are written against. | | `compiler-rust/src/parser` | `${...}` holes, the payloads of quotes, macro arguments. | -| `compiler-rust/tests/macros.rs` | End-to-end tests: small projects compiled in memory. | +| `compiler-rust/tests/macros.rs` | End-to-end tests: small projects, the JavaScript and the expanded source. | +| `compiler-rust/tests/macro_errors.rs` | The diagnostics of broken programs, compared with `tests/macro_errors/*.txt`. | | `playground/` | The browser playground and its host. | ## Parsing @@ -80,11 +82,41 @@ expanded file is a thing a person can read. Its cost is a type check of the file per pass. Changing it later does not change the language: the surface (`code<'a>`, quotes, `Macro`) does not say how code is represented. -`SourceText` keeps, for every character, the offset in the original file it -stands for: itself for text that was there, the start of the replaced range -for generated text. `expand::remap_positions` rewrites every position in the -parse arena of the expanded text through that map, so everything after -parsing sees original positions. +`SourceText` keeps, for every character, where it comes from: + +- a character of the file as written has its offset in that file, also when + it is an argument that a macro put in its result; +- a generated character has the macro use it was generated for, and, when it + was written in a quote, the file, line and column of that quote. A + function generated for a `@generic` is generated for the call that needed + it and has a description, "`Json.encode` for `user`". Code generated + inside generated code belongs to the use in the file as written. + +`expand::remap_positions` rewrites every position in the parse arena of the +expanded text through that map, so everything after parsing sees original +positions. It goes by location: one that starts or ends in generated code +covers the macro use, one inside an argument stays where the argument is. +The arena keeps the expansion (`ParseArena::expansion`): the text, and the +offset each position had in it. + +## Diagnostics + +A diagnostic in generated code is reported at the macro use. When the driver +prints the frame of a location (`push_generated_code_note` in `driver.rs`, +for errors and warnings), it asks the expansion what is at the location's +offsets in the expanded text. For generated code, `report.rs` adds a note +after the frame: the lines of the quote the code was written in, read from +the macro's file, or, for code that is not from a quote (`Code.raw`, the +builders), the lines of the expanded source. + +Errors of expansion itself (a macro that reports or raises, generated code +that does not parse, passes that run out) go through `expand::diagnostic`, +which places and annotates them the same way. + +The final compilation of an expanded file runs with +`MacroMode::Expanded`. A macro use that is still there is typed by its +declared type instead of stopping the compilation: it is there because +something near it has an error, and that error is the one to report. ## Quotes @@ -93,18 +125,28 @@ parsing sees original positions. ```rescript %code(JSON.Encode.string(${value})) // becomes -(Macro.__quoteCode(["JSON.Encode.string(", ")"], [Macro.__holeCode(value)])) +(Macro.__quoteCode( + [[("JSON.Encode.string(", 9, 20)], [(")", 9, 48)]], + [Macro.__holeCode(value)], + "Json.res", +)) ``` -The pieces are the source text around the holes. `__holeCode`, `__holeType` +The pieces are the source text around the holes, each with the line and +column it has in the macro's file. A code value is `{c: text, m: spans}`: +`m` lists which parts of the text are a piece of a quote or an argument of +the macro (an argument arrives with `$o`, the compiler's name for its range). +`Macro` keeps the spans when it builds code from parts (`cat` in +`Macro.res`), and the engine returns them with the code. That is how a +character of the expanded text gets its origin. `__holeCode`, `__holeType` and `__holePat` are identity functions whose types make the hole's expression check as `code<'a>`, `typ` or `pat`; `__holeItem` is for a hole that stands where a whole declaration does. A quote of declarations lowers to `__quoteDecls`. At run time a quote is string concatenation, with parentheses around each filled hole except a declaration. -While it copies a piece, the lowering qualifies the top-level value and -module names of the macro's own file with the file's module name, so that +While it copies a piece, the lowering puts the file's module name in front +of the top-level value and module names of the macro's own file, so that `encode(v)` inside a quote in `Json.res` reads `Json.encode(v)` at the use. This is the only hygiene there is so far. @@ -189,7 +231,8 @@ it, turning ES module output into CommonJS by text when needed. "answers": {"info:1": {"TAG": "Record", "name": "user", "fields": []}}} ``` -The response is `{"ok": ""}`, `{"error": "...", "offset": n}` or +The response is `{"ok": "", "spans": [...]}`, `{"error": "..."}` (with +`"exception": true` when the macro raised instead of reporting) or `{"need": ""}`. A question is `info:`, `companion::`, `readFile:` or `env:`. On `need` the compiler adds the answer and calls again (`Discovery::run`). Answers @@ -225,9 +268,11 @@ the runtime: they are checked with the runtime package's flags ## Tests `cargo test --manifest-path compiler-rust/Cargo.toml --test macros` compiles -small projects in memory, with QuickJS as the engine, and checks the -JavaScript and the expanded source. One test compiles every example of the -playground. `playground/scripts/smoke.mjs` builds and runs the same examples +small projects, with QuickJS as the engine, and checks the JavaScript and +the expanded source. One test compiles every example of the playground. +`--test macro_errors` compiles broken programs and compares what the +compiler says with `tests/macro_errors/*.txt`; `UPDATE_EXPECTED=1` rewrites +those files. `playground/scripts/smoke.mjs` builds and runs the same examples with the compiler in WebAssembly. ## Next steps @@ -244,8 +289,10 @@ In the order that seems right: interfaces `Type.info` looked at as inputs of the module, next to the `reads` the build already tracks. 3. **Hygiene.** Rename the binders a quote introduces per expansion. -4. **Positions inside generated code**, using the quote's pieces to map an - offset in generated text to an offset in the macro's file. +4. **Check a quote where it is written.** A quote is text until a use + expands it, so `%code(${e} + 1)` returned as `code` is found at + the use, not in the macro's file. Typing a quote's content against its + holes at definition would catch it there. 5. **`rescript expand `** and the editor: show the expansion; hover and definitions inside macro arguments. 6. **Port ppx-spice** to a library of macros, with the Rust port as the diff --git a/docs/comptime/README.md b/docs/comptime/README.md index b3a5badee8..0afb35deb4 100644 --- a/docs/comptime/README.md +++ b/docs/comptime/README.md @@ -478,25 +478,95 @@ greet(~name="Alice", ~count="3") 7 │ // A key that is not in en.json does not compile: 8 │ let oops = %I18n.t("goodbye") - I18n.t: There is no message "goodbye" in en.json. It has: title, greeting, empty + There is no message "goodbye" in en.json. It has: title, greeting, empty + + This is reported by the macro `I18n.t`. ``` ### Errors +An error is reported in the code the person wrote, and says what the macro +has to do with it. + `Macro.error(message)` stops compilation with the message at the macro use, -as above. Code a macro generates is type checked like written code, and a -type error in it is reported at the macro use. A syntax error in generated -code shows the generated code: +as above. A macro that raises an exception is reported there too, as +"The macro `I18n.t` raised an exception". + +An error in an argument points at the argument, because the argument is +still the text that was written: + +``` + We've found a bug for you! + Main.res:1:24-26 + + 1 │ let x = %Debug.log(1 + "a") + + This has type: string + But it's expected to have type: int +``` + +Code a macro generates is type checked like written code. An error or a +warning in it is reported at the macro use, followed by the place in the +macro where that code is written: + +``` + We've found a bug for you! + Main.res:2:9-28 + + 1 │ let a = 1 + 2 │ let x = %Quoted.twice(a + 1) + + This is in the code the macro generated, written at Quoted.res:7:9-13 + + 5 ┆ %code({ + 6 ┆ let v = ${e} + 7 ┆ v + "two" + 8 ┆ }) + + This has type: string + But it's expected to have type: int +``` + +In a function generated for a `@generic`, the note says which one. Here a +field of `t` is a function, and the error is at the call that needed +`Json.encode` for `t`: ``` -A macro generated code with a syntax error. The frame shows the expanded source. + We've found a bug for you! + Main.res:2:21-31 + + 1 │ type t = {name: string, f: int => int} + 2 │ let enc = (t: t) => Json.encode(t) + + This is in the code generated by `Json.encode` for `t`, written at Json.res:25:35-40 + + 24 ┆ let key = f.attrs->Attr.string("Json.key")->Option.getOr(f.jsName) + 25 ┆ %code((${Code.string(key)}, encode(${value->Code.field(f.name)}))) + 26 ┆ }) + Json.encode cannot encode the type int => int + + This is reported by the macro `Json.encode`. +``` + +Code that is not written in a quote (`Code.raw`, the builders) is shown as +it is in the expanded source. So is generated code that does not parse: + +``` Syntax error! - UseBad.res:1:13 + Main.res:2:9-24 + + 1 │ let a = 1 + 2 │ let x = %Throws.syntax() + 3 │ let b = 2 + + This is in the code the macro generated. In the expanded source: - 1 │ let x = (1 +) + 1 │ let a = 1 + 2 │ let x = (let = 1 +) + 3 │ let b = 2 - Did you forget to write an expression here? + I'm not sure what to parse here when looking at "let". ``` ## Reference @@ -709,8 +779,9 @@ implemented: - **Hygiene for binders.** A `let` inside a quote can capture a name used by argument code. The plan is a fresh mark per expansion on binders that a quote introduces, with `Code.ident` as the explicit way out. -- **Positions inside generated code.** A type error in generated code is - reported at the macro use, not at the place in the quote. +- **A quote is checked where it is used.** An error in generated code names + the place in the quote, but only once a use expands it: a macro whose + quote cannot have the type the macro declares compiles until then. - **Attribute payloads beyond one string.** `@Json.key("user_age")` reaches the macro; `@Json.codec({strict: true})` does not yet pass its argument. - **Parametric types.** `Type.info` of `result` or a record with type From 2f1fbbe63f27ecb3d9b05674c73caedd2b8b132c Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 15:12:12 +0100 Subject: [PATCH 22/38] parser: splice holes `${...items}` in macro quotes A splice hole stands for any number of items of a list. It is the extension `res.hole.splice`: an expression where an expression is an item (arguments, array and tuple items), a row of a record, and a case of a switch. A block does not continue into a splice hole, so that one after a case of a switch is the next case. Co-authored-by: Jaap Frolich Session: https://jakes-mac-mini.tail23a77e.ts.net:8443/session/os-01a1caab-4faf-7817-951e-2b3f9a5dae19 Signed-off-by: Jaap Frolich --- compiler-rust/src/parser/expr.rs | 60 +++++++++++++++++++++++++++-- compiler-rust/src/parser/grammar.rs | 3 +- compiler-rust/src/parser/module.rs | 26 ++++++++++++- 3 files changed, 83 insertions(+), 6 deletions(-) diff --git a/compiler-rust/src/parser/expr.rs b/compiler-rust/src/parser/expr.rs index b421bdf312..b8ea79a6ed 100644 --- a/compiler-rust/src/parser/expr.rs +++ b/compiler-rust/src/parser/expr.rs @@ -135,6 +135,13 @@ fn is_valid_bigint_literal(s: &str) -> bool { // Placeholder Transformation // ============================================================================ +/// Whether the next token continues a block with another expression. A +/// splice hole `${...cases}` after a case of a switch does not: it stands +/// for more cases, not for an expression of the case before it. +fn block_continues(p: &mut Parser<'_>) -> bool { + grammar::is_block_expr_start(&p.token) && !super::module::at_splice_hole(p) +} + /// Check and emit "consecutive expressions" error if expressions on same line without semicolon. /// /// Matches OCaml's `parse_newline_or_semicolon_expr_block`: @@ -147,7 +154,7 @@ pub fn parse_newline_or_semicolon_expr_block(p: &mut Parser<'_>) { return; } - if grammar::is_block_expr_start(&p.token) { + if block_continues(p) { // Check if we're on the same line as the previous token // OCaml: if p.prev_end_pos.pos_lnum < p.start_pos.pos_lnum then () else err if p.prev_end_pos.line >= p.start_pos.line { @@ -3177,6 +3184,12 @@ fn parse_braced_or_record_expr(p: &mut Parser<'_>) -> Expression { p.expect(Token::Rbrace); expr } + // `{${...fields}}`: a record whose first row is a splice hole. + Token::DollarLbrace if super::module::at_splice_hole(p) => { + let expr = parse_record_expr(p, start_pos_idx, None, vec![]); + p.expect(Token::Rbrace); + expr + } Token::Lident(ref s) if s == "async" && super::core::is_es6_arrow_expression(p, false) => { p.expect(Token::Lident("async".into())); let expr = @@ -3376,6 +3389,14 @@ fn remove_module_name_from_punned_field_value(p: &mut Parser<'_>, exp: Expressio /// OCaml `parse_record_expr_row` (compiler/syntax/src/res_core.ml:3440-3508). fn parse_record_expr_row(p: &mut Parser<'_>) -> Option { + if super::module::at_splice_hole(p) { + let (lid, expr) = parse_splice_hole_row(p); + return Some(ExpressionRecordField { + lid, + expr, + opt: false, + }); + } let attrs = parse_attributes(p); if p.token == Token::DotDotDot { p.err(DiagnosticCategory::Message( @@ -3688,7 +3709,7 @@ fn parse_expr_block_item(p: &mut Parser<'_>) -> Expression { let (rec_flag, bindings) = super::module::parse_let_bindings_item(p, unwrap, attrs, start_pos_idx); parse_newline_or_semicolon_expr_block(p); - let next = if grammar::is_block_expr_start(&p.token) { + let next = if block_continues(p) { parse_expr_block(p) } else { let loc = p.mk_loc_current(); @@ -3731,7 +3752,7 @@ fn parse_expr_block_item(p: &mut Parser<'_>) -> Expression { e1.pexp_attributes = all; } parse_newline_or_semicolon_expr_block(p); - if grammar::is_block_expr_start(&p.token) { + if block_continues(p) { let e2 = parse_expr_block(p); let loc = p.mk_loc_spanning_preserve_ghost(e1.pexp_loc, e2.pexp_loc); let e1 = p.arena_mut().push_expr(e1); @@ -3761,7 +3782,7 @@ fn parse_expr_block_first(p: &mut Parser<'_>, first: Option) -> Expr None => parse_expr_block_item(p), }; parse_newline_or_semicolon_expr_block(p); - let block_expr = if grammar::is_block_expr_start(&p.token) { + let block_expr = if block_continues(p) { let next = parse_expr_block_item(p); let loc = p.mk_loc_spanning_preserve_ghost(item.pexp_loc, next.pexp_loc); let item = p.arena_mut().push_expr(item); @@ -4161,8 +4182,39 @@ fn parse_pattern_matching(p: &mut Parser<'_>) -> Vec { cases } +/// A splice hole that stands for rows of a record or cases of a switch: +/// the hole as an expression, and a name for the place the row or case +/// keeps for it. Only the lowering of a quote reads it. +fn parse_splice_hole_row(p: &mut Parser<'_>) -> (Loc, ExprIdx) { + let start_pos_idx = p.start_pos_idx(); + let extension = super::module::parse_hole_extension(p); + let loc = p.mk_loc_idx_to_prev_end(start_pos_idx); + let expr = p.arena_mut().push_expr(Expression { + pexp_desc: ExpressionDesc::Pexp_extension(Box::new(extension)), + pexp_loc: loc, + pexp_attributes: Attributes::new(), + }); + let lid = p.push_lident_static(super::module::SPLICE_HOLE_EXTENSION); + (with_loc(lid, loc), expr) +} + /// OCaml `parse_pattern_match_case` (compiler/syntax/src/res_core.ml:3972-3995). fn parse_pattern_match_case(p: &mut Parser<'_>) -> Option { + // `switch x { | A => 1 ${...cases} }`: cases a macro quote splices in. + if super::module::at_splice_hole(p) { + let (lid, rhs) = parse_splice_hole_row(p); + let lhs = p.arena_mut().push_pat(Pattern { + ppat_desc: PatternDesc::Ppat_any, + ppat_loc: lid.loc, + ppat_attributes: Attributes::new(), + }); + return Some(Case { + pc_bar: None, + pc_lhs: lhs, + pc_guard: None, + pc_rhs: rhs, + }); + } p.begin_region(); p.leave_breadcrumb(Grammar::PatternMatchCase); if p.token != Token::Bar { diff --git a/compiler-rust/src/parser/grammar.rs b/compiler-rust/src/parser/grammar.rs index 2f81aed7fb..9b2805188c 100644 --- a/compiler-rust/src/parser/grammar.rs +++ b/compiler-rust/src/parser/grammar.rs @@ -529,7 +529,8 @@ pub fn is_dict_row_start(token: &Token<'_>) -> bool { pub fn is_record_row_start(token: &Token<'_>) -> bool { matches!( token, - Token::DotDotDot | Token::Uident(_) | Token::Lident(_) + // `${`: a splice hole of a macro quote, `{a: 1, ${...fields}}`. + Token::DotDotDot | Token::Uident(_) | Token::Lident(_) | Token::DollarLbrace ) || token.is_keyword() } diff --git a/compiler-rust/src/parser/module.rs b/compiler-rust/src/parser/module.rs index 051118a2f1..ea352d263e 100644 --- a/compiler-rust/src/parser/module.rs +++ b/compiler-rust/src/parser/module.rs @@ -4112,18 +4112,42 @@ pub fn parse_extension_id(p: &mut Parser<'_>, start_pos_idx: PosIdx) -> Located< /// Name of the extension a macro quote hole `${expr}` is kept as. pub const HOLE_EXTENSION: &str = "res.hole"; +/// Name of the extension a splice hole `${...expr}` is kept as. +pub const SPLICE_HOLE_EXTENSION: &str = "res.hole.splice"; + +/// Whether the parser is at `${...`: the start of a splice hole. +pub(super) fn at_splice_hole(p: &mut Parser<'_>) -> bool { + p.token == Token::DollarLbrace + && p.lookahead(|p| { + p.next(); + p.token == Token::DotDotDot + }) +} + /// `${expr}`: a hole in a macro quote (`%code(...)`, `%type(...)`, /// `%pat(...)`). It is an extension node named [`HOLE_EXTENSION`] whose /// payload is the expression, so no parsetree node kind is added. +/// +/// `${...expr}` is a splice hole: it stands for the items of a list (the +/// arguments of a call, the fields of a record, the cases of a switch), and +/// is the extension [`SPLICE_HOLE_EXTENSION`]. pub(super) fn parse_hole_extension(p: &mut Parser<'_>) -> Extension { let start_pos_idx = p.start_pos_idx(); p.expect(Token::DollarLbrace); + let splice = p.token == Token::DotDotDot; + if splice { + p.next(); + } let expr = super::expr::parse_expr(p); p.expect(Token::Rbrace); let loc = p.mk_loc_idx_to_prev_end(start_pos_idx); let expr_loc = expr.pexp_loc; let expr_idx = p.arena_mut().push_expr(expr); - let name = p.arena_mut().push_string(HOLE_EXTENSION); + let name = p.arena_mut().push_string(if splice { + SPLICE_HOLE_EXTENSION + } else { + HOLE_EXTENSION + }); let item = StructureItem { pstr_desc: StructureItemDesc::Pstr_eval(Box::new((expr_idx, Attributes::new()))), pstr_loc: expr_loc, From 5fdff8e05896b1aa818c23d8f6d7c4f4b154cb14 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:46:03 +0100 Subject: [PATCH 23/38] macros: splice holes, record entries, optional fields A splice hole `${...items}` in a quote is lowered by the list it is in: the arguments of a call or a constructor and the items of an array or a tuple take an array of code, the fields of a record an array of entries, the cases of a switch an array of a pattern and its code. A hole with no items leaves no comma behind. A splice hole anywhere else is an error at its position. A record value is built from entries: Code.entry, Code.entryOf and Code.spread. Code.record takes them, so its fields can have different types, be optional (`name: ?value`) and follow a spread. The type of an optional field is the type of `value.field`, an option. Code.entryOf, Pat.constructor and Type.record agree with it, and Type.optional and Type.required change a field with its type. Code.withAttr puts an attribute a macro computes on code. Co-authored-by: Jaap Frolich Session: https://jakes-mac-mini.tail23a77e.ts.net:8443/session/os-01a1caab-4faf-7817-951e-2b3f9a5dae19 Signed-off-by: Jaap Frolich --- compiler-rust/src/macros/discover.rs | 13 +- compiler-rust/src/macros/expand.rs | 11 + compiler-rust/src/macros/quote.rs | 216 ++++++++++++++- compiler-rust/tests/macros.rs | 265 ++++++++++++++++++- packages/@rescript/runtime/Macro.res | 144 ++++++++-- packages/@rescript/runtime/lib/es6/Macro.mjs | 194 ++++++++++++-- packages/@rescript/runtime/lib/js/Macro.cjs | 194 ++++++++++++-- playground/examples/decode/Decode.res | 9 +- playground/examples/decode/Main.res | 1 + playground/examples/default/Default.res | 2 +- playground/examples/derive/Enum.res | 27 +- playground/examples/types/Partial.res | 2 +- 12 files changed, 988 insertions(+), 90 deletions(-) diff --git a/compiler-rust/src/macros/discover.rs b/compiler-rust/src/macros/discover.rs index 3e9415bfd2..10aaaa40f8 100644 --- a/compiler-rust/src/macros/discover.rs +++ b/compiler-rust/src/macros/discover.rs @@ -23,7 +23,7 @@ use crate::parser::ast::{ StructureItem as ParsedStructureItem, StructureItemDesc as ParsedStructureItemDesc, }; use crate::parser::longident::Longident; -use crate::parser::module::HOLE_EXTENSION; +use crate::parser::module::{HOLE_EXTENSION, SPLICE_HOLE_EXTENSION}; use crate::types::context::TypeContext; use crate::types::decl::ValueDescription; use crate::types::env::Env; @@ -876,6 +876,11 @@ fn fail(tctx: &mut TypeCheckContext<'_>, loc: LocIdx, message: impl Into const HOLE_OUTSIDE_QUOTE: &str = "A hole `${...}` can only be used inside a quote: %code(...), %type(...) or %pat(...)."; +/// `${...}` or `${...items}`: both belong in a quote. +fn is_hole_name(name: &str) -> bool { + name == HOLE_EXTENSION || name == SPLICE_HOLE_EXTENSION +} + fn discovering(tctx: &TypeCheckContext<'_>) -> bool { matches!(tctx.macro_mode, MacroMode::Discover(_)) } @@ -1173,7 +1178,7 @@ pub(crate) fn expression_extension( expected_ty: TypeExprRef, ) -> Option> { let name = tctx.arena.get_string(extension.0.txt).to_string(); - let is_hole = name == HOLE_EXTENSION; + let is_hole = is_hole_name(&name); if is_hole || quote::is_quote_name(&name) { // Quotes are lowered before a discovery pass; one that is left has // no payload. @@ -1688,7 +1693,7 @@ pub(crate) fn pattern_extension( extension: &Extension, ) -> Option { let name = tctx.arena.get_string(extension.0.txt).to_string(); - if name == HOLE_EXTENSION { + if is_hole_name(&name) { return Some(if matches!(tctx.macro_mode, MacroMode::Off) { required(tctx, loc) } else { @@ -1745,7 +1750,7 @@ pub(crate) fn type_extension( extension: &Extension, ) -> Option { let name = tctx.arena.get_string(extension.0.txt).to_string(); - if name == HOLE_EXTENSION { + if is_hole_name(&name) { return Some(if matches!(tctx.macro_mode, MacroMode::Off) { required(tctx, loc) } else { diff --git a/compiler-rust/src/macros/expand.rs b/compiler-rust/src/macros/expand.rs index c8562b81ff..9bcee66394 100644 --- a/compiler-rust/src/macros/expand.rs +++ b/compiler-rust/src/macros/expand.rs @@ -156,6 +156,17 @@ pub fn expand_source( text = Arc::new(text.apply(quote_edits)); continue; } + if let Some((start, end)) = quote::stray_splice(parser.arena(), &structure) { + return Err(diagnostic( + BUG, + source, + &text, + filename, + (start, end), + false, + quote::SPLICE_OUT_OF_PLACE, + )); + } let opens = top_level_opens(&parser, &structure, &text); let mut frontend_output = String::new(); diff --git a/compiler-rust/src/macros/quote.rs b/compiler-rust/src/macros/quote.rs index a5ccfc3500..bb54acbe57 100644 --- a/compiler-rust/src/macros/quote.rs +++ b/compiler-rust/src/macros/quote.rs @@ -18,21 +18,27 @@ //! is in. The hole expressions stay ordinary code of the macro: they are //! type checked, and a quote nested in a hole is lowered by the next pass. //! +//! A splice hole `${...items}` stands for any number of items of a list: +//! the arguments of a call, the items of an array or a tuple, the fields of +//! a record, the cases of a switch. It is lowered to `Macro.__spliceItems`, +//! `Macro.__spliceEntries` or `Macro.__spliceCases` by the list it is in. +//! //! Hygiene, as far as syntax decides it: a name the quote uses that the //! macro's file defines at its top level is written with the module's name //! (`encode` in `Json.res` becomes `Json.encode`), so it means the same where //! the macro is used. Names the quote binds itself and all other names are //! left as written and resolve at the use. -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use crate::binary_ast::ast_iter::{self, AstIter}; use crate::parse_arena::{CoreTypeIdx, ExprIdx, LocIdx, ParseArena, PatIdx}; use crate::parser::ast::{ - CoreTypeDesc, ExpressionDesc, Extension, PatternDesc, Payload, StructureItem, StructureItemDesc, + ArgLabel, CoreTypeDesc, ExpressionDesc, Extension, PatternDesc, Payload, StructureItem, + StructureItemDesc, }; use crate::parser::longident::Longident; -use crate::parser::module::HOLE_EXTENSION; +use crate::parser::module::{HOLE_EXTENSION, SPLICE_HOLE_EXTENSION}; use super::edit::{Edit, LineTable, Segment, SourceText}; @@ -136,14 +142,32 @@ fn top_level(arena: &ParseArena, structure: &[StructureItem]) -> TopLevel { names } +/// The list a splice hole `${...items}` stands in. +#[derive(Clone, Copy, PartialEq, Eq)] +enum SplicePlace { + /// Arguments of a call or a constructor, items of an array or a tuple. + Items, + /// Fields of a record. + Entries, + /// Cases of a switch. + Cases, +} + #[derive(Clone, Copy, PartialEq, Eq)] enum HoleKind { Code, Type, Pat, Item, + Splice(SplicePlace), + /// A splice hole where no list is written. It is left in the lowered + /// code, where [`stray_splice`] finds it. + SpliceOutOfPlace, } +/// The message for a splice hole that is not in a list of a quote. +pub const SPLICE_OUT_OF_PLACE: &str = "A splice `${...items}` stands for the items of a list in a quote: the arguments of a call, the items of an array or a tuple, the fields of a record, or the cases of a switch."; + struct Hole { /// The hole, `${...}`. outer: (u32, u32), @@ -162,10 +186,35 @@ struct QuoteScan<'a> { bound: HashSet, /// Expressions that are a structure item of the quote on their own. item_exprs: &'a HashSet, + /// The splice holes that are an item of a list, with the list. + splice_places: HashMap, +} + +fn is_splice(arena: &ParseArena, extension: &Extension) -> bool { + arena.get_string(extension.0.txt) == SPLICE_HOLE_EXTENSION +} + +fn is_splice_expr(arena: &ParseArena, idx: ExprIdx) -> bool { + matches!(&arena.get_expr(idx).pexp_desc, ExpressionDesc::Pexp_extension(extension) if is_splice(arena, extension)) } +/// Whether `idx` is an operator, as the function of `a + b` is. +fn is_operator(arena: &ParseArena, idx: ExprIdx) -> bool { + let ExpressionDesc::Pexp_ident(lid) = &arena.get_expr(idx).pexp_desc else { + return false; + }; + match arena.get_longident(lid.txt) { + Longident::Lident(name) => !arena + .get_string(*name) + .starts_with(|ch: char| ch.is_alphabetic() || ch == '_'), + _ => false, + } +} + +/// The range of the expression in a hole or a splice hole. fn hole_inner(arena: &ParseArena, extension: &Extension) -> Option<(u32, u32)> { - if arena.get_string(extension.0.txt) != HOLE_EXTENSION { + let name = arena.get_string(extension.0.txt); + if name != HOLE_EXTENSION && name != SPLICE_HOLE_EXTENSION { return None; } let Payload::PStr(items) = &extension.1 else { @@ -180,13 +229,70 @@ fn hole_inner(arena: &ParseArena, extension: &Extension) -> Option<(u32, u32)> { Some(range(arena, arena.get_expr(eval.0).pexp_loc)) } +impl QuoteScan<'_> { + /// Record the splice holes that are an item of a list of `idx`. + fn find_splice_places(&mut self, arena: &ParseArena, idx: ExprIdx) { + let mut place = |item: ExprIdx, place: SplicePlace| { + if is_splice_expr(arena, item) { + self.splice_places.insert(item, place); + } + }; + match &arena.get_expr(idx).pexp_desc { + // `f(a, b)`, and not `a + b`, which is an application as well. + ExpressionDesc::Pexp_apply(apply) if !is_operator(arena, apply.funct) => { + for (label, arg) in arena.apply_args(apply.args) { + if matches!(label, ArgLabel::Nolabel) { + place(*arg, SplicePlace::Items); + } + } + } + ExpressionDesc::Pexp_tuple(items) | ExpressionDesc::Pexp_array(items) => { + for item in arena.expr_list(*items) { + place(*item, SplicePlace::Items); + } + } + ExpressionDesc::Pexp_construct(_, args) => { + for arg in arena.expr_list(args.txt) { + place(*arg, SplicePlace::Items); + } + } + ExpressionDesc::Pexp_variant(inner) => { + for arg in arena.expr_list(inner.1.txt) { + place(*arg, SplicePlace::Items); + } + } + ExpressionDesc::Pexp_record(inner) => { + for field in arena.expr_field_list(inner.0) { + place(field.expr, SplicePlace::Entries); + } + } + ExpressionDesc::Pexp_match(inner) => { + for case in arena.case_list(inner.1) { + // The parser makes a case without a bar of a splice hole + // only: `| _ => ${...cases}` is not one. + if case.pc_bar.is_none() { + place(case.pc_rhs, SplicePlace::Cases); + } + } + } + _ => {} + } + } +} + impl AstIter for QuoteScan<'_> { fn expr(&mut self, arena: &ParseArena, idx: ExprIdx) { + self.find_splice_places(arena, idx); let expr = arena.get_expr(idx); match &expr.pexp_desc { ExpressionDesc::Pexp_extension(extension) => { if let Some(inner) = hole_inner(arena, extension) { - let kind = if self.item_exprs.contains(&idx) { + let kind = if is_splice(arena, extension) { + match self.splice_places.get(&idx) { + Some(place) => HoleKind::Splice(*place), + None => HoleKind::SpliceOutOfPlace, + } + } else if self.item_exprs.contains(&idx) { HoleKind::Item } else { HoleKind::Code @@ -232,7 +338,11 @@ impl AstIter for QuoteScan<'_> { self.holes.push(Hole { outer: range(arena, pat.ppat_loc), inner, - kind: HoleKind::Pat, + kind: if is_splice(arena, extension) { + HoleKind::SpliceOutOfPlace + } else { + HoleKind::Pat + }, }); } } @@ -255,7 +365,11 @@ impl AstIter for QuoteScan<'_> { self.holes.push(Hole { outer: range(arena, typ.ptyp_loc), inner, - kind: HoleKind::Type, + kind: if is_splice(arena, extension) { + HoleKind::SpliceOutOfPlace + } else { + HoleKind::Type + }, }); return; } @@ -310,6 +424,7 @@ impl QuoteFinder<'_> { } else { &item_exprs }, + splice_places: HashMap::new(), }; scan.payload(arena, &extension.1); @@ -335,6 +450,23 @@ impl QuoteFinder<'_> { } scan.holes.sort_by_key(|hole| hole.outer.0); + // The comma after a splice hole of items is the hole's: the hole + // writes it when it has items, so that none leave no comma behind. + let mut trailing_comma = vec![false; scan.holes.len()]; + for (hole, trailing) in scan.holes.iter_mut().zip(&mut trailing_comma) { + if !matches!( + hole.kind, + HoleKind::Splice(SplicePlace::Items | SplicePlace::Entries) + ) { + continue; + } + let rest = self.text.slice(hole.outer.1, payload.1); + let blank = rest.chars().take_while(|ch| ch.is_whitespace()).count() as u32; + if rest.chars().nth(blank as usize) == Some(',') { + hole.outer.1 += blank + 1; + *trailing = true; + } + } substitutions.sort_by_key(|at| at.0); let in_hole = |at: (u32, u32)| { scan.holes @@ -398,17 +530,33 @@ impl QuoteFinder<'_> { ))]; for (index, hole) in scan.holes.iter().enumerate() { let wrapper = match hole.kind { - HoleKind::Code => "__holeCode", + HoleKind::Code | HoleKind::SpliceOutOfPlace => "__holeCode", HoleKind::Type => "__holeType", HoleKind::Pat => "__holePat", HoleKind::Item => "__holeItem", + HoleKind::Splice(SplicePlace::Items) => "__spliceItems", + HoleKind::Splice(SplicePlace::Entries) => "__spliceEntries", + HoleKind::Splice(SplicePlace::Cases) => "__spliceCases", }; segments.push(Segment::Text(format!( "{}Macro.{wrapper}(", if index == 0 { "" } else { ", " } ))); - segments.push(Segment::Copy(hole.inner.0, hole.inner.1)); - segments.push(Segment::Text(")".into())); + match hole.kind { + // The whole hole, `${...items}`, stays in the code. + HoleKind::SpliceOutOfPlace => { + segments.push(Segment::Copy(hole.outer.0, hole.outer.1)); + } + _ => segments.push(Segment::Copy(hole.inner.0, hole.inner.1)), + } + segments.push(Segment::Text( + match hole.kind { + HoleKind::Splice(SplicePlace::Items | SplicePlace::Entries) => { + format!(", {})", trailing_comma[index]) + } + _ => ")".into(), + }, + )); } segments.push(Segment::Text(format!("], {}))", string_literal(self.file)))); self.edits.push(Edit { @@ -459,3 +607,51 @@ pub fn lowering_edits( ast_iter::walk_structure(&mut finder, arena, structure); finder.edits } + +/// Finds a splice hole that no quote lowered. +struct StraySplice { + found: Option<(u32, u32)>, +} + +impl AstIter for StraySplice { + fn expr(&mut self, arena: &ParseArena, idx: ExprIdx) { + let expr = arena.get_expr(idx); + if let ExpressionDesc::Pexp_extension(extension) = &expr.pexp_desc + && is_splice(arena, extension) + { + self.found.get_or_insert(range(arena, expr.pexp_loc)); + return; + } + ast_iter::walk_expr(self, arena, idx); + } + + fn pat(&mut self, arena: &ParseArena, idx: PatIdx) { + let pat = arena.get_pat(idx); + if let PatternDesc::Ppat_extension(extension) = &pat.ppat_desc + && is_splice(arena, extension) + { + self.found.get_or_insert(range(arena, pat.ppat_loc)); + return; + } + ast_iter::walk_pat(self, arena, idx); + } + + fn typ(&mut self, arena: &ParseArena, idx: CoreTypeIdx) { + let typ = arena.get_core_type(idx); + if let CoreTypeDesc::Ptyp_extension(extension) = &typ.ptyp_desc + && is_splice(arena, extension) + { + self.found.get_or_insert(range(arena, typ.ptyp_loc)); + return; + } + ast_iter::walk_typ(self, arena, idx); + } +} + +/// The first splice hole `${...items}` of `structure` that is not in a list +/// of a quote, once the quotes are lowered: see [`SPLICE_OUT_OF_PLACE`]. +pub fn stray_splice(arena: &ParseArena, structure: &[StructureItem]) -> Option<(u32, u32)> { + let mut finder = StraySplice { found: None }; + ast_iter::walk_structure(&mut finder, arena, structure); + finder.found +} diff --git a/compiler-rust/tests/macros.rs b/compiler-rust/tests/macros.rs index c9e6194aa7..0e080010e9 100644 --- a/compiler-rust/tests/macros.rs +++ b/compiler-rust/tests/macros.rs @@ -224,7 +224,7 @@ open Macro @macro let t = (source: typ): typ => switch Type.info(source) { - | Record({fields}) => Type.record(fields->Array.map(f => {...f, optional: true})) + | Record({fields}) => Type.record(fields->Array.map(Type.optional)) | _ => error("Partial.t needs a record type") } "#, @@ -649,7 +649,7 @@ let rec value = (_: code): code<'a> => | Bool => %code(false) | Array(_) => %code([]) | Option(_) => %code(None) - | Record({fields}) => Code.record(fields->Array.map(f => (f.name, %code(value())))) + | Record({fields}) => Code.record(fields->Array.map(f => Code.entryOf(f, %code(value())))) | _ => error(`Default.value: no default for ${Type.name(expected())}`) } "#, @@ -665,3 +665,264 @@ let rec value = (_: code): code<'a> => assert!(js.contains("retries: 0"), "{js}"); assert!(js.contains("verbose: false"), "{js}"); } + +const BUILD: &str = r#" +open Macro + +// Entries of different types, a spread and an optional entry in one record. +@macro +let labelled = (base: code<'r>, x: code, label: code>): code<'r> => + Code.record([Code.entry("x", x), Code.spread(base), Code.entry("label", label, ~optional=true)]) + +// The fields of the record, with a field of the quote before them. +@generic +let withId = (value: code<'a>, id: code): code<'a> => + switch Type.info(typeOf(value)) { + | Record({fields}) => + let rest = + fields->Array.filter(f => f.name != "id")->Array.map(f => Code.entryOf(f, value->Code.field(f.name))) + %code({id: ${id}, ${...rest}}) + | _ => error("withId needs a record") + } + +// The fields of the record, after a spread. +@generic +let cleared = (value: code<'a>): code<'a> => + switch Type.info(typeOf(value)) { + | Record({fields}) => + let cleared = fields->Array.filter(f => f.optional)->Array.map(f => Code.entryOf(f, %code(None))) + %code({...${value}, ${...cleared}}) + | _ => error("cleared needs a record") + } + +@macro +let call = (f: code<'f>, a: code<'a>, b: code<'b>): code<'c> => + %code(${f}(${...[Code.untyped(a), Code.untyped(b)]})) + +// Arguments of a constructor. +@macro +let twin = (a: code): code<'p> => %code(Pair(${...[a, a]})) + +// Holes with no items at the start, in the middle and at the end of a list. +@macro +let items = (a: code): code<(array, (int, int, int), int)> => { + let none: array> = [] + let two = [a, a] + %code(([${...none}, 0, ${...two}, ${...none}, 9, ${...none}], (1, ${...two}), Math.Int.max(${...none}, ${...two}))) +} + +// Cases of a switch, between cases of the quote. +@generic +let name = (value: code<'a>): code => + switch Type.info(typeOf(value)) { + | Variant({constructors}) => + let cases = constructors->Array.filterMap(c => + c.name == "Unknown" + ? None + : { + let (pattern, _) = Pat.constructor(c) + Some((pattern, Code.string(String.toLowerCase(c.name)))) + } + ) + %code( + switch ${value} { + | Unknown => "?" + ${...cases} + } + ) + | _ => error("name needs a variant") + } + +@macro +let quiet = (value: code<'a>): code<'a> => Code.withAttr(value, "warning", ~payload=Code.string("-27")) +"#; + +#[test] +fn record_entries() { + let mut project = Project::new(); + compile_ok(&mut project, "Build.res", BUILD); + let js = compile_ok( + &mut project, + "Points.res", + r#" +type point = {x: int, y: int, label?: string} +let origin: point = {x: 0, y: 0} +let named = %Build.labelled(origin, 3, Some("three")) +"#, + ); + let expanded = project.expanded.clone().unwrap(); + // The spread comes first, as a record has it. + assert!( + expanded.contains(r#"{...origin, x: 3, label: ?(Some("three"))}"#), + "{expanded}" + ); + assert!(js.contains("newrecord.label = \"three\""), "{js}"); +} + +#[test] +fn splice_holes() { + let mut project = Project::new(); + compile_ok(&mut project, "Build.res", BUILD); + let js = compile_ok( + &mut project, + "Splices.res", + r#" +type user = {id: int, name: string, age?: int} +let ada: user = {id: 1, name: "Ada", age: 36} +let renumbered = Build.withId(ada, 2) +let ageless = Build.cleared(ada) + +let pair = %Build.call((a, b) => (a, b), 1, "one") +let (list, triple, most) = %Build.items(5) + +type pair = Pair(int, int) +let twin = %Build.twin(4) + +type state = Unknown | Idle | Running +let label = (state: state) => Build.name(state) +"#, + ); + let expanded = project.expanded.clone().unwrap(); + // An optional field is copied as an option, with `?`. + assert!(expanded.contains("{id: (b$), name: a$.name, age: ?a$.age}"), "{expanded}"); + assert!(expanded.contains("{...(a$), age: ?None}"), "{expanded}"); + assert!(expanded.contains(r#"((a, b) => (a, b))(1, "one")"#), "{expanded}"); + // No items: no comma is left behind. + assert!(expanded.contains("[ 0, 5, 5, 9, ]"), "{expanded}"); + assert!(expanded.contains("(1, 5, 5)"), "{expanded}"); + assert!(expanded.contains("Math.Int.max( 5, 5)"), "{expanded}"); + assert!(expanded.contains("Pair(4, 4)"), "{expanded}"); + assert!(expanded.contains("| Idle => \"idle\"\n| Running => \"running\""), "{expanded}"); + assert_eq!(project.warnings, "", "{}", project.warnings); + assert!(js.contains("\"running\""), "{js}"); +} + +#[test] +fn splice_hole_out_of_place() { + let mut project = Project::new(); + let error = compile_err( + &mut project, + "Wrong.res", + "open Macro\n@macro\nlet sum = (a: code): code => %code(1 + ${...[a]})\n", + ); + assert!(error.contains("A splice `${...items}` stands for the items of a list"), "{error}"); + assert!(error.contains("Wrong.res:3:"), "{error}"); + + let error = compile_err(&mut project, "Outside.res", "let xs = [1]\nlet ys = [0, ${...xs}]\n"); + assert!(error.contains("A splice `${...items}` stands for the items of a list"), "{error}"); +} + +#[test] +fn optional_fields() { + let mut project = Project::new(); + compile_ok(&mut project, "Json.res", JSON); + compile_ok( + &mut project, + "Fields.res", + r#" +open Macro + +@generic +let describe = (value: code<'a>): code => + switch Type.info(typeOf(value)) { + | Record({fields}) => + Code.string( + fields->Array.map(f => f.name ++ (f.optional ? "?" : "") ++ ": " ++ Type.name(f.typ))->Array.join(", "), + ) + | _ => error("describe needs a record") + } + +@macro +let same = (source: typ): typ => + switch Type.info(source) { + | Record({fields}) => Type.record(fields) + | _ => error("same needs a record") + } + +@macro +let partial = (source: typ): typ => + switch Type.info(source) { + | Record({fields}) => Type.record(fields->Array.map(Type.optional)) + | _ => error("partial needs a record") + } + +@macro +let required = (source: typ): typ => + switch Type.info(source) { + | Record({fields}) => Type.record(fields->Array.map(Type.required)) + | _ => error("required needs a record") + } + +@macro +let flagged = (source: typ): typ => + switch Type.info(source) { + | Record({fields}) => Type.record(fields->Array.map(f => {...f, optional: true})) + | _ => error("flagged needs a record") + } + +@generic +let default = (_: code): code<'a> => + switch Type.info(expected()) { + | Int => %code(0) + | String => %code("") + | Option(_) => %code(None) + | Record({fields}) => Code.record(fields->Array.map(f => Code.entryOf(f, %code((default(): ${f.typ}))))) + | _ => error("no default") + } +"#, + ); + let js = compile_ok( + &mut project, + "User.res", + r#" +type user = {name: string, age?: int} +let ada: user = {name: "Ada", age: 36} +let fields = Fields.describe(ada) + +type copy = %Fields.same(user) +let copy: copy = {name: "Ada", age: 36} + +type patch = %Fields.partial(user) +let patch: patch = {age: 37} + +type full = %Fields.required(user) +let full: full = {name: "Ada", age: 36} + +let empty: user = Fields.default() + +type shape = Circle({radius: float, label?: string}) | Dot +let encode = (shape: shape) => Json.encode(shape) +"#, + ); + let expanded = project.expanded.clone().unwrap(); + // The type of an optional field is the type of `value.field`. + assert!(expanded.contains(r#""name: string, age?: option""#), "{expanded}"); + assert!(expanded.contains("type copy = {name: string, age?: int}"), "{expanded}"); + assert!(expanded.contains("type patch = {name?: string, age?: int}"), "{expanded}"); + assert!(expanded.contains("type full = {name: string, age: int}"), "{expanded}"); + assert!(expanded.contains("age: ?((default$option_int(): (option)))"), "{expanded}"); + // The pattern of an inline record binds an optional field as an option: + // the switch has a case for a shape without a label. + assert!(expanded.contains("Circle({radius: radius$0, label: ?label$1})"), "{expanded}"); + assert_eq!(project.warnings, "", "{}", project.warnings); + assert!(!js.contains("Match_failure"), "{js}"); + + let error = compile_err( + &mut project, + "Flagged.res", + "type user = {name: string}\ntype t = %Fields.flagged(user)\n", + ); + assert!(error.contains("Type.optional makes a field optional"), "{error}"); +} + +#[test] +fn attribute_on_generated_code() { + let mut project = Project::new(); + compile_ok(&mut project, "Build.res", BUILD); + compile_ok(&mut project, "Loud.res", "let size = unused => 2\n"); + assert!(project.warnings.contains("unused variable unused"), "{}", project.warnings); + compile_ok(&mut project, "Quiet.res", "let size = %Build.quiet(unused => 2)\n"); + let expanded = project.expanded.clone().unwrap(); + assert!(expanded.contains(r#"@warning("-27") (unused => 2)"#), "{expanded}"); + assert_eq!(project.warnings, "", "{}", project.warnings); +} diff --git a/packages/@rescript/runtime/Macro.res b/packages/@rescript/runtime/Macro.res index 1e05fb6e0d..d0ca3c5c46 100644 --- a/packages/@rescript/runtime/Macro.res +++ b/packages/@rescript/runtime/Macro.res @@ -28,9 +28,10 @@ type decls = code /* The representation the compiler and the engine share: the source text, and for a type the compiler's handle of it. `m` says which parts of the text are text from elsewhere, an argument of the macro or a quote: the - compiler reports an error in generated code with it. */ + compiler reports an error in generated code with it. `o`: the type + inside, for an option type a macro built with `Type.option`. */ type span -type rec node = {c: string, m?: array, id?: int, t?: node, raw?: bool} +type rec node = {c: string, m?: array, id?: int, t?: node, raw?: bool, o?: node} external toNode: 'a => node = "%identity" external ofNode: node => 'a = "%identity" @@ -146,6 +147,39 @@ let __quoteDecls = (pieces, holes, file): decls => ofNode(quote(pieces, holes, f let __quoteType = (pieces, holes, file): typ => ofNode(quote(pieces, holes, file)) let __quotePat = (pieces, holes, file): pat => ofNode(quote(pieces, holes, file)) +/* Splice holes. `${...items}` in a list of a quote stands for any number + of its items; the compiler picks the function by the list. `trailing`: + a comma follows the hole. That comma is the hole's own, so that a hole + with no items leaves no comma behind. */ +let splice = (items: array, trailing: bool): hole => + ofNode({...cat([join(items, ", "), text(trailing && items->Array.length > 0 ? "," : "")]), raw: true}) + +/** A field of a record value: see `Code.entry`. */ +type recordEntry + +/* The spread of a record comes before its fields. */ +let entryNodes = (entries: array): array => { + let nodes = entries->Array.map(toNode) + let isSpread = (node: node) => node.c->String.startsWith("...") + let spreads = nodes->Array.filter(isSpread) + if spreads->Array.length > 1 { + host->fail( + "A record can have one spread, and these fields have more: " ++ spreads->Array.map(node => node.c)->Array.join(", "), + None, + ) + } else { + spreads->Array.concat(nodes->Array.filter(node => !isSpread(node))) + } +} + +let caseNode = ((pattern, body): (pat, code<'a>)): node => + cat([text("| "), toNode(pattern), text(" => "), toNode(body)]) + +let __spliceItems = (items: array>, trailing: bool): hole => splice(items->Array.map(toNode), trailing) +let __spliceEntries = (entries: array, trailing: bool): hole => splice(entryNodes(entries), trailing) +let __spliceCases = (cases: array<(pat, code<'a>)>): hole => + ofNode({...join(cases->Array.map(caseNode), "\n"), raw: true}) + let isSimple: string => bool = %raw(`function (text) { return /^[A-Za-z_][A-Za-z0-9_$.]*$/.test(text) }`) @@ -179,7 +213,13 @@ module Type = { name: string, /** The name at run time: the `@as` name when there is one. */ jsName: string, + /** + The type of `value.name`. For an optional field `age?: int` that is + `option`: reading the field, `Code.entryOf` and `Pat.constructor` + all use this type. + */ typ: typ, + /** `age?: int`. Change it with `Type.optional` and `Type.required`. */ optional: bool, mutable_: bool, attrs: array, @@ -252,13 +292,53 @@ module Type = { ) ->Array.join("") + /** `option` */ + let option = (t: typ): typ => ofNode({c: "option<" ++ source(t) ++ ">", o: toNode(t)}) + + /* The `t` of `option`. */ + let optionOf = (t: typ): option => { + let node = toNode(t) + switch (node.o, node.id) { + | (Some(inner), _) => Some(ofNode(inner)) + | (None, Some(_)) => + switch info(t) { + | Option(inner) => Some(inner) + | _ => None + } + | (None, None) => None + } + } + + /* The type an optional field is declared with: `int` for `age?: int`, + where `typ` is `option`. */ + let declared = (field: field): typ => + switch optionOf(field.typ) { + | Some(inner) => inner + | None => + error( + "The optional field `" ++ + field.name ++ + "` has the type `" ++ + source(field.typ) ++ "`, and the type of an optional field is an option. Type.optional makes a field optional.", + ) + } + + /** + The field as an optional one: `age?: int`. Its `typ` becomes + `option`, the type of `value.age`. An optional field stays as it is. + */ + let optional = (field: field): field => + field.optional ? field : {...field, optional: true, typ: option(field.typ)} + + /** The field as a required one: `age: int` for `age?: int`. */ + let required = (field: field): field => + field.optional ? {...field, optional: false, typ: declared(field)} : field + let fieldText = (field: field): string => attrText(field.attrs) ++ (field.jsName != field.name ? "@as(" ++ JSON.stringify(JSON.Encode.string(field.jsName)) ++ ") " : "") ++ (field.mutable_ ? "mutable " : "") ++ - field.name ++ - (field.optional ? "?: " : ": ") ++ - source(field.typ) + field.name ++ (field.optional ? "?: " ++ source(declared(field)) : ": " ++ source(field.typ)) /** A record type with these fields. */ let record = (fields: array): typ => make("{" ++ fields->Array.map(fieldText)->Array.join(", ") ++ "}") @@ -333,30 +413,49 @@ module Code = { let tuple = (items: array>): code<'b> => build([text("("), join(items->Array.map(toNode), ", "), text(")")]) - /** `{name: value, ...}` */ - let record = (fields: array<(string, code<'a>)>): code<'b> => + /** The same code without its type, to put code of different types in one array. */ + external untyped: code<'a> => code = "%identity" + + /** `@name value`, or `@name(payload) value`. */ + let withAttr = (value: code<'a>, name: string, ~payload: option>=?): code<'a> => build([ - text("{"), - join(fields->Array.map(((name, value)) => cat([text(name ++ ": "), toNode(value)])), ", "), - text("}"), + text("@" ++ name), + switch payload { + | Some(payload) => cat([text("("), toNode(payload), text(") ")]) + | None => text(" ") + }, + atomNode(toNode(value)), ]) + /** A field of a record value: `name: value`, `name: ?value` or `...value`. */ + type entry = recordEntry + + /** + `name: value`. With `~optional=true`, `name: ?value`: the value is an + option, and `None` leaves the field out. + */ + let entry = (name: string, value: code<'a>, ~optional=false): entry => + build([text(name ++ (optional ? ": ?" : ": ")), optional ? atomNode(toNode(value)) : toNode(value)]) + + /** + The entry of a field of a record type, for a value of the type `field.typ`: + `name: ?value` when the field is optional, `name: value` otherwise. + */ + let entryOf = (field: Type.field, value: code<'a>): entry => entry(field.name, value, ~optional=field.optional) + + /** `...value`: the fields of another record of the same type. */ + let spread = (value: code<'a>): entry => build([text("..."), atomNode(toNode(value))]) + + /** `{name: value, ...}` */ + let record = (entries: array): code<'a> => build([text("{"), join(entryNodes(entries), ", "), text("}")]) + /** `f(a, b)` */ let call = (f: code<'a>, args: array>): code<'c> => build([atomNode(toNode(f)), text("("), join(args->Array.map(toNode), ", "), text(")")]) /** `switch value { | pattern => body ... }` */ let switch_ = (value: code<'a>, arms: array<(pat, code<'b>)>): code<'b> => - build([ - text("switch "), - atomNode(toNode(value)), - text(" {\n"), - join( - arms->Array.map(((pattern, body)) => cat([text("| "), toNode(pattern), text(" => "), toNode(body)])), - "\n", - ), - text("\n}"), - ]) + build([text("switch "), atomNode(toNode(value)), text(" {\n"), join(arms->Array.map(caseNode), "\n"), text("\n}")]) /** A parameter of `fn`. */ type param = string @@ -400,7 +499,10 @@ module Pat = { make( c.name ++ "({" ++ - c.fields->Array.mapWithIndex((f, i) => f.name ++ ": " ++ names->Array.getUnsafe(i))->Array.join(", ") ++ "})", + c.fields + // `?`: the name is bound to the option of an optional field, absent or not. + ->Array.mapWithIndex((f, i) => f.name ++ (f.optional ? ": ?" : ": ") ++ names->Array.getUnsafe(i)) + ->Array.join(", ") ++ "})", ), c.fields->Array.mapWithIndex((f, i) => typed(names->Array.getUnsafe(i), f.typ)), ) diff --git a/packages/@rescript/runtime/lib/es6/Macro.mjs b/packages/@rescript/runtime/lib/es6/Macro.mjs index e689b651aa..9329e3bcea 100644 --- a/packages/@rescript/runtime/lib/es6/Macro.mjs +++ b/packages/@rescript/runtime/lib/es6/Macro.mjs @@ -133,6 +133,55 @@ function __quotePat(pieces, holes, file) { return quote(pieces, holes, file); } +function splice(items, trailing) { + return { + ...cat([ + join(items, ", "), + text(trailing && items.length !== 0 ? "," : "") + ]), + raw: true + }; +} + +function entryNodes(entries) { + let nodes = entries.map(prim => prim); + let isSpread = node => node.c.startsWith("..."); + let spreads = nodes.filter(isSpread); + if (spreads.length > 1) { + return __rescript_macro.fail("A record can have one spread, and these fields have more: " + spreads.map(node => node.c).join(", "), undefined); + } else { + return spreads.concat(nodes.filter(node => !node.c.startsWith("..."))); + } +} + +function caseNode(param) { + return cat([ + { + c: "| " + }, + param[0], + { + c: " => " + }, + param[1] + ]); +} + +function __spliceItems(items, trailing) { + return splice(items.map(prim => prim), trailing); +} + +function __spliceEntries(entries, trailing) { + return splice(entryNodes(entries), trailing); +} + +function __spliceCases(cases) { + return { + ...join(cases.map(caseNode), "\n"), + raw: true + }; +} + let isSimple = (function (text) { return /^[A-Za-z_][A-Za-z0-9_$.]*$/.test(text) }); @@ -214,14 +263,77 @@ function attrText(attrs) { }).join(""); } +function option(t) { + return { + c: "option<" + t.c + ">", + o: t + }; +} + +function optionOf(t) { + let match = t.o; + let match$1 = t.id; + if (match !== undefined) { + return Primitive_option.some(match); + } + if (match$1 === undefined) { + return; + } + let inner = info(t); + if (typeof inner !== "object" || inner.TAG !== "Option") { + return; + } else { + return Primitive_option.some(inner._0); + } +} + +function declared(field) { + let inner = optionOf(field.typ); + if (inner !== undefined) { + return Primitive_option.valFromOption(inner); + } else { + return __rescript_macro.fail("The optional field `" + field.name + "` has the type `" + field.typ.c + "`, and the type of an optional field is an option. Type.optional makes a field optional.", undefined); + } +} + +function optional(field) { + if (field.optional) { + return field; + } else { + return { + name: field.name, + jsName: field.jsName, + typ: option(field.typ), + optional: true, + mutable_: field.mutable_, + attrs: field.attrs + }; + } +} + +function required(field) { + if (field.optional) { + return { + name: field.name, + jsName: field.jsName, + typ: declared(field), + optional: false, + mutable_: field.mutable_, + attrs: field.attrs + }; + } else { + return field; + } +} + function fieldText(field) { return attrText(field.attrs) + ( field.jsName !== field.name ? "@as(" + JSON.stringify(field.jsName) + ") " : "" ) + ( field.mutable_ ? "mutable " : "" ) + field.name + ( - field.optional ? "?: " : ": " - ) + field.typ.c; + field.optional ? "?: " + declared(field).c : ": " + field.typ.c + ); } function record(fields) { @@ -266,6 +378,11 @@ let Type = { name: name, companion: companion, attrText: attrText, + option: option, + optionOf: optionOf, + declared: declared, + optional: optional, + required: required, fieldText: fieldText, record: record, variant: variant, @@ -333,15 +450,53 @@ function tuple(items) { ]); } -function record$1(fields) { +function withAttr(value, name, payload) { + return cat([ + text("@" + name), + payload !== undefined ? cat([ + { + c: "(" + }, + Primitive_option.valFromOption(payload), + { + c: ") " + } + ]) : ({ + c: " " + }), + atomNode(value) + ]); +} + +function entry(name, value, optionalOpt) { + let optional = optionalOpt !== undefined ? optionalOpt : false; + return cat([ + text(name + ( + optional ? ": ?" : ": " + )), + optional ? atomNode(value) : value + ]); +} + +function entryOf(field, value) { + return entry(field.name, value, field.optional); +} + +function spread(value) { + return cat([ + { + c: "..." + }, + atomNode(value) + ]); +} + +function record$1(entries) { return cat([ { c: "{" }, - join(fields.map(param => cat([ - text(param[0] + ": "), - param[1] - ])), ", "), + join(entryNodes(entries), ", "), { c: "}" } @@ -370,16 +525,7 @@ function switch_(value, arms) { { c: " {\n" }, - join(arms.map(param => cat([ - { - c: "| " - }, - param[0], - { - c: " => " - }, - param[1] - ])), "\n"), + join(arms.map(caseNode), "\n"), { c: "\n}" } @@ -417,6 +563,10 @@ let Code = { field: field$1, array: array, tuple: tuple, + withAttr: withAttr, + entry: entry, + entryOf: entryOf, + spread: spread, record: record$1, call: call, switch_: switch_, @@ -448,7 +598,9 @@ function constructor$1(c) { if (c.fields.length !== 0) { let names = c.fields.map((f, i) => f.name + "$" + i.toString()); return [ - make(c.name + "({" + c.fields.map((f, i) => f.name + ": " + names[i]).join(", ") + "})"), + make(c.name + "({" + c.fields.map((f, i) => f.name + ( + f.optional ? ": ?" : ": " + ) + names[i]).join(", ") + "})"), c.fields.map((f, i) => typed(names[i], f.typ)) ]; } @@ -494,6 +646,12 @@ export { __quoteDecls, __quoteType, __quotePat, + splice, + entryNodes, + caseNode, + __spliceItems, + __spliceEntries, + __spliceCases, isSimple, atom, atomNode, diff --git a/packages/@rescript/runtime/lib/js/Macro.cjs b/packages/@rescript/runtime/lib/js/Macro.cjs index 2bcca5c0d7..74c224e2f5 100644 --- a/packages/@rescript/runtime/lib/js/Macro.cjs +++ b/packages/@rescript/runtime/lib/js/Macro.cjs @@ -133,6 +133,55 @@ function __quotePat(pieces, holes, file) { return quote(pieces, holes, file); } +function splice(items, trailing) { + return { + ...cat([ + join(items, ", "), + text(trailing && items.length !== 0 ? "," : "") + ]), + raw: true + }; +} + +function entryNodes(entries) { + let nodes = entries.map(prim => prim); + let isSpread = node => node.c.startsWith("..."); + let spreads = nodes.filter(isSpread); + if (spreads.length > 1) { + return __rescript_macro.fail("A record can have one spread, and these fields have more: " + spreads.map(node => node.c).join(", "), undefined); + } else { + return spreads.concat(nodes.filter(node => !node.c.startsWith("..."))); + } +} + +function caseNode(param) { + return cat([ + { + c: "| " + }, + param[0], + { + c: " => " + }, + param[1] + ]); +} + +function __spliceItems(items, trailing) { + return splice(items.map(prim => prim), trailing); +} + +function __spliceEntries(entries, trailing) { + return splice(entryNodes(entries), trailing); +} + +function __spliceCases(cases) { + return { + ...join(cases.map(caseNode), "\n"), + raw: true + }; +} + let isSimple = (function (text) { return /^[A-Za-z_][A-Za-z0-9_$.]*$/.test(text) }); @@ -214,14 +263,77 @@ function attrText(attrs) { }).join(""); } +function option(t) { + return { + c: "option<" + t.c + ">", + o: t + }; +} + +function optionOf(t) { + let match = t.o; + let match$1 = t.id; + if (match !== undefined) { + return Primitive_option.some(match); + } + if (match$1 === undefined) { + return; + } + let inner = info(t); + if (typeof inner !== "object" || inner.TAG !== "Option") { + return; + } else { + return Primitive_option.some(inner._0); + } +} + +function declared(field) { + let inner = optionOf(field.typ); + if (inner !== undefined) { + return Primitive_option.valFromOption(inner); + } else { + return __rescript_macro.fail("The optional field `" + field.name + "` has the type `" + field.typ.c + "`, and the type of an optional field is an option. Type.optional makes a field optional.", undefined); + } +} + +function optional(field) { + if (field.optional) { + return field; + } else { + return { + name: field.name, + jsName: field.jsName, + typ: option(field.typ), + optional: true, + mutable_: field.mutable_, + attrs: field.attrs + }; + } +} + +function required(field) { + if (field.optional) { + return { + name: field.name, + jsName: field.jsName, + typ: declared(field), + optional: false, + mutable_: field.mutable_, + attrs: field.attrs + }; + } else { + return field; + } +} + function fieldText(field) { return attrText(field.attrs) + ( field.jsName !== field.name ? "@as(" + JSON.stringify(field.jsName) + ") " : "" ) + ( field.mutable_ ? "mutable " : "" ) + field.name + ( - field.optional ? "?: " : ": " - ) + field.typ.c; + field.optional ? "?: " + declared(field).c : ": " + field.typ.c + ); } function record(fields) { @@ -266,6 +378,11 @@ let Type = { name: name, companion: companion, attrText: attrText, + option: option, + optionOf: optionOf, + declared: declared, + optional: optional, + required: required, fieldText: fieldText, record: record, variant: variant, @@ -333,15 +450,53 @@ function tuple(items) { ]); } -function record$1(fields) { +function withAttr(value, name, payload) { + return cat([ + text("@" + name), + payload !== undefined ? cat([ + { + c: "(" + }, + Primitive_option.valFromOption(payload), + { + c: ") " + } + ]) : ({ + c: " " + }), + atomNode(value) + ]); +} + +function entry(name, value, optionalOpt) { + let optional = optionalOpt !== undefined ? optionalOpt : false; + return cat([ + text(name + ( + optional ? ": ?" : ": " + )), + optional ? atomNode(value) : value + ]); +} + +function entryOf(field, value) { + return entry(field.name, value, field.optional); +} + +function spread(value) { + return cat([ + { + c: "..." + }, + atomNode(value) + ]); +} + +function record$1(entries) { return cat([ { c: "{" }, - join(fields.map(param => cat([ - text(param[0] + ": "), - param[1] - ])), ", "), + join(entryNodes(entries), ", "), { c: "}" } @@ -370,16 +525,7 @@ function switch_(value, arms) { { c: " {\n" }, - join(arms.map(param => cat([ - { - c: "| " - }, - param[0], - { - c: " => " - }, - param[1] - ])), "\n"), + join(arms.map(caseNode), "\n"), { c: "\n}" } @@ -417,6 +563,10 @@ let Code = { field: field$1, array: array, tuple: tuple, + withAttr: withAttr, + entry: entry, + entryOf: entryOf, + spread: spread, record: record$1, call: call, switch_: switch_, @@ -448,7 +598,9 @@ function constructor$1(c) { if (c.fields.length !== 0) { let names = c.fields.map((f, i) => f.name + "$" + i.toString()); return [ - make(c.name + "({" + c.fields.map((f, i) => f.name + ": " + names[i]).join(", ") + "})"), + make(c.name + "({" + c.fields.map((f, i) => f.name + ( + f.optional ? ": ?" : ": " + ) + names[i]).join(", ") + "})"), c.fields.map((f, i) => typed(names[i], f.typ)) ]; } @@ -493,6 +645,12 @@ exports.__quoteCode = __quoteCode; exports.__quoteDecls = __quoteDecls; exports.__quoteType = __quoteType; exports.__quotePat = __quotePat; +exports.splice = splice; +exports.entryNodes = entryNodes; +exports.caseNode = caseNode; +exports.__spliceItems = __spliceItems; +exports.__spliceEntries = __spliceEntries; +exports.__spliceCases = __spliceCases; exports.isSimple = isSimple; exports.atom = atom; exports.atomNode = atomNode; diff --git a/playground/examples/decode/Decode.res b/playground/examples/decode/Decode.res index 8176d24b7c..2040df9ad5 100644 --- a/playground/examples/decode/Decode.res +++ b/playground/examples/decode/Decode.res @@ -51,11 +51,12 @@ let fromJson = (json: code): code<'a> => } ) | Record({fields}) => + // `entryOf` writes `name: value`, and `name: ?value` for an optional + // field: its type is an option, and a key that is missing leaves it out. Code.record( - fields->Array.map(f => ( - f.name, - %code((fromJson(field(${json}, ${Code.string(f.jsName)})): ${f.typ})), - )), + fields->Array.map(f => + Code.entryOf(f, %code((fromJson(field(${json}, ${Code.string(f.jsName)})): ${f.typ}))) + ), ) | _ => error(`Decode.fromJson cannot decode to ${Type.name(expected())}`) } diff --git a/playground/examples/decode/Main.res b/playground/examples/decode/Main.res index fdc43a5225..1c4d405bdf 100644 --- a/playground/examples/decode/Main.res +++ b/playground/examples/decode/Main.res @@ -4,6 +4,7 @@ type user = { name: string, age: int, email: option, + nickname?: string, addresses: array
    , } diff --git a/playground/examples/default/Default.res b/playground/examples/default/Default.res index ad8e831da6..a08e4c955b 100644 --- a/playground/examples/default/Default.res +++ b/playground/examples/default/Default.res @@ -10,7 +10,7 @@ let value = (_: code): code<'a> => | Bool => %code(false) | Array(_) => %code([]) | Option(_) => %code(None) - | Record({fields}) => Code.record(fields->Array.map(f => (f.name, %code(value())))) + | Record({fields}) => Code.record(fields->Array.map(f => Code.entryOf(f, %code(value())))) | Variant({constructors}) => switch constructors->Array.find(c => c.args->Array.length == 0 && c.fields->Array.length == 0) { | Some(c) => Code.ident(c.name) diff --git a/playground/examples/derive/Enum.res b/playground/examples/derive/Enum.res index dd1ca08aeb..b7998f39b4 100644 --- a/playground/examples/derive/Enum.res +++ b/playground/examples/derive/Enum.res @@ -14,20 +14,25 @@ let derive = (t: Type.decl): decls => let label = (c: Type.constructor) => c.attrs->Attr.string("Enum.label")->Option.getOr(c.jsName) let value = (c: Type.constructor): code => Code.ident(c.name) - let toString = Code.switch_( - %code(value), - constructors->Array.map(c => { - let (pattern, _) = Pat.constructor(c) - (pattern, Code.string(label(c))) - }), - ) + // One case per constructor: a pattern and the code of the case. + let names = constructors->Array.map(c => { + let (pattern, _) = Pat.constructor(c) + (pattern, Code.string(label(c))) + }) let known = constructors->Array.map(c => (Pat.string(label(c)), %code(Some(${value(c)})))) - let fromString = Code.switch_(%code(text), [...known, (Pat.any, %code(None))]) + // `${...cases}` puts the cases in a switch of the quote. %code( - let ${Pat.var(t.name ++ "ToString")} = (value: ${t.typ}): string => ${toString} - let ${Pat.var(t.name ++ "FromString")} = (text: string): option<${t.typ}> => ${fromString} - let ${Pat.var(t.name ++ "Values")}: array<${t.typ}> = ${Code.array(constructors->Array.map(value))} + let ${Pat.var(t.name ++ "ToString")} = (value: ${t.typ}): string => + switch value { + ${...names} + } + let ${Pat.var(t.name ++ "FromString")} = (text: string): option<${t.typ}> => + switch text { + ${...known} + | _ => None + } + let ${Pat.var(t.name ++ "Values")}: array<${t.typ}> = [${...constructors->Array.map(value)}] ) | _ => error("Enum.derive needs a variant type") } diff --git a/playground/examples/types/Partial.res b/playground/examples/types/Partial.res index a0722961a5..946bc4393c 100644 --- a/playground/examples/types/Partial.res +++ b/playground/examples/types/Partial.res @@ -4,6 +4,6 @@ open Macro @macro let t = (source: typ): typ => switch Type.info(source) { - | Record({fields}) => Type.record(fields->Array.map(f => {...f, optional: true})) + | Record({fields}) => Type.record(fields->Array.map(Type.optional)) | _ => error(`Partial.t needs a record type, and ${Type.name(source)} is not one`) } From 43a753e2e0e140105b3b4f350c679fbbc0eb4fe2 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:46:03 +0100 Subject: [PATCH 24/38] playground: examples for records, splice holes, optional fields, attributes Co-authored-by: Jaap Frolich Session: https://jakes-mac-mini.tail23a77e.ts.net:8443/session/os-01a1caab-4faf-7817-951e-2b3f9a5dae19 Signed-off-by: Jaap Frolich --- playground/examples/attrs/Main.res | 31 +++++++++++++++++ playground/examples/attrs/Mock.res | 35 +++++++++++++++++++ playground/examples/index.json | 36 +++++++++++++++++++ playground/examples/optional/Main.res | 16 +++++++++ playground/examples/optional/Patch.res | 37 ++++++++++++++++++++ playground/examples/record/Convert.res | 31 +++++++++++++++++ playground/examples/record/Main.res | 26 ++++++++++++++ playground/examples/splice/Main.res | 19 ++++++++++ playground/examples/splice/Splice.res | 48 ++++++++++++++++++++++++++ 9 files changed, 279 insertions(+) create mode 100644 playground/examples/attrs/Main.res create mode 100644 playground/examples/attrs/Mock.res create mode 100644 playground/examples/optional/Main.res create mode 100644 playground/examples/optional/Patch.res create mode 100644 playground/examples/record/Convert.res create mode 100644 playground/examples/record/Main.res create mode 100644 playground/examples/splice/Main.res create mode 100644 playground/examples/splice/Splice.res diff --git a/playground/examples/attrs/Main.res b/playground/examples/attrs/Main.res new file mode 100644 index 0000000000..d234663912 --- /dev/null +++ b/playground/examples/attrs/Main.res @@ -0,0 +1,31 @@ +type user = {id: int, name: string} + +type api = { + load: int => user, + save: (user, bool) => unit, + count: unit => int, +} + +// Every field is `@warning("-27") (arg1: ...) => throw(...)`. +let mock: api = Mock.make() + +// A test replaces what it uses. The rest fails when it is reached. +let api = {...mock, count: () => 3} +Console.log(api.count()) +Console.log( + try api.load(1).name catch { + | Failure(message) => message + }, +) + +// The attribute on a whole record, with the number as an argument: +// `user` and `notify` are not used, and nothing is reported. +let silent: api = %Mock.allow( + 27, + { + load: id => {id, name: "nobody"}, + save: (user, notify) => (), + count: () => 0, + }, +) +Console.log(silent.load(7)) diff --git a/playground/examples/attrs/Mock.res b/playground/examples/attrs/Mock.res new file mode 100644 index 0000000000..b31de5e38e --- /dev/null +++ b/playground/examples/attrs/Mock.res @@ -0,0 +1,35 @@ +open Macro + +// Mock.make() is a record of functions that fail when they are called: +// what a test starts from, before it replaces the functions it uses. +// +// The parameters of a generated function have names, to read well in the +// expansion, and are not used: the compiler would warn about each one. +// The macro puts @warning("-27") on the function, so whoever uses the +// macro gets no warning for code they did not write. +// +// An attribute belongs to an expression. A field of a record has no place +// for one, so it goes on the field's value. +@generic +let make = (_: code): code<'a> => + switch Type.info(expected()) { + | Record({fields}) => + Code.record( + fields->Array.map(f => + switch Type.info(f.typ) { + | Function({params}) => + let named = params->Array.mapWithIndex((typ, i) => Code.param("arg" ++ Int.toString(i + 1), typ)) + let stub = Code.fn(named, %code(throw(Failure(${Code.string(f.name ++ " is not mocked")})))) + Code.entryOf(f, %code(@warning("-27") ${stub})) + | _ => error(`Mock.make: the field ${f.name} is not a function`) + } + ), + ) + | _ => error("Mock.make fills a record of functions") + } + +// An attribute a quote cannot write, because the macro computes it: +// Code.withAttr(value, name, ~payload) is `@name(payload) value`. +@macro +let allow = (warning: int, value: code<'a>): code<'a> => + Code.withAttr(value, "warning", ~payload=Code.string("-" ++ Int.toString(warning))) diff --git a/playground/examples/index.json b/playground/examples/index.json index cff6c61c70..b890122cf8 100644 --- a/playground/examples/index.json +++ b/playground/examples/index.json @@ -109,6 +109,42 @@ "Main.res" ] }, + { + "id": "record", + "title": "A record built from data", + "summary": "Convert.to(user) fills a record of the expected type from the fields of another one, an entry per field.", + "files": [ + "Convert.res", + "Main.res" + ] + }, + { + "id": "splice", + "title": "Splice holes: lists in a quote", + "summary": "${...items} stands for any number of record fields, call arguments or switch cases in a quote.", + "files": [ + "Splice.res", + "Main.res" + ] + }, + { + "id": "optional", + "title": "Optional fields", + "summary": "%Patch.t(user) makes every field optional and Patch.apply merges a patch: optional fields need no special case.", + "files": [ + "Patch.res", + "Main.res" + ] + }, + { + "id": "attrs", + "title": "Attributes on generated code", + "summary": "An attribute on the value of a field, and on a whole record: here @warning(\"-27\") for functions the macro writes.", + "files": [ + "Mock.res", + "Main.res" + ] + }, { "id": "pattern", "title": "Pattern macros and checked literals", diff --git a/playground/examples/optional/Main.res b/playground/examples/optional/Main.res new file mode 100644 index 0000000000..3ae2bcca49 --- /dev/null +++ b/playground/examples/optional/Main.res @@ -0,0 +1,16 @@ +type user = { + name: string, + age: int, + nickname?: string, +} + +// {name?: string, age?: int, nickname?: string} +type userPatch = %Patch.t(user) + +let update = (user: user, patch: userPatch): user => Patch.apply(user, patch) + +let ada: user = {name: "Ada", age: 36} + +Console.log(ada->update({age: 37})) +Console.log(ada->update({nickname: "countess"})) +Console.log(ada->update({nickname: "countess"})->update({name: "Ada Lovelace"})) diff --git a/playground/examples/optional/Patch.res b/playground/examples/optional/Patch.res new file mode 100644 index 0000000000..fb753adbc6 --- /dev/null +++ b/playground/examples/optional/Patch.res @@ -0,0 +1,37 @@ +open Macro + +// The type of an optional field is the type of `value.field`: for +// `nickname?: string` that is option. Reading the field, writing it +// with Code.entryOf and declaring it with Type.record all agree on it, so a +// macro needs no special case to be right for optional fields. + +// %Patch.t(user): the record type with every field optional. +// Type.optional leaves a field that is optional already as it is. +@macro +let t = (source: typ): typ => + switch Type.info(source) { + | Record({fields}) => Type.record(fields->Array.map(Type.optional)) + | _ => error(`Patch.t needs a record type, and ${Type.name(source)} is not one`) + } + +// Patch.apply(value, patch): the record with the fields of the patch that +// have a value. +@generic +let apply = (value: code<'a>, patch: code<'p>): code<'a> => + switch Type.info(typeOf(value)) { + | Record({fields}) => + Code.record( + fields->Array.map(f => { + let current = value->Code.field(f.name) + let change = patch->Code.field(f.name) + // entryOf takes a value of the type f.typ. It writes `name: value`, + // and `name: ?value` for an optional field, which leaves the field + // out of the record when the value is None. + Code.entryOf( + f, + f.optional ? %code(Option.orElse(${change}, ${current})) : %code(Option.getOr(${change}, ${current})), + ) + }), + ) + | _ => error("Patch.apply needs a record") + } diff --git a/playground/examples/record/Convert.res b/playground/examples/record/Convert.res new file mode 100644 index 0000000000..6d1e31516a --- /dev/null +++ b/playground/examples/record/Convert.res @@ -0,0 +1,31 @@ +open Macro + +// Convert.to(value) is a record of the type the call site expects, filled +// from the fields of `value` that have the same names. +// +// Which fields there are is known when the macro runs, not when it is +// written, so the record cannot be one quote. It is built from entries, one +// per field: Code.entry(name, value) is `name: value`. +@generic +let to = (value: code<'a>): code<'b> => + switch (Type.info(typeOf(value)), Type.info(expected())) { + | (Record({fields: sources}), Record({fields: targets})) => + Code.record( + targets->Array.filterMap(target => { + let read = value->Code.field(target.name) + switch sources->Array.find(source => source.name == target.name) { + // `name: value.name` + | Some({optional: false}) => Some(Code.entry(target.name, read)) + // Optional on both sides: `name: ?value.name` passes on an option, + // and leaves the field out when there is no value. + | Some(_) if target.optional => Some(Code.entry(target.name, read, ~optional=true)) + | Some(_) => + error(`Convert.to: ${target.name} is optional in ${Type.name(typeOf(value))} and required in ${Type.name(expected())}`) + // A field that is not there stays out when it may. + | None if target.optional => None + | None => error(`Convert.to: ${Type.name(typeOf(value))} has no field ${target.name}`) + } + }), + ) + | _ => error("Convert.to converts a record to a record") + } diff --git a/playground/examples/record/Main.res b/playground/examples/record/Main.res new file mode 100644 index 0000000000..26f6e83151 --- /dev/null +++ b/playground/examples/record/Main.res @@ -0,0 +1,26 @@ +type user = { + id: int, + name: string, + email: string, + passwordHash: string, + nickname?: string, +} + +// What the API returns: a user without the email and the password hash. +type publicUser = { + id: int, + name: string, + nickname?: string, + avatar?: string, +} + +let ada: user = {id: 1, name: "Ada", email: "ada@example.com", passwordHash: "x91f", nickname: "countess"} +let grace: user = {id: 2, name: "Grace", email: "grace@example.com", passwordHash: "b07c"} + +let shown: publicUser = Convert.to(ada) +Console.log(shown) +Console.log([ada, grace]->Array.map((user): publicUser => Convert.to(user))) + +// A field the source cannot give is a compile error at the call: +// type login = {name: string, password: string} +// let login: login = Convert.to(ada) diff --git a/playground/examples/splice/Main.res b/playground/examples/splice/Main.res new file mode 100644 index 0000000000..0dc317472a --- /dev/null +++ b/playground/examples/splice/Main.res @@ -0,0 +1,19 @@ +type point = {x: float, y: float} +type storedPoint = {key: string, version: int, x: float, y: float} + +let point = {x: 3.0, y: 4.0} + +// {key: "p1", version: 1, x: point.x, y: point.y} +let stored: storedPoint = Splice.withKey(point, "p1") +Console.log(stored) + +// distance(point.x, point.y) +let distance = (x, y) => Math.sqrt(x *. x +. y *. y) +Console.log(Splice.call(distance, point)) + +type level = Debug | Info | Warning | Error + +// One case per constructor, then the case of the quote. +let level: option = Splice.parse("Warning") +let unknown: option = Splice.parse("loud") +Console.log2(level, unknown) diff --git a/playground/examples/splice/Splice.res b/playground/examples/splice/Splice.res new file mode 100644 index 0000000000..9b9dc0c434 --- /dev/null +++ b/playground/examples/splice/Splice.res @@ -0,0 +1,48 @@ +open Macro + +// `${...items}` is a splice hole: it stands for any number of items of a +// list in a quote. The rest of the quote stays ordinary code. + +// Fields of a record, after fields the quote writes itself. +// `rest` is an array of entries, as Code.record takes. +@generic +let withKey = (value: code<'a>, key: code): code<'b> => + switch Type.info(typeOf(value)) { + | Record({fields}) => + let rest = fields->Array.map(f => Code.entryOf(f, value->Code.field(f.name))) + %code({key: ${key}, version: 1, ${...rest}}) + | _ => error("Splice.withKey needs a record") + } + +// Arguments of a call: an array of code. +@generic +let call = (f: code<'f>, value: code<'a>): code<'b> => + switch Type.info(typeOf(value)) { + | Record({fields}) => + let args = fields->Array.map(f => value->Code.field(f.name)) + %code(${f}(${...args})) + | _ => error("Splice.call needs a record") + } + +// Cases of a switch, before a case of the quote: an array of a pattern and +// the code of its case. +@generic +let parse = (text: code): code<'a> => + switch Type.info(expected()) { + | Option(inner) => + switch Type.info(inner) { + | Variant({constructors}) => + let cases = constructors->Array.map(c => ( + Pat.string(String.toLowerCase(c.name)), + %code(Some(${Code.ident(c.name)})), + )) + %code( + switch String.toLowerCase(${text}) { + ${...cases} + | _ => None + } + ) + | _ => error("Splice.parse needs a variant") + } + | _ => error("Splice.parse returns an option") + } From dc2abcc1ccd03a6073d8d579fecdcc6f062e24a0 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:46:04 +0100 Subject: [PATCH 25/38] docs: records from data, splice holes, optional fields, attributes Co-authored-by: Jaap Frolich Session: https://jakes-mac-mini.tail23a77e.ts.net:8443/session/os-01a1caab-4faf-7817-951e-2b3f9a5dae19 Signed-off-by: Jaap Frolich --- docs/comptime/IMPLEMENTATION.md | 28 ++++ docs/comptime/README.md | 218 +++++++++++++++++++++++++++++--- 2 files changed, 229 insertions(+), 17 deletions(-) diff --git a/docs/comptime/IMPLEMENTATION.md b/docs/comptime/IMPLEMENTATION.md index 6632f54615..a86d8f1518 100644 --- a/docs/comptime/IMPLEMENTATION.md +++ b/docs/comptime/IMPLEMENTATION.md @@ -28,6 +28,13 @@ compiler. Read that first. `res.hole` with the expression as payload, where an expression, a type or a pattern is expected. The scanner did not accept `$` outside template strings before, so no existing source changes meaning. +- `${...expr}` is a splice hole, the extension `res.hole.splice`. It parses + where a hole does, and in two places of its own: as a row of a record + (`{a: 1, ${...rest}}`, a field named `res.hole.splice` whose value is the + extension) and as a case of a switch (a case without a bar, with the + pattern `_` and the extension as its right-hand side). A block does not continue into a splice + hole, so one after a case is the next case and not an expression of that + case's body. - `%code(...)` has the ordinary payload of an extension: an expression or structure items. `%type(...)` takes a type and `%pat(...)` a pattern. - An extension whose name starts with an uppercase letter takes @@ -145,6 +152,27 @@ that stands where a whole declaration does. A quote of declarations lowers to `__quoteDecls`. At run time a quote is string concatenation, with parentheses around each filled hole except a declaration. +A splice hole is lowered by the list it is an item of, which the scan of a +quote records for each one (`SplicePlace`): + +| The list | The hole becomes | Its argument | +| --- | --- | --- | +| Arguments of a call or a constructor, items of an array or a tuple | `Macro.__spliceItems(items, trailing)` | `array>` | +| Fields of a record | `Macro.__spliceEntries(entries, trailing)` | `array` | +| Cases of a switch | `Macro.__spliceCases(cases)` | `array<(pat, code<'a>)>` | + +The operands of an operator are an application as well, and are not a list: +`1 + ${...xs}` is not a place for a splice. The comma after a hole of items +or entries belongs to the hole (`trailing`), which writes it when it has +items: a hole with none leaves no comma in the text. A splice hole in any +other place is left in the lowered code, where `quote::stray_splice` finds +it and expansion reports it at its position, as it does for one outside a +quote. + +A record value is built from entries (`Code.entry`, `Code.entryOf`, +`Code.spread`): `Code.record` and a splice hole in a record both take them, +and both put a spread before the fields, where the syntax wants it. + While it copies a piece, the lowering puts the file's module name in front of the top-level value and module names of the macro's own file, so that `encode(v)` inside a quote in `Json.res` reads `Json.encode(v)` at the use. diff --git a/docs/comptime/README.md b/docs/comptime/README.md index 0afb35deb4..8bb18e781b 100644 --- a/docs/comptime/README.md +++ b/docs/comptime/README.md @@ -84,6 +84,9 @@ code. `%type(...)` and `%pat(...)` quote a type and a pattern. A quote is checked for syntax where it is written. Its types are checked where the macro is used, after the holes are filled. +A hole stands for one thing. `${...items}` is a splice hole: it stands for +any number of items of a list. See [Lists in a quote](#lists-in-a-quote). + ```rescript @@ -276,10 +279,9 @@ let fromJson = (json: code): code<'a> => ) | Record({fields}) => Code.record( - fields->Array.map(f => ( - f.name, - %code((fromJson(field(${json}, ${Code.string(f.jsName)})): ${f.typ})), - )), + fields->Array.map(f => + Code.entryOf(f, %code((fromJson(field(${json}, ${Code.string(f.jsName)})): ${f.typ}))) + ), ) // ... } @@ -290,6 +292,10 @@ let user: user = Decode.fromJson(json) +`Code.entryOf(f, value)` is the field `f` of a record value. The next +sections are about it: [a record built from data](#a-record-built-from-data) +and [optional fields](#optional-fields). + The same idea gives a value for every type: @@ -322,6 +328,90 @@ let equal = (a: code<'a>, b: code<'a>): code => +### A record built from data + +A quote has the shape it is written with. A record whose fields are known +only when the macro runs is built from entries, one per field. +`Code.entry(name, value)` is `name: value` and `Code.spread(value)` is +`...value`. The values can have different types: the record is type checked +where the macro is used. + + + +```rescript +// Convert.res: a record of the expected type, from the fields of another +@generic +let to = (value: code<'a>): code<'b> => + switch (Type.info(typeOf(value)), Type.info(expected())) { + | (Record({fields: sources}), Record({fields: targets})) => + Code.record( + targets->Array.filterMap(target => { + let read = value->Code.field(target.name) + switch sources->Array.find(source => source.name == target.name) { + | Some({optional: false}) => Some(Code.entry(target.name, read)) + | Some(_) if target.optional => Some(Code.entry(target.name, read, ~optional=true)) + | None if target.optional => None + // ... the other two are errors at the call + } + }), + ) + | _ => error("Convert.to converts a record to a record") + } + +// Main.res +let shown: publicUser = Convert.to(ada) +``` + + + +`~optional=true` writes `name: ?value`: the value is an option, and `None` +leaves the field out of the record. + +### Lists in a quote + +`${...items}` is a splice hole. It stands for any number of items of a list +in a quote, and the rest of the quote stays ordinary code. What it takes +follows from the list it is in: + +| The list | The hole takes | | +| --- | --- | --- | +| Arguments of a call or a constructor, items of an array or a tuple | `array>` | `f(${...args})`, `[first, ${...rest}]` | +| Fields of a record | `array` | `{id: 1, ${...fields}}` | +| Cases of a switch | `array<(pat, code<'a>)>` | `switch x { ${...cases} }` | + + + +```rescript +// Fields of a record, after fields the quote writes itself. +@generic +let withKey = (value: code<'a>, key: code): code<'b> => + switch Type.info(typeOf(value)) { + | Record({fields}) => + let rest = fields->Array.map(f => Code.entryOf(f, value->Code.field(f.name))) + %code({key: ${key}, version: 1, ${...rest}}) + | _ => error("Splice.withKey needs a record") + } + +// Cases of a switch, before a case of the quote. +let cases = constructors->Array.map(c => ( + Pat.string(String.toLowerCase(c.name)), + %code(Some(${Code.ident(c.name)})), +)) +%code( + switch String.toLowerCase(${text}) { + ${...cases} + | _ => None + } +) +``` + + + +A splice hole with no items leaves nothing behind, the comma after it +included. Items of different types go in one array as `Code.untyped(item)`. +A splice hole that is not in one of these lists is an error where it is +written. + ### Declarations from a type A macro attached to a type receives the declaration and returns @@ -335,17 +425,18 @@ let derive = (t: Type.decl): decls => switch Type.info(t.typ) { | Variant({constructors}) => let label = (c: Type.constructor) => c.attrs->Attr.string("Enum.label")->Option.getOr(c.jsName) - let toString = Code.switch_( - %code(value), - constructors->Array.map(c => { - let (pattern, _) = Pat.constructor(c) - (pattern, Code.string(label(c))) - }), - ) + // One case per constructor: a pattern and the code of the case. + let names = constructors->Array.map(c => { + let (pattern, _) = Pat.constructor(c) + (pattern, Code.string(label(c))) + }) %code( - let ${Pat.var(t.name ++ "ToString")} = (value: ${t.typ}): string => ${toString} + let ${Pat.var(t.name ++ "ToString")} = (value: ${t.typ}): string => + switch value { + ${...names} + } let ${Pat.var(t.name ++ "Values")}: array<${t.typ}> = - ${Code.array(constructors->Array.map(c => Code.ident(c.name)))} + [${...constructors->Array.map(c => Code.ident(c.name))}] ) | _ => error("Enum.derive needs a variant type") } @@ -386,7 +477,7 @@ A macro in a type position takes types and returns a type. @macro let t = (source: typ): typ => switch Type.info(source) { - | Record({fields}) => Type.record(fields->Array.map(f => {...f, optional: true})) + | Record({fields}) => Type.record(fields->Array.map(Type.optional)) | _ => error(`Partial.t needs a record type, and ${Type.name(source)} is not one`) } @@ -396,6 +487,89 @@ type userPatch = %Partial.t(user) +### Optional fields + +The `typ` of a field is the type of `value.field`. For `nickname?: string` +that is `option`, and `optional` is true. Everything that reads, +writes, binds or declares a field agrees with that type: + +| | For `nickname?: string` | +| --- | --- | +| `value->Code.field(f.name)` | Code of type `option`. | +| `Code.entryOf(f, value)` | `nickname: ?value`, for a value of type `option`. `None` leaves the field out. | +| `Pat.constructor(c)` | Binds the field of an inline record as an `option`. | +| `Type.record([f])` | Declares `nickname?: string`. | +| `Type.optional(f)`, `Type.required(f)` | `age?: int` from `age: int`, and back. The `typ` follows. | + +A macro that treats every field the same is right for optional fields +without a special case. It looks at `f.optional` when it wants to do +something else for them. + + + +```rescript +// %Patch.t(user): every field optional +@macro +let t = (source: typ): typ => + switch Type.info(source) { + | Record({fields}) => Type.record(fields->Array.map(Type.optional)) + | _ => error(`Patch.t needs a record type, and ${Type.name(source)} is not one`) + } + +// Patch.apply(value, patch): the fields of the patch that have a value +@generic +let apply = (value: code<'a>, patch: code<'p>): code<'a> => + switch Type.info(typeOf(value)) { + | Record({fields}) => + Code.record( + fields->Array.map(f => { + let current = value->Code.field(f.name) + let change = patch->Code.field(f.name) + Code.entryOf( + f, + f.optional ? %code(Option.orElse(${change}, ${current})) : %code(Option.getOr(${change}, ${current})), + ) + }), + ) + | _ => error("Patch.apply needs a record") + } +``` + + + +A field that is made optional by hand, `{...f, optional: true}`, keeps a +`typ` that is not an option. `Type.record` reports that and names +`Type.optional`. + +### Attributes on generated code + +An attribute belongs to an expression, and generated code is an expression: +a quote writes the attribute in front of it. A field of a record value has +no place for an attribute, so it goes on the value of the field, or on the +whole record. + + + +```rescript +// Mock.make(): a record of functions that fail when they are called. Their +// parameters are not used, and the user of the macro gets no warning for it. +| Function({params}) => + let named = params->Array.mapWithIndex((typ, i) => Code.param("arg" ++ Int.toString(i + 1), typ)) + let stub = Code.fn(named, %code(throw(Failure(${Code.string(f.name ++ " is not mocked")})))) + Code.entryOf(f, %code(@warning("-27") ${stub})) + +// An attribute the macro computes: `@warning("-27") value` +@macro +let allow = (warning: int, value: code<'a>): code<'a> => + Code.withAttr(value, "warning", ~payload=Code.string("-" ++ Int.toString(warning))) +``` + + + +A hole cannot stand in an attribute: `Code.withAttr` is for a name or a +payload that is computed. The attributes of a field of a record type are +data, the `attrs` and the `jsName` of a `Type.field`. + ### Patterns and checked literals A macro that returns `pat` is used where a pattern is written. A macro that @@ -571,7 +745,7 @@ it is in the expanded source. So is generated code that does not parse: ## Reference -### The seven forms +### The forms | Form | Where | Meaning | | --- | --- | --- | @@ -581,6 +755,7 @@ it is in the expanded source. So is generated code that does not parse: | `%type(...)` | expression | A quoted type. | | `%pat(...)` | expression | A quoted pattern. | | `${...}` | inside a quote | A hole: an expression of type `code`, `typ` or `pat`, by its position. | +| `${...items}` | in a list of a quote | A splice hole: an array of the items of the list. The three dots are written. | | `%comptime(expr)` | expression | The value of `expr`, computed while compiling. | Everything else is the module `Macro` of the standard library @@ -627,9 +802,14 @@ compile-time parameter has to be called directly. | `Type.name(t)` | The type as source text: `array`. | | `Type.companion(t, name)` | The value `name` in the module that defines `t`, as code. | | `Type.record(fields)`, `Type.variant(constructors)`, `Type.field`, `Type.constructor` | Build a type. | +| `Type.option(t)` | `option`. | +| `Type.optional(field)`, `Type.required(field)` | The field as `age?: int`, and as `age: int`. | | `Code.string`, `int`, `float`, `bool`, `unit` | Literals. | | `Code.ident(name)` | A name that is resolved where the macro is used. | | `Code.field`, `array`, `tuple`, `record`, `call`, `switch_`, `fn` | Build code whose shape depends on data: a field access, a switch with one arm per constructor, a function with one parameter per name. | +| `Code.entry(name, value, ~optional=?)`, `Code.entryOf(field, value)`, `Code.spread(value)` | The entries `Code.record` and a splice hole in a record take: `name: value`, `name: ?value`, `...value`. | +| `Code.withAttr(value, name, ~payload=?)` | `@name(payload) value`. | +| `Code.untyped(code)` | The same code as `code`, to put code of different types in one array. | | `Code.print(code)` | The source text of a piece of code. | | `Code.raw(text)` | Code from source text. Nothing checks it until the macro's result is compiled. | | `Code.decls(items)` | Several declarations in a row. | @@ -653,8 +833,9 @@ type info = | Unknown // inference has not settled it ``` -A `field` has `name`, `jsName` (the `@as` name), `typ`, `optional`, -`mutable_` and `attrs`. A `constructor` has `name`, `jsName`, `args`, +A `field` has `name`, `jsName` (the `@as` name), `typ` (the type of +`value.name`: an option for an optional field), `optional`, `mutable_` and +`attrs`. A `constructor` has `name`, `jsName`, `args`, `fields` (of an inline record) and `attrs`. ### Rules @@ -782,6 +963,9 @@ implemented: - **A quote is checked where it is used.** An error in generated code names the place in the quote, but only once a use expands it: a macro whose quote cannot have the type the macro declares compiles until then. +- **Splice holes in patterns and types.** `${...items}` stands in lists of + expressions. The fields of a record type are built with `Type.record`, + and the arguments of a constructor pattern with `Pat.constructor`. - **Attribute payloads beyond one string.** `@Json.key("user_age")` reaches the macro; `@Json.codec({strict: true})` does not yet pass its argument. - **Parametric types.** `Type.info` of `result` or a record with type From 8314d53cb74365054739c1124ce3180f61443734 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:56:38 +0100 Subject: [PATCH 26/38] macros: test what splice holes and optional fields report A splice hole out of place, in a quote and outside one; an error in code that was spliced in, which keeps the place it was written at; a field made optional by hand. Co-authored-by: Jaap Frolich Session: https://jakes-mac-mini.tail23a77e.ts.net:8443/session/os-01a1caab-4faf-7817-951e-2b3f9a5dae19 Signed-off-by: Jaap Frolich --- compiler-rust/tests/macro_errors.rs | 47 +++++++++++++++++++ .../macro_errors/optionalFieldByHand.txt | 15 ++++++ .../tests/macro_errors/spliceOutOfPlace.txt | 15 ++++++ .../macro_errors/spliceOutsideAQuote.txt | 13 +++++ .../tests/macro_errors/splicedEntryType.txt | 24 ++++++++++ 5 files changed, 114 insertions(+) create mode 100644 compiler-rust/tests/macro_errors/optionalFieldByHand.txt create mode 100644 compiler-rust/tests/macro_errors/spliceOutOfPlace.txt create mode 100644 compiler-rust/tests/macro_errors/spliceOutsideAQuote.txt create mode 100644 compiler-rust/tests/macro_errors/splicedEntryType.txt diff --git a/compiler-rust/tests/macro_errors.rs b/compiler-rust/tests/macro_errors.rs index 4a24f8691f..d7a36ee3ad 100644 --- a/compiler-rust/tests/macro_errors.rs +++ b/compiler-rust/tests/macro_errors.rs @@ -214,3 +214,50 @@ fn comptime_errors() { ); }); } + +const SPLICED: &str = r#"open Macro + +// Entries of a record, one of them a quote with the wrong type. +@macro +let point = (x: code): code<'r> => { + let entries = [Code.entry("x", x), Code.entry("y", %code("two"))] + %code({${...entries}}) +} + +@macro +let flagged = (source: typ): typ => + switch Type.info(source) { + | Record({fields}) => Type.record(fields->Array.map(f => {...f, optional: true})) + | _ => error("flagged needs a record") + } +"#; + +#[test] +fn splice_holes_and_optional_fields() { + on_a_big_stack(|| { + let mut project = Project::new(); + project.compile("Spliced.res", SPLICED).unwrap(); + // A splice hole stands in a list of a quote, and nowhere else. + check( + &mut project, + "spliceOutOfPlace", + "open Macro\n@macro\nlet sum = (a: code): code => %code(1 + ${...[a]})\n", + ); + check( + &mut project, + "spliceOutsideAQuote", + "let xs = [1]\nlet ys = [0, ${...xs}]\n", + ); + // Spliced code keeps the place it was written at. + check( + &mut project, + "splicedEntryType", + "type point = {x: int, y: int}\nlet p: point = %Spliced.point(1)\n", + ); + check( + &mut project, + "optionalFieldByHand", + "type user = {name: string}\ntype t = %Spliced.flagged(user)\n", + ); + }); +} diff --git a/compiler-rust/tests/macro_errors/optionalFieldByHand.txt b/compiler-rust/tests/macro_errors/optionalFieldByHand.txt new file mode 100644 index 0000000000..a40ea22639 --- /dev/null +++ b/compiler-rust/tests/macro_errors/optionalFieldByHand.txt @@ -0,0 +1,15 @@ +type user = {name: string} +type t = %Spliced.flagged(user) +---- + + We've found a bug for you! + OptionalFieldByHand.res:2:10-31 + + 1 │ type user = {name: string} + 2 │ type t = %Spliced.flagged(user) + 3 │ + + The optional field `name` has the type `string`, and the type of an optional field is an option. Type.optional makes a field optional. + + This is reported by the macro `Spliced.flagged`. + diff --git a/compiler-rust/tests/macro_errors/spliceOutOfPlace.txt b/compiler-rust/tests/macro_errors/spliceOutOfPlace.txt new file mode 100644 index 0000000000..7e64a59631 --- /dev/null +++ b/compiler-rust/tests/macro_errors/spliceOutOfPlace.txt @@ -0,0 +1,15 @@ +open Macro +@macro +let sum = (a: code): code => %code(1 + ${...[a]}) +---- + + We've found a bug for you! + SpliceOutOfPlace.res:3:50-58 + + 1 │ open Macro + 2 │ @macro + 3 │ let sum = (a: code): code => %code(1 + ${...[a]}) + 4 │ + + A splice `${...items}` stands for the items of a list in a quote: the arguments of a call, the items of an array or a tuple, the fields of a record, or the cases of a switch. + diff --git a/compiler-rust/tests/macro_errors/spliceOutsideAQuote.txt b/compiler-rust/tests/macro_errors/spliceOutsideAQuote.txt new file mode 100644 index 0000000000..43c8b6bc0a --- /dev/null +++ b/compiler-rust/tests/macro_errors/spliceOutsideAQuote.txt @@ -0,0 +1,13 @@ +let xs = [1] +let ys = [0, ${...xs}] +---- + + We've found a bug for you! + SpliceOutsideAQuote.res:2:14-21 + + 1 │ let xs = [1] + 2 │ let ys = [0, ${...xs}] + 3 │ + + A splice `${...items}` stands for the items of a list in a quote: the arguments of a call, the items of an array or a tuple, the fields of a record, or the cases of a switch. + diff --git a/compiler-rust/tests/macro_errors/splicedEntryType.txt b/compiler-rust/tests/macro_errors/splicedEntryType.txt new file mode 100644 index 0000000000..43fae1c944 --- /dev/null +++ b/compiler-rust/tests/macro_errors/splicedEntryType.txt @@ -0,0 +1,24 @@ +type point = {x: int, y: int} +let p: point = %Spliced.point(1) +---- + + We've found a bug for you! + SplicedEntryType.res:2:16-32 + + 1 │ type point = {x: int, y: int} + 2 │ let p: point = %Spliced.point(1) + 3 │ + + This is in the code the macro generated, written at Spliced.res:6:60-64 + + 4 │ @macro + 5 │ let point = (x: code): code<'r> => { + 6 │ let entries = [Code.entry("x", x), Code.entry("y", %code("two"))] + 7 │ %code({${...entries}}) + 8 │ } + + This has type: string + But the record field y is expected to have type: int + + You can convert string to int with Int.fromString. + From 3251837c32dde0a4b53f01fe822f67f47ca7e289 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 16:00:03 +0100 Subject: [PATCH 27/38] macros: `%comptime(expr)` is written `%Macro.eval(expr)` Why: `%comptime` was the last place the first name of the feature was written. Everything else that runs while compiling is a macro, named by a module path, and a lowercase extension is a quote. The value of an expression is now the macro the compiler has built in: it is known by the name `Macro.eval`, and is an error where no expression is written. Breaking: `%comptime(expr)` is not evaluated any more. Write `%Macro.eval(expr)`. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/os-01a1caab-4faf-7817-951e-2b3f9a5dae19 Signed-off-by: Jaap Frolich --- compiler-rust/src/macros/discover.rs | 35 ++++++----- compiler-rust/src/macros/expand.rs | 58 +++++++++---------- compiler-rust/src/macros/host.js | 8 +-- compiler-rust/src/macros/mod.rs | 5 ++ compiler-rust/src/macros/reflect.rs | 2 +- compiler-rust/tests/macro_errors.rs | 25 +++++--- .../tests/macro_errors/comptimeFunction.txt | 11 ---- .../tests/macro_errors/comptimeLocal.txt | 15 ----- .../tests/macro_errors/comptimeThrows.txt | 12 ---- .../tests/macro_errors/evalFunction.txt | 11 ++++ .../tests/macro_errors/evalLocal.txt | 15 +++++ .../tests/macro_errors/evalThrows.txt | 12 ++++ .../{comptimeType.txt => evalType.txt} | 6 +- compiler-rust/tests/macros.rs | 4 +- playground/examples/comptime/Main.res | 8 --- playground/examples/eval/Main.res | 8 +++ .../examples/{comptime => eval}/Sieve.res | 0 playground/examples/index.json | 6 +- 18 files changed, 131 insertions(+), 110 deletions(-) delete mode 100644 compiler-rust/tests/macro_errors/comptimeFunction.txt delete mode 100644 compiler-rust/tests/macro_errors/comptimeLocal.txt delete mode 100644 compiler-rust/tests/macro_errors/comptimeThrows.txt create mode 100644 compiler-rust/tests/macro_errors/evalFunction.txt create mode 100644 compiler-rust/tests/macro_errors/evalLocal.txt create mode 100644 compiler-rust/tests/macro_errors/evalThrows.txt rename compiler-rust/tests/macro_errors/{comptimeType.txt => evalType.txt} (64%) delete mode 100644 playground/examples/comptime/Main.res create mode 100644 playground/examples/eval/Main.res rename playground/examples/{comptime => eval}/Sieve.res (100%) diff --git a/compiler-rust/src/macros/discover.rs b/compiler-rust/src/macros/discover.rs index 10aaaa40f8..c8734e454f 100644 --- a/compiler-rust/src/macros/discover.rs +++ b/compiler-rust/src/macros/discover.rs @@ -37,7 +37,7 @@ use crate::types::typedtree::{Expression, ExpressionDesc as TypedExpressionDesc} use super::edit::{Code, Edit, Segment, SourceText, Span, SpanSource}; use super::reflect::{self, TypeTable}; -use super::{MacroHost, is_macro_name, quote}; +use super::{EVAL_MACRO, MacroHost, is_macro_name, quote}; /// Whether the type checker expands macros. pub enum MacroMode { @@ -66,10 +66,10 @@ pub struct MacroDiagnostic { pub message: String, } -/// A `%comptime(expr)` found by a pass: evaluated between passes, when no +/// A `%Macro.eval(expr)` found by a pass: evaluated between passes, when no /// type checker is running. #[derive(Debug, Clone)] -pub struct ComptimeSite { +pub struct EvalSite { pub start: u32, pub end: u32, /// The expression's source text. @@ -466,7 +466,7 @@ pub struct Discovery { /// counts as being, for the order of what is reported. pub failed_items: Vec, pub instances: InstanceTable, - pub comptime: Vec, + pub evals: Vec, pending: Vec, /// Nesting of `type_structure`: 1 while typing a top-level item. depth: u32, @@ -494,7 +494,7 @@ pub struct PassResult { pub errors: Vec, pub failed_items: Vec, pub instances: InstanceTable, - pub comptime: Vec, + pub evals: Vec, } impl Discovery { @@ -512,7 +512,7 @@ impl Discovery { errors: Vec::new(), failed_items: Vec::new(), instances, - comptime: Vec::new(), + evals: Vec::new(), pending: Vec::new(), depth: 0, item_start: 0, @@ -620,7 +620,7 @@ impl Discovery { errors: self.errors, failed_items: self.failed_items, instances: self.instances, - comptime: self.comptime, + evals: self.evals, } } @@ -1096,6 +1096,15 @@ fn find_macro( loc: LocIdx, name: &str, ) -> Result, TypeCoreError> { + // Only `expression_extension` evaluates it. + if name == EVAL_MACRO { + return Err(error_at( + loc, + format!( + "`%{EVAL_MACRO}(expr)` is the value of an expression: it is written where an expression is." + ), + )); + } let Some((_, desc)) = lookup_value(tctx, env, name) else { let own_module = tctx .persistent_env @@ -1194,8 +1203,8 @@ pub(crate) fn expression_extension( ) })); } - if name == "comptime" { - return Some(comptime(tctx, env, loc, extension, expected_ty)); + if name == EVAL_MACRO { + return Some(eval(tctx, env, loc, extension, expected_ty)); } if !is_macro_name(&name) { return None; @@ -1254,9 +1263,9 @@ pub(crate) fn expression_extension( ))) } -/// `%comptime(expr)`: `expr` is typed as usual; its value replaces it +/// `%Macro.eval(expr)`: `expr` is typed as usual; its value replaces it /// between passes. -fn comptime( +fn eval( tctx: &mut TypeCheckContext<'_>, env: &Env, loc: LocIdx, @@ -1272,7 +1281,7 @@ fn comptime( return Err(fail( tctx, loc, - "%comptime takes one expression: `%comptime(expr)`.", + format!("%{EVAL_MACRO} takes one expression: `%{EVAL_MACRO}(expr)`."), )); } }; @@ -1284,7 +1293,7 @@ fn comptime( let shape = reflect::value_shape(ctx, env, typed.exp_type, 0); with_discovery(tctx, |_, discovery| { let expression = discovery.text.slice(inner.0, inner.1).to_string(); - discovery.comptime.push(ComptimeSite { + discovery.evals.push(EvalSite { start: at.0, end: at.1, expression, diff --git a/compiler-rust/src/macros/expand.rs b/compiler-rust/src/macros/expand.rs index 9bcee66394..1f0798aa1c 100644 --- a/compiler-rust/src/macros/expand.rs +++ b/compiler-rust/src/macros/expand.rs @@ -26,7 +26,7 @@ use crate::parser::{Parser, code_frame, module}; use crate::types::typemod::type_structure; use super::MacroHost; -use super::discover::{ComptimeSite, Discovery, InstanceTable, MacroDiagnostic, MacroMode}; +use super::discover::{Discovery, EvalSite, InstanceTable, MacroDiagnostic, MacroMode}; use super::edit::{Edit, LineTable, SourceText}; use super::quote; @@ -224,8 +224,8 @@ pub fn expand_source( let mut edits = pass.edits; let mut errors = pass.errors; - for site in &pass.comptime { - match evaluate_comptime( + for site in &pass.evals { + match evaluate( site, &opens, filename, @@ -380,7 +380,7 @@ fn generated_syntax_error( } /// The `open` statements at the top level of the file, as source text: -/// `%comptime` expressions are compiled in their scope. +/// `%Macro.eval` expressions are compiled in their scope. fn top_level_opens( parser: &Parser<'_>, structure: &[crate::parser::ast::StructureItem], @@ -400,10 +400,10 @@ fn top_level_opens( .collect() } -/// `%comptime(expr)`: compile `let value = expr` as a module of its own, +/// `%Macro.eval(expr)`: compile `let value = expr` as a module of its own, /// run it, and write the value back as a literal. -fn evaluate_comptime( - site: &ComptimeSite, +fn evaluate( + site: &EvalSite, opens: &[String], filename: &str, module_name: &str, @@ -413,7 +413,7 @@ fn evaluate_comptime( ) -> Result { if site.shape.get("k") == Some(&json!("other")) { return Err(format!( - "%comptime: a value of type {} cannot be written as a literal. Supported: int, float, string, bool, unit, arrays, tuples, options, dicts and records of those.", + "%Macro.eval: a value of type {} cannot be written as a literal. Supported: int, float, string, bool, unit, arrays, tuples, options, dicts and records of those.", site.shape .get("name") .and_then(Value::as_str) @@ -421,22 +421,22 @@ fn evaluate_comptime( )); } let source = format!("{}\nlet value = {}\n", opens.join("\n"), site.expression); - let comptime_module = format!("{module_name}__comptime"); - let comptime_file = std::path::Path::new(filename) - .with_file_name(format!("{comptime_module}.res")) + let eval_module = format!("{module_name}__eval"); + let eval_file = std::path::Path::new(filename) + .with_file_name(format!("{eval_module}.res")) .to_string_lossy() .into_owned(); - let mut comptime_options = options.clone(); - comptime_options.source_filename = Some(comptime_file.clone()); - comptime_options.module_name = Some(comptime_module.clone()); - comptime_options.capture_intermediates = false; - comptime_options.skip_js_render = false; - comptime_options.js_output_targets = Vec::new(); + let mut eval_options = options.clone(); + eval_options.source_filename = Some(eval_file.clone()); + eval_options.module_name = Some(eval_module.clone()); + eval_options.capture_intermediates = false; + eval_options.skip_js_render = false; + eval_options.js_output_targets = Vec::new(); let compiled = driver::compile_source_in_process( &source, - &comptime_file, - &comptime_module, - &comptime_options, + &eval_file, + &eval_module, + &eval_options, registry, false, ) @@ -445,7 +445,7 @@ fn evaluate_comptime( // its header: the expression is in this file, not in one of its own. let report = format!("{error:#}"); let said = report - .find(&comptime_file) + .find(&eval_file) .and_then(|at| report[at..].find("\n\n").map(|blank| &report[at + blank..])) .unwrap_or(&report); let said: Vec<&str> = said.trim_matches('\n').lines().map(str::trim_end).collect(); @@ -457,7 +457,7 @@ fn evaluate_comptime( .unwrap_or(0); let said: Vec<&str> = said.iter().map(|line| line.get(indent..).unwrap_or("")).collect(); format!( - "{}\n\n%comptime compiles its expression on its own, before the rest of this file: it can use other modules, not what this file defines.", + "{}\n\n%Macro.eval compiles its expression on its own, before the rest of this file: it can use other modules, not what this file defines.", said.join("\n") ) })?; @@ -475,9 +475,9 @@ fn evaluate_comptime( "answers": answers, }); let response = super::call_host(&**host, &request.to_string()) - .map_err(|message| format!("%comptime: the macro engine failed: {message}"))?; + .map_err(|message| format!("%Macro.eval: the macro engine failed: {message}"))?; let response: Value = serde_json::from_str(&response).map_err(|error| { - format!("%comptime: the macro engine returned invalid JSON: {error}") + format!("%Macro.eval: the macro engine returned invalid JSON: {error}") })?; if let Some(literal) = response.get("ok").and_then(Value::as_str) { return Ok(literal.to_string()); @@ -485,19 +485,19 @@ fn evaluate_comptime( if let Some(message) = response.get("error").and_then(Value::as_str) { return Err( if response.get("exception").and_then(Value::as_bool) == Some(true) { - format!("The expression of %comptime raised an exception:\n{message}") + format!("The expression of %Macro.eval raised an exception:\n{message}") } else { - format!("%comptime: {message}") + format!("%Macro.eval: {message}") }, ); } let Some(question) = response.get("need").and_then(Value::as_str) else { - return Err("%comptime: the macro engine returned an unknown response.".into()); + return Err("%Macro.eval: the macro engine returned an unknown response.".into()); }; let answer = super::discover::answer_input(&base_dir, question).unwrap_or_else( - || json!({ "__error": format!("`{question}` cannot be answered in %comptime.") }), + || json!({ "__error": format!("`{question}` cannot be answered in %Macro.eval.") }), ); answers.insert(question.to_string(), answer); } - Err("%comptime: the expression asked more than 1024 questions.".into()) + Err("%Macro.eval: the expression asked more than 1024 questions.".into()) } diff --git a/compiler-rust/src/macros/host.js b/compiler-rust/src/macros/host.js index 6de8e6619b..7420ad4fb7 100644 --- a/compiler-rust/src/macros/host.js +++ b/compiler-rust/src/macros/host.js @@ -136,7 +136,7 @@ case "int": return String(value | 0); case "float": - if (!isFinite(value)) throw { __macro_error: "%comptime: the value is not a finite number." }; + if (!isFinite(value)) throw { __macro_error: "%Macro.eval: the value is not a finite number." }; return /[.e]/.test(String(value)) ? String(value) : String(value) + "."; case "string": return JSON.stringify(String(value)); @@ -151,7 +151,7 @@ case "option": if (value === undefined) return "None"; if (value !== null && typeof value === "object" && value.BS_PRIVATE_NESTED_SOME_NONE !== undefined) { - throw { __macro_error: "%comptime: a nested option cannot be written as a literal." }; + throw { __macro_error: "%Macro.eval: a nested option cannot be written as a literal." }; } return "Some(" + reify(value, shape.of) + ")"; case "dict": @@ -165,7 +165,7 @@ return field.name + ": " + reify(item, field.of); }).filter(function (item) { return item !== null; }).join(", ") + "}"; default: - throw { __macro_error: "%comptime: a value of type " + shape.name + " cannot be written as a literal." }; + throw { __macro_error: "%Macro.eval: a value of type " + shape.name + " cannot be written as a literal." }; } } @@ -209,7 +209,7 @@ return JSON.stringify({ ok: "" }); } if (request.kind === "eval") { - // %comptime: `source` is a compiled module that exports `value`. + // %Macro.eval: `source` is a compiled module that exports `value`. var module = { exports: {} }; run(request.source, module); return JSON.stringify({ ok: reify(module.exports.value, request.shape) }); diff --git a/compiler-rust/src/macros/mod.rs b/compiler-rust/src/macros/mod.rs index 0a9f4f0286..0cab9e97ba 100644 --- a/compiler-rust/src/macros/mod.rs +++ b/compiler-rust/src/macros/mod.rs @@ -79,3 +79,8 @@ impl std::error::Error for MacroExpansionRequired {} pub fn is_macro_name(name: &str) -> bool { name.starts_with(|c: char| c.is_ascii_uppercase()) } + +/// The macro the compiler has built in: `%Macro.eval(expr)` is the value of +/// `expr`, computed while compiling. It is known by this name, not looked +/// up in the module `Macro`. +pub const EVAL_MACRO: &str = "Macro.eval"; diff --git a/compiler-rust/src/macros/reflect.rs b/compiler-rust/src/macros/reflect.rs index af8a5be645..ee531a3d71 100644 --- a/compiler-rust/src/macros/reflect.rs +++ b/compiler-rust/src/macros/reflect.rs @@ -348,7 +348,7 @@ fn constructor_info( } } -/// The shape `%comptime` needs to write a value of type `ty` as a literal +/// The shape `%Macro.eval` needs to write a value of type `ty` as a literal /// (read by `reify` in host.js). pub fn value_shape(ctx: &TypeContext, env: &Env, ty: TypeExprRef, depth: usize) -> Value { let unsupported = |ctx: &TypeContext, ty| json!({ "k": "other", "name": print_type(ctx, ty) }); diff --git a/compiler-rust/tests/macro_errors.rs b/compiler-rust/tests/macro_errors.rs index d7a36ee3ad..09ce2d9fc8 100644 --- a/compiler-rust/tests/macro_errors.rs +++ b/compiler-rust/tests/macro_errors.rs @@ -189,28 +189,35 @@ fn an_error_of_a_macro_is_reported_at_its_use() { } #[test] -fn comptime_errors() { +fn eval_errors() { on_a_big_stack(|| { let mut project = Project::new(); check( &mut project, - "comptimeLocal", - "let n = 3\nlet x = %comptime(n + 1)\n", + "evalLocal", + "let n = 3\nlet x = %Macro.eval(n + 1)\n", ); check( &mut project, - "comptimeThrows", - "let x = %comptime(Option.getOrThrow((None: option)))\n", + "evalThrows", + "let x = %Macro.eval(Option.getOrThrow((None: option)))\n", ); check( &mut project, - "comptimeType", - "let x = %comptime(1 + \"a\")\n", + "evalType", + "let x = %Macro.eval(1 + \"a\")\n", ); check( &mut project, - "comptimeFunction", - "let x = %comptime((a: int) => a)\n", + "evalFunction", + "let x = %Macro.eval((a: int) => a)\n", + ); + // It is an expression, with one argument. + check(&mut project, "evalWithoutExpression", "let x = %Macro.eval()\n"); + check( + &mut project, + "evalAsAPattern", + "let f = x =>\n switch x {\n | %Macro.eval(1) => true\n | _ => false\n }\n", ); }); } diff --git a/compiler-rust/tests/macro_errors/comptimeFunction.txt b/compiler-rust/tests/macro_errors/comptimeFunction.txt deleted file mode 100644 index d3a1963cf4..0000000000 --- a/compiler-rust/tests/macro_errors/comptimeFunction.txt +++ /dev/null @@ -1,11 +0,0 @@ -let x = %comptime((a: int) => a) ----- - - We've found a bug for you! - ComptimeFunction.res:1:9-32 - - 1 │ let x = %comptime((a: int) => a) - 2 │ - - %comptime: a value of type int => int cannot be written as a literal. Supported: int, float, string, bool, unit, arrays, tuples, options, dicts and records of those. - diff --git a/compiler-rust/tests/macro_errors/comptimeLocal.txt b/compiler-rust/tests/macro_errors/comptimeLocal.txt deleted file mode 100644 index 2226dab745..0000000000 --- a/compiler-rust/tests/macro_errors/comptimeLocal.txt +++ /dev/null @@ -1,15 +0,0 @@ -let n = 3 -let x = %comptime(n + 1) ----- - - We've found a bug for you! - ComptimeLocal.res:2:9-24 - - 1 │ let n = 3 - 2 │ let x = %comptime(n + 1) - 3 │ - - The value n can't be found - - %comptime compiles its expression on its own, before the rest of this file: it can use other modules, not what this file defines. - diff --git a/compiler-rust/tests/macro_errors/comptimeThrows.txt b/compiler-rust/tests/macro_errors/comptimeThrows.txt deleted file mode 100644 index 924f48d06f..0000000000 --- a/compiler-rust/tests/macro_errors/comptimeThrows.txt +++ /dev/null @@ -1,12 +0,0 @@ -let x = %comptime(Option.getOrThrow((None: option))) ----- - - We've found a bug for you! - ComptimeThrows.res:1:9-57 - - 1 │ let x = %comptime(Option.getOrThrow((None: option))) - 2 │ - - The expression of %comptime raised an exception: - Panic! Option.getOrThrow called for None value - diff --git a/compiler-rust/tests/macro_errors/evalFunction.txt b/compiler-rust/tests/macro_errors/evalFunction.txt new file mode 100644 index 0000000000..77a9b63e30 --- /dev/null +++ b/compiler-rust/tests/macro_errors/evalFunction.txt @@ -0,0 +1,11 @@ +let x = %Macro.eval((a: int) => a) +---- + + We've found a bug for you! + EvalFunction.res:1:9-34 + + 1 │ let x = %Macro.eval((a: int) => a) + 2 │ + + %Macro.eval: a value of type int => int cannot be written as a literal. Supported: int, float, string, bool, unit, arrays, tuples, options, dicts and records of those. + diff --git a/compiler-rust/tests/macro_errors/evalLocal.txt b/compiler-rust/tests/macro_errors/evalLocal.txt new file mode 100644 index 0000000000..a6bb94eabd --- /dev/null +++ b/compiler-rust/tests/macro_errors/evalLocal.txt @@ -0,0 +1,15 @@ +let n = 3 +let x = %Macro.eval(n + 1) +---- + + We've found a bug for you! + EvalLocal.res:2:9-26 + + 1 │ let n = 3 + 2 │ let x = %Macro.eval(n + 1) + 3 │ + + The value n can't be found + + %Macro.eval compiles its expression on its own, before the rest of this file: it can use other modules, not what this file defines. + diff --git a/compiler-rust/tests/macro_errors/evalThrows.txt b/compiler-rust/tests/macro_errors/evalThrows.txt new file mode 100644 index 0000000000..ad9cf77558 --- /dev/null +++ b/compiler-rust/tests/macro_errors/evalThrows.txt @@ -0,0 +1,12 @@ +let x = %Macro.eval(Option.getOrThrow((None: option))) +---- + + We've found a bug for you! + EvalThrows.res:1:9-59 + + 1 │ let x = %Macro.eval(Option.getOrThrow((None: option))) + 2 │ + + The expression of %Macro.eval raised an exception: + Panic! Option.getOrThrow called for None value + diff --git a/compiler-rust/tests/macro_errors/comptimeType.txt b/compiler-rust/tests/macro_errors/evalType.txt similarity index 64% rename from compiler-rust/tests/macro_errors/comptimeType.txt rename to compiler-rust/tests/macro_errors/evalType.txt index 165557a508..040940971b 100644 --- a/compiler-rust/tests/macro_errors/comptimeType.txt +++ b/compiler-rust/tests/macro_errors/evalType.txt @@ -1,10 +1,10 @@ -let x = %comptime(1 + "a") +let x = %Macro.eval(1 + "a") ---- We've found a bug for you! - ComptimeType.res:1:23-25 + EvalType.res:1:25-27 - 1 │ let x = %comptime(1 + "a") + 1 │ let x = %Macro.eval(1 + "a") 2 │ This has type: string diff --git a/compiler-rust/tests/macros.rs b/compiler-rust/tests/macros.rs index 0e080010e9..5fbd4bdcdb 100644 --- a/compiler-rust/tests/macros.rs +++ b/compiler-rust/tests/macros.rs @@ -285,7 +285,7 @@ let double = x => x * 2 } #[test] -fn comptime_evaluates_now() { +fn eval_computes_now() { let mut project = Project::new(); compile_ok( &mut project, @@ -295,7 +295,7 @@ fn comptime_evaluates_now() { let js = compile_ok( &mut project, "UseTable.res", - "let table = %comptime(Table.squares(5))\nlet label = %comptime(String.toUpperCase(\"abc\") ++ \"!\")\n", + "let table = %Macro.eval(Table.squares(5))\nlet label = %Macro.eval(String.toUpperCase(\"abc\") ++ \"!\")\n", ); assert!(js.contains("16"), "{js}"); assert!(js.contains("\"ABC!\""), "{js}"); diff --git a/playground/examples/comptime/Main.res b/playground/examples/comptime/Main.res deleted file mode 100644 index 53092e30ba..0000000000 --- a/playground/examples/comptime/Main.res +++ /dev/null @@ -1,8 +0,0 @@ -// The JavaScript output has the numbers, and no import of Sieve. -let primes = %comptime(Sieve.primesBelow(60)) -let fib25 = %comptime(Sieve.fib(25)) -let banner = %comptime(String.repeat("=", 20) ++ " primes " ++ String.repeat("=", 20)) - -Console.log(banner) -Console.log(primes) -Console.log(fib25) diff --git a/playground/examples/eval/Main.res b/playground/examples/eval/Main.res new file mode 100644 index 0000000000..6c28cc4948 --- /dev/null +++ b/playground/examples/eval/Main.res @@ -0,0 +1,8 @@ +// The JavaScript output has the numbers, and no import of Sieve. +let primes = %Macro.eval(Sieve.primesBelow(60)) +let fib25 = %Macro.eval(Sieve.fib(25)) +let banner = %Macro.eval(String.repeat("=", 20) ++ " primes " ++ String.repeat("=", 20)) + +Console.log(banner) +Console.log(primes) +Console.log(fib25) diff --git a/playground/examples/comptime/Sieve.res b/playground/examples/eval/Sieve.res similarity index 100% rename from playground/examples/comptime/Sieve.res rename to playground/examples/eval/Sieve.res diff --git a/playground/examples/index.json b/playground/examples/index.json index b890122cf8..657f934977 100644 --- a/playground/examples/index.json +++ b/playground/examples/index.json @@ -55,9 +55,9 @@ ] }, { - "id": "comptime", - "title": "%comptime: compute now", - "summary": "%comptime(expr) runs an expression while compiling and leaves its value in the output.", + "id": "eval", + "title": "%Macro.eval: compute now", + "summary": "%Macro.eval(expr) runs an expression while compiling and leaves its value in the output.", "files": [ "Sieve.res", "Main.res" From ee287121fddd3c7210ee25ec7150233e3cd449c1 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 16:00:03 +0100 Subject: [PATCH 28/38] docs: `%Macro.eval` in the RFC and the site The form `%comptime(expr)` leaves the table of forms, and `%Macro.eval(expr)` is listed with the module `Macro`. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/os-01a1caab-4faf-7817-951e-2b3f9a5dae19 Signed-off-by: Jaap Frolich --- CHANGELOG.md | 2 +- docs/comptime/IMPLEMENTATION.md | 17 +++++++++++------ docs/comptime/README.md | 17 +++++++++-------- playground/implementation.html | 2 +- playground/index.html | 2 +- 5 files changed, 23 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index be130bb8a9..ccb097c64a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,7 +21,7 @@ #### :rocket: New Feature -- Add compile-time macros to the Rust compiler: `@macro` and `@generic` functions that return quoted code (`%code`, `%type`, `%pat` with `${...}` holes), `%comptime`, and the `Macro` module. `rescript build` does not expand them yet; see `docs/comptime`. https://github.com/jfrolich/rescript-rust/pull/90 +- Add compile-time macros to the Rust compiler: `@macro` and `@generic` functions that return quoted code (`%code`, `%type`, `%pat` with `${...}` holes), `%Macro.eval`, and the `Macro` module. `rescript build` does not expand them yet; see `docs/comptime`. https://github.com/jfrolich/rescript-rust/pull/90 #### :bug: Bug fix diff --git a/docs/comptime/IMPLEMENTATION.md b/docs/comptime/IMPLEMENTATION.md index a86d8f1518..9e2a8c508e 100644 --- a/docs/comptime/IMPLEMENTATION.md +++ b/docs/comptime/IMPLEMENTATION.md @@ -8,10 +8,10 @@ compiler. Read that first. | Path | What | | --- | --- | | `compiler-rust/src/macros/mod.rs` | The `MacroHost` trait (the JavaScript engine), `MacroExpansionRequired`, and where compiler text and engine text are converted. | -| `compiler-rust/src/macros/expand.rs` | The expansion of one file: the pass loop, `%comptime` evaluation, position mapping. | +| `compiler-rust/src/macros/expand.rs` | The expansion of one file: the pass loop, `%Macro.eval`, position mapping. | | `compiler-rust/src/macros/discover.rs` | The type checker's hooks: recognizing macro uses, running the macro, recording edits, instances of generics. | | `compiler-rust/src/macros/quote.rs` | Lowering `%code`, `%type` and `%pat` in a macro's own file. | -| `compiler-rust/src/macros/reflect.rs` | Answers about types: `Type.info`, printing a type as source, the literal shape of a `%comptime` value. | +| `compiler-rust/src/macros/reflect.rs` | Answers about types: `Type.info`, printing a type as source, the literal shape of a `%Macro.eval` value. | | `compiler-rust/src/macros/edit.rs` | `SourceText`: text that knows where each character comes from, and edits on it. | | `compiler-rust/src/macros/report.rs` | What a diagnostic says about generated code. | | `compiler-rust/src/macros/host.js` | The engine side: module loader, sandbox, call entry point. The same script in QuickJS and in the browser. | @@ -66,7 +66,7 @@ sequenceDiagram E-->>T: need info:3 T->>E: call again, with the answer E-->>T: code as text - T-->>X: edits, errors, %comptime sites + T-->>X: edits, errors, %Macro.eval sites X->>X: apply edits end X-->>D: expanded text + origin map @@ -185,7 +185,7 @@ are called from `typecore.rs` and `typemod.rs`: | Hook | Called at | Does | | --- | --- | --- | -| `expression_extension` | `Pexp_extension` | `%M.f(...)`, `%comptime`, leftover quotes and holes | +| `expression_extension` | `Pexp_extension` | `%M.f(...)`, `%Macro.eval`, leftover quotes and holes | | `type_extension`, `pattern_extension` | `Ptyp_extension`, `Ppat_extension` | macros in type and pattern position | | `declarations_extension` | `Pstr_extension`, `Pmod_extension` | macros that return declarations | | `type_item`, `value_item` | a `type` or `let` item with a macro attribute | derive on a type, rewrite of a `let` | @@ -237,11 +237,16 @@ passes of a file. The calls a generated instance makes to the generic (the `encode(...)` on each field) are ordinary uses, found by the next pass. -### `%comptime` +### `%Macro.eval` + +`%Macro.eval(expr)` is known by its name (`macros::EVAL_MACRO`); the module +`Macro` has no value `eval`. It parses as any macro use does, with the +expression as its argument, and in a place other than an expression it is +an error. A discovery pass types the expression and records the site with the shape of its type (`reflect::value_shape`). After the pass, -`expand::evaluate_comptime` compiles `opens + let value = ` as a +`expand::evaluate` compiles `opens + let value = ` as a module of its own in memory, sends its JavaScript to the engine (`kind: "eval"`), and `host.js` writes the value as a literal by the shape. diff --git a/docs/comptime/README.md b/docs/comptime/README.md index 8bb18e781b..1b12fca9f6 100644 --- a/docs/comptime/README.md +++ b/docs/comptime/README.md @@ -609,14 +609,15 @@ let marathon = (miles: float) => Length.milesToMeters(miles) /. 1000.0 ### Computing now -`%comptime(expr)` evaluates an expression while compiling and puts the value -in its place as a literal. It needs no macro: `expr` is ordinary code that -uses other modules. +`%Macro.eval(expr)` evaluates an expression while compiling and puts the +value in its place as a literal. It is the one macro the compiler has built +in, so there is none to write: `expr` is ordinary code that uses other +modules. - + ```rescript -let primes = %comptime(Sieve.primesBelow(60)) +let primes = %Macro.eval(Sieve.primesBelow(60)) ``` ```js @@ -756,7 +757,6 @@ it is in the expanded source. So is generated code that does not parse: | `%pat(...)` | expression | A quoted pattern. | | `${...}` | inside a quote | A hole: an expression of type `code`, `typ` or `pat`, by its position. | | `${...items}` | in a list of a quote | A splice hole: an array of the items of the list. The three dots are written. | -| `%comptime(expr)` | expression | The value of `expr`, computed while compiling. | Everything else is the module `Macro` of the standard library (`packages/@rescript/runtime/Macro.res`). @@ -794,6 +794,7 @@ compile-time parameter has to be called directly. | | | | --- | --- | | `code<'a>`, `typ`, `pat`, `decls` | Code that evaluates to an `'a`; a type; a pattern; declarations. | +| `%Macro.eval(expr)` | The value of `expr`, computed while compiling. A macro the compiler has built in: it is written with this name, and is not a value of the module. | | `error(message)`, `errorAt(~offset, message)` | Stop compilation at the macro use. | | `typeOf(code)` | The type of an argument of a `@generic`. | | `expected()` | The type the call site of a `@generic` expects as result. | @@ -861,7 +862,7 @@ A `field` has `name`, `jsName` (the `@as` name), `typ` (the type of types and values of its arguments and its result type. A file has one instance per key, in a `let rec` group before the first top-level item that needs it. Instances are not shared between files. -- **`%comptime`** can use other modules, not values of its own file. The +- **`%Macro.eval`** can use other modules, not values of its own file. The value has to be writable as a literal: numbers, strings, booleans, `()`, arrays, tuples, options, dicts and records of those. @@ -993,7 +994,7 @@ implemented: noisier, and cannot be passed as a value. 3. **The engine.** QuickJS only, or Node as an option for macros that need npm packages with native parts. QuickJS runs plain JavaScript packages. -4. **Names.** `@macro`, `@generic`, `%code`, `%comptime`, the module +4. **Names.** `@macro`, `@generic`, `%code`, `%Macro.eval`, the module `Macro`. `Macro.Type` takes the place of the standard library's `Type` under `open Macro`; it includes that module so nothing is lost. 5. **Text or trees.** Expansion edits source text and type checks again. diff --git a/playground/implementation.html b/playground/implementation.html index 6b08cad940..bdd37cb57d 100644 --- a/playground/implementation.html +++ b/playground/implementation.html @@ -10,7 +10,7 @@ Macros: the compiler side · ReScript RFC diff --git a/playground/index.html b/playground/index.html index f2220b54db..3b8565088c 100644 --- a/playground/index.html +++ b/playground/index.html @@ -10,7 +10,7 @@ Compile-time macros for ReScript · RFC From 06c1889db60bae70e1adbe7926f7f95f0cc484af Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 15:06:08 +0000 Subject: [PATCH 29/38] macros: test %Macro.eval without an expression and as a pattern Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/os-01a1caab-4faf-7817-951e-2b3f9a5dae19 Signed-off-by: Jaap Frolich --- .../tests/macro_errors/evalAsAPattern.txt | 18 ++++++++++++++++++ .../macro_errors/evalWithoutExpression.txt | 11 +++++++++++ 2 files changed, 29 insertions(+) create mode 100644 compiler-rust/tests/macro_errors/evalAsAPattern.txt create mode 100644 compiler-rust/tests/macro_errors/evalWithoutExpression.txt diff --git a/compiler-rust/tests/macro_errors/evalAsAPattern.txt b/compiler-rust/tests/macro_errors/evalAsAPattern.txt new file mode 100644 index 0000000000..c5758d699c --- /dev/null +++ b/compiler-rust/tests/macro_errors/evalAsAPattern.txt @@ -0,0 +1,18 @@ +let f = x => + switch x { + | %Macro.eval(1) => true + | _ => false + } +---- + + We've found a bug for you! + EvalAsAPattern.res:3:5-18 + + 1 │ let f = x => + 2 │ switch x { + 3 │ | %Macro.eval(1) => true + 4 │ | _ => false + 5 │ } + + `%Macro.eval(expr)` is the value of an expression: it is written where an expression is. + diff --git a/compiler-rust/tests/macro_errors/evalWithoutExpression.txt b/compiler-rust/tests/macro_errors/evalWithoutExpression.txt new file mode 100644 index 0000000000..469ad69a8f --- /dev/null +++ b/compiler-rust/tests/macro_errors/evalWithoutExpression.txt @@ -0,0 +1,11 @@ +let x = %Macro.eval() +---- + + We've found a bug for you! + EvalWithoutExpression.res:1:9-21 + + 1 │ let x = %Macro.eval() + 2 │ + + %Macro.eval takes one expression: `%Macro.eval(expr)`. + From d9225eba13ea5b39e9c0338fd6d73cb910eefc64 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 20:55:22 +0000 Subject: [PATCH 30/38] playground: an example with types from a database schema `%Sql.tables()` reads the `create table` statements of schema.sql while compiling and is a module per table with the type of its rows. `%Sql.query("select ...")` checks a query against the same schema: its `row` is a record of the selected columns, its `run` takes a labelled argument per `:parameter` with the type of the column it is compared with, and a table or column that is not in the schema is an error of the macro. The row types are written with `Code.raw`: a hole in a quote is put in parentheses, which a record type as the body of a type declaration cannot be. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/os-01a1d178-0260-7bbc-a0b0-6180a8266b98 Signed-off-by: Jaap Frolich --- playground/examples/index.json | 10 ++ playground/examples/sql/Main.res | 39 ++++++++ playground/examples/sql/Sql.res | 146 +++++++++++++++++++++++++++++ playground/examples/sql/schema.sql | 13 +++ 4 files changed, 208 insertions(+) create mode 100644 playground/examples/sql/Main.res create mode 100644 playground/examples/sql/Sql.res create mode 100644 playground/examples/sql/schema.sql diff --git a/playground/examples/index.json b/playground/examples/index.json index 657f934977..639bd4e09a 100644 --- a/playground/examples/index.json +++ b/playground/examples/index.json @@ -54,6 +54,16 @@ "Main.res" ] }, + { + "id": "sql", + "title": "Types from a database schema", + "summary": "%Sql.tables() and %Sql.query(\"select ...\") read schema.sql while compiling: rows are typed records, and a column that does not exist is a compile error.", + "files": [ + "Sql.res", + "schema.sql", + "Main.res" + ] + }, { "id": "eval", "title": "%Macro.eval: compute now", diff --git a/playground/examples/sql/Main.res b/playground/examples/sql/Main.res new file mode 100644 index 0000000000..82bbe8b970 --- /dev/null +++ b/playground/examples/sql/Main.res @@ -0,0 +1,39 @@ +// The types of the tables come from schema.sql. +module Db = %Sql.tables() + +// A query is checked against the schema while compiling. +module InCity = %Sql.query("select name, vip from customers where city = :city") +module Large = %Sql.query("select * from orders where total >= :minimum and customer_id = :customer") + +// A column that is not in the schema does not compile: +// module Emails = %Sql.query("select email from customers") + +// Stands in for a database on this page: it prints the SQL it is given and +// answers with these rows. +let db: Sql.db = %raw(`{ + query(sql, params) { + console.log(sql, params) + return sql.includes("orders") + ? [ + {id: 7, customer_id: 1, total: 250.0, shipped_at: null}, + {id: 9, customer_id: 1, total: 120.5, shipped_at: new Date("2026-03-01")}, + ] + : [{id: 1, name: "Ada", city: "Utrecht", vip: true}] + } +}`) + +InCity.run(db, ~city="Utrecht")->Array.forEach(customer => + Console.log(customer.name ++ (customer.vip ? " is a vip" : "")) +) + +Large.run(db, ~minimum=100.0, ~customer=1)->Array.forEach(order => + switch order.shippedAt { + | Value(date) => Console.log2(order.id, "shipped on " ++ date->Date.toDateString) + | Null => Console.log2(order.id, "not shipped") + } +) + +switch Db.Customers.byId(db, 1) { +| Some({name, city: Value(city)}) => Console.log(name ++ " lives in " ++ city) +| _ => () +} diff --git a/playground/examples/sql/Sql.res b/playground/examples/sql/Sql.res new file mode 100644 index 0000000000..f7964ce07e --- /dev/null +++ b/playground/examples/sql/Sql.res @@ -0,0 +1,146 @@ +open Macro + +// What runs the SQL when the program runs: a driver with a `query` method. +type db +@send external exec: (db, string, array) => array<'row> = "query" +external param: 'a => unknown = "%identity" + +type column = { + sqlName: string, + // The type of a value of the column that is not null. + typ: typ, + // The field of the row type: `Null.t` when the column can be null, and + // `customerId` with the name `customer_id` at run time. + field: Type.field, +} +type table = {sqlName: string, columns: array} + +let capitalize = (text: string) => String.toUpperCase(String.charAt(text, 0)) ++ String.slice(text, ~start=1) + +// customer_id as customerId +let camel = (name: string) => + name->String.split("_")->Array.mapWithIndex((part, i) => i == 0 ? part : capitalize(part))->Array.join("") + +let columnType = (sqlType: string): typ => + switch String.toLowerCase(sqlType) { + | "integer" => %type(int) + | "text" => %type(string) + | "boolean" => %type(bool) + | "numeric" => %type(float) + | "timestamp" => %type(Date.t) + | other => error(`schema.sql has a column of the type ${other}, which Sql does not know`) + } + +// The tables of schema.sql, read while compiling. +let schema = (): array => + readFile("schema.sql") + ->String.split(";") + ->Array.filterMap(statement => + switch /create\s+table\s+(\w+)\s*\(([\s\S]*)\)/i->RegExp.exec(statement) { + | Some(found) => + switch found->RegExp.Result.matches { + | [Some(name), Some(body)] => + let columns = body->String.split(",\n")->Array.map(line => { + let words = line->String.trim->String.split(" ") + let sqlName = words->Array.getUnsafe(0) + let typ = columnType(words->Array.getUnsafe(1)) + let lower = String.toLowerCase(line) + let required = lower->String.includes("not null") || lower->String.includes("primary key") + { + sqlName, + typ, + field: {...Type.field(camel(sqlName), required ? typ : %type(Null.t<${typ}>)), jsName: sqlName}, + } + }) + Some({sqlName: name, columns}) + | _ => None + } + | None => None + } + ) + +let rowType = (name: string, columns: array): decls => + Code.raw(`type ${name} = ${Type.name(Type.record(columns->Array.map(c => c.field)))}`) + +// module Db = %Sql.tables(): a module per table of the schema, with the +// type of its rows, all of them, and the one with an id. +@macro +let tables = (): decls => + Code.decls( + schema()->Array.map(table => { + let select = "select * from " ++ table.sqlName + Code.decls([ + Code.raw(`module ${capitalize(table.sqlName)} = {`), + rowType("t", table.columns), + %code( + let all = (db: Sql.db): array => exec(db, ${Code.string(select)}, []) + let byId = (db: Sql.db, id: int): option => + exec(db, ${Code.string(select ++ " where id = $1")}, [param(id)])[0] + ), + Code.raw("}"), + ]) + }), + ) + +let shape = "Sql.query reads: select columns from table where column = :parameter" + +// module Q = %Sql.query("select ..."): the query is checked against the +// schema while compiling. `Q.row` is a record of the selected columns, and +// `Q.run` takes a labelled argument per `:parameter`, with the type of the +// column it is compared with. +@macro +let query = (sql: string): decls => { + let (selected, tableName) = switch /^\s*select\s+(.+?)\s+from\s+(\w+)/i->RegExp.exec(sql) { + | Some(found) => + switch found->RegExp.Result.matches { + | [Some(selected), Some(tableName)] => (selected, tableName) + | _ => error(shape) + } + | None => error(shape) + } + let tables = schema() + let table = switch tables->Array.find(table => table.sqlName == tableName) { + | Some(table) => table + | None => + error( + `There is no table "${tableName}" in schema.sql. It has: ${tables->Array.map(t => t.sqlName)->Array.join(", ")}`, + ) + } + let column = (name: string) => + switch table.columns->Array.find(c => c.sqlName == name) { + | Some(column) => column + | None => + error( + `The table "${tableName}" has no column "${name}". It has: ${table.columns + ->Array.map(c => c.sqlName) + ->Array.join(", ")}`, + ) + } + let columns = + String.trim(selected) == "*" + ? table.columns + : selected->String.split(",")->Array.map(name => column(String.trim(name))) + + // `city = :city` is `city = $1` for the driver, and the parameter `~city` + // of the type of the column. + let params = [] + let rec number = (text: string) => + switch /(\w+)\s*(?:=|<>|<=|>=|<|>)\s*:(\w+)/->RegExp.exec(text) { + | Some(found) => + switch found->RegExp.Result.matches { + | [Some(columnName), Some(name)] => + params->Array.push((name, column(columnName).typ)) + number(text->String.replace(":" ++ name, "$" ++ Int.toString(params->Array.length))) + | _ => text + } + | None => text + } + let numbered = number(sql) + + let values = params->Array.map(((name, _)) => %code(param(${Code.ident(name)}))) + let run = Code.fn( + [Code.param("db", %type(Sql.db))]->Array.concat(params->Array.map(((name, typ)) => Code.labelled(name, typ))), + %code((exec(db, ${Code.string(numbered)}, [${...values}]): array)), + ) + Code.decls([rowType("row", columns), %code(let run = ${run})]) +} diff --git a/playground/examples/sql/schema.sql b/playground/examples/sql/schema.sql new file mode 100644 index 0000000000..7f71e49a88 --- /dev/null +++ b/playground/examples/sql/schema.sql @@ -0,0 +1,13 @@ +create table customers ( + id integer primary key, + name text not null, + city text, + vip boolean not null +); + +create table orders ( + id integer primary key, + customer_id integer not null references customers(id), + total numeric not null, + shipped_at timestamp +); From c0f343c8e55a679112e5f0b4b185b37f81e9b711 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 20:55:22 +0000 Subject: [PATCH 31/38] docs: types from a schema in the RFC The tour shows the `sql` example after reading files: types and checked queries from a schema file, why the schema is a file and the query a string. What is missing lists what the example had to write as text: a record type as the body of a quoted type declaration, and a type of the macro's own file. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/os-01a1d178-0260-7bbc-a0b0-6180a8266b98 Signed-off-by: Jaap Frolich --- docs/comptime/README.md | 46 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/docs/comptime/README.md b/docs/comptime/README.md index 1b12fca9f6..8d1d5ab33e 100644 --- a/docs/comptime/README.md +++ b/docs/comptime/README.md @@ -658,6 +658,47 @@ greet(~name="Alice", ~count="3") This is reported by the macro `I18n.t`. ``` +### Types from a schema + +A macro that reads a file can give types to something outside the program. +Here `schema.sql` holds the `create table` statements of a database. +`%Sql.tables()` is a module per table with the type of its rows, and +`%Sql.query` checks a query against the schema: `row` is a record of the +selected columns, and `run` takes a labelled argument per `:parameter`, with +the type of the column it is compared with. + + + +```rescript +module Db = %Sql.tables() +module InCity = %Sql.query("select name, vip from customers where city = :city") + +InCity.run(db, ~city="Utrecht") // array, {name: string, vip: bool} +Db.Customers.byId(db, 1) // option +``` + + + +A column that can be null is a `Null.t`, and `customer_id` is the field +`customerId`. A column that is not in the schema does not compile: + +``` + We've found a bug for you! + Main.res:9:17-57 + + 8 │ // A column that is not in the schema does not compile: + 9 │ module Emails = %Sql.query("select email from customers") + + The table "customers" has no column "email". It has: id, name, city, vip + + This is reported by the macro `Sql.query`. +``` + +The schema is a file because a macro has no network: a dump of the database +is checked in, or written by a step of the build. The query is a string +because a macro sees the code of an argument as text, not as a tree it can +take apart. + ### Errors An error is reported in the code the person wrote, and says what the macro @@ -967,6 +1008,11 @@ implemented: - **Splice holes in patterns and types.** `${...items}` stands in lists of expressions. The fields of a record type are built with `Type.record`, and the arguments of a constructor pattern with `Pat.constructor`. +- **Type declarations in a quote.** A hole is written in parentheses, so + `type t = ${row}` is not a record type declaration, and a type of the + macro's own file is not resolved in that file the way a value is. The + `sql` example writes its row types with `Code.raw` and names `Sql.db` in + full. - **Attribute payloads beyond one string.** `@Json.key("user_age")` reaches the macro; `@Json.codec({strict: true})` does not yet pass its argument. - **Parametric types.** `Type.info` of `result` or a record with type From 2b68ace6d81cd1e2495619ca3a44718ff5a4bf3a Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 22:07:50 +0000 Subject: [PATCH 32/38] macros: a hole is the body of a quoted type declaration Why: A filled hole is written in parentheses, and a record or a variant type cannot be: `type row = ${Type.record(fields)}` in a quote was a syntax error where the macro is used, so a macro that declares a record type had to write the declaration as text with `Code.raw`. A type hole that is the body of a type declaration of the quote is lowered to `Macro.__holeTypeBody`, which fills it without parentheses. @macro let shapes = (): decls => %code( type point = ${Type.record([Type.field("x", %type(int)), Type.field("y", %type(int))])} type side = ${Type.variant([Type.constructor("Left"), Type.constructor("Right")])} ) Before (expanded): type point = ({x: int, y: int}) type side = (| Left | Right) After (expanded): type point = {x: int, y: int} type side = | Left | Right Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/os-01a1d178-0260-7bbc-a0b0-6180a8266b98 Signed-off-by: Jaap Frolich --- compiler-rust/src/macros/quote.rs | 18 +++++++++- compiler-rust/tests/macros.rs | 36 ++++++++++++++++++++ packages/@rescript/runtime/Macro.res | 3 ++ packages/@rescript/runtime/lib/es6/Macro.mjs | 8 +++++ packages/@rescript/runtime/lib/js/Macro.cjs | 8 +++++ 5 files changed, 72 insertions(+), 1 deletion(-) diff --git a/compiler-rust/src/macros/quote.rs b/compiler-rust/src/macros/quote.rs index bb54acbe57..2dc8d9929d 100644 --- a/compiler-rust/src/macros/quote.rs +++ b/compiler-rust/src/macros/quote.rs @@ -35,7 +35,7 @@ use crate::binary_ast::ast_iter::{self, AstIter}; use crate::parse_arena::{CoreTypeIdx, ExprIdx, LocIdx, ParseArena, PatIdx}; use crate::parser::ast::{ ArgLabel, CoreTypeDesc, ExpressionDesc, Extension, PatternDesc, Payload, StructureItem, - StructureItemDesc, + StructureItemDesc, TypeDeclaration, }; use crate::parser::longident::Longident; use crate::parser::module::{HOLE_EXTENSION, SPLICE_HOLE_EXTENSION}; @@ -157,6 +157,9 @@ enum SplicePlace { enum HoleKind { Code, Type, + /// The body of a type declaration, `type t = ${body}`. It is not put in + /// parentheses: a record or a variant type cannot be. + TypeBody, Pat, Item, Splice(SplicePlace), @@ -188,6 +191,8 @@ struct QuoteScan<'a> { item_exprs: &'a HashSet, /// The splice holes that are an item of a list, with the list. splice_places: HashMap, + /// The types that are the body of a type declaration of the quote. + type_bodies: HashSet, } fn is_splice(arena: &ParseArena, extension: &Extension) -> bool { @@ -367,6 +372,8 @@ impl AstIter for QuoteScan<'_> { inner, kind: if is_splice(arena, extension) { HoleKind::SpliceOutOfPlace + } else if self.type_bodies.contains(&idx) { + HoleKind::TypeBody } else { HoleKind::Type }, @@ -375,6 +382,13 @@ impl AstIter for QuoteScan<'_> { } ast_iter::walk_typ(self, arena, idx); } + + fn type_declaration(&mut self, arena: &ParseArena, td: &TypeDeclaration) { + if let Some(body) = td.ptype_manifest { + self.type_bodies.insert(body); + } + ast_iter::walk_type_declaration(self, arena, td); + } } /// Finds the quotes of a file that are not inside another quote. @@ -425,6 +439,7 @@ impl QuoteFinder<'_> { &item_exprs }, splice_places: HashMap::new(), + type_bodies: HashSet::new(), }; scan.payload(arena, &extension.1); @@ -532,6 +547,7 @@ impl QuoteFinder<'_> { let wrapper = match hole.kind { HoleKind::Code | HoleKind::SpliceOutOfPlace => "__holeCode", HoleKind::Type => "__holeType", + HoleKind::TypeBody => "__holeTypeBody", HoleKind::Pat => "__holePat", HoleKind::Item => "__holeItem", HoleKind::Splice(SplicePlace::Items) => "__spliceItems", diff --git a/compiler-rust/tests/macros.rs b/compiler-rust/tests/macros.rs index 5fbd4bdcdb..77644d203e 100644 --- a/compiler-rust/tests/macros.rs +++ b/compiler-rust/tests/macros.rs @@ -926,3 +926,39 @@ fn attribute_on_generated_code() { assert!(expanded.contains(r#"@warning("-27") (unused => 2)"#), "{expanded}"); assert_eq!(project.warnings, "", "{}", project.warnings); } + +const SHAPES: &str = r#" +open Macro + +// A record type, a variant type and another type as the body of a type +// declaration. +@macro +let shapes = (): decls => + %code( + type point = ${Type.record([Type.field("x", %type(int)), Type.field("y", %type(int))])} + type side = ${Type.variant([Type.constructor("Left"), Type.constructor("Right")])} + type points = ${%type(array)} + let origin: point = {x: 0, y: 0} + ) +"#; + +#[test] +fn a_hole_is_the_body_of_a_type_declaration() { + let mut project = Project::new(); + compile_ok(&mut project, "Shapes.res", SHAPES); + let js = compile_ok( + &mut project, + "Main.res", + r#" +%%Shapes.shapes() + +let path: points = [origin, {x: 1, y: 2}] +let side = Left +"#, + ); + let expanded = project.expanded.clone().unwrap(); + assert!(expanded.contains("type point = {x: int, y: int}"), "{expanded}"); + assert!(expanded.contains("type side = | Left | Right"), "{expanded}"); + assert!(expanded.contains("type points = array"), "{expanded}"); + assert!(js.contains("origin"), "{js}"); +} diff --git a/packages/@rescript/runtime/Macro.res b/packages/@rescript/runtime/Macro.res index d0ca3c5c46..cdfa8ab4ce 100644 --- a/packages/@rescript/runtime/Macro.res +++ b/packages/@rescript/runtime/Macro.res @@ -112,6 +112,9 @@ external __holeCode: code<'a> => hole = "%identity" external __holeType: typ => hole = "%identity" external __holePat: pat => hole = "%identity" let __holeItem = (value: code<'a>): hole => ofNode({...toNode(value), raw: true}) +/* The body of a type declaration, `type t = ${body}`: a record or a variant + type cannot be written in parentheses. */ +let __holeTypeBody = (value: typ): hole => ofNode({...toNode(value), raw: true}) /* A piece is the text between two holes: parts of the macro's file, each with its line and column there (line 0: text that is not from the file). */ diff --git a/packages/@rescript/runtime/lib/es6/Macro.mjs b/packages/@rescript/runtime/lib/es6/Macro.mjs index 9329e3bcea..9217b09e4f 100644 --- a/packages/@rescript/runtime/lib/es6/Macro.mjs +++ b/packages/@rescript/runtime/lib/es6/Macro.mjs @@ -92,6 +92,13 @@ function __holeItem(value) { }; } +function __holeTypeBody(value) { + return { + ...value, + raw: true + }; +} + let quote = (function (pieces, holes, file) { var parts = []; function add(piece) { @@ -641,6 +648,7 @@ export { readFile, env, __holeItem, + __holeTypeBody, quote, __quoteCode, __quoteDecls, diff --git a/packages/@rescript/runtime/lib/js/Macro.cjs b/packages/@rescript/runtime/lib/js/Macro.cjs index 74c224e2f5..6389450524 100644 --- a/packages/@rescript/runtime/lib/js/Macro.cjs +++ b/packages/@rescript/runtime/lib/js/Macro.cjs @@ -92,6 +92,13 @@ function __holeItem(value) { }; } +function __holeTypeBody(value) { + return { + ...value, + raw: true + }; +} + let quote = (function (pieces, holes, file) { var parts = []; function add(piece) { @@ -640,6 +647,7 @@ exports.expected = expected; exports.readFile = readFile; exports.env = env; exports.__holeItem = __holeItem; +exports.__holeTypeBody = __holeTypeBody; exports.quote = quote; exports.__quoteCode = __quoteCode; exports.__quoteDecls = __quoteDecls; From 74b3239eb5fa250185bff48d226cfb5d413032cb Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 22:09:44 +0000 Subject: [PATCH 33/38] macros: `Code.module_` builds a module with a computed name A quote writes the name of a module out, so a macro that makes a module per item of its data had to write `module Name = {` as text with `Code.raw`. `Code.module_(name, items)` is `module Name = { items }`, with the items a quote of declarations. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/os-01a1d178-0260-7bbc-a0b0-6180a8266b98 Signed-off-by: Jaap Frolich --- compiler-rust/tests/macros.rs | 34 ++++++++++++++++++++ packages/@rescript/runtime/Macro.res | 4 +++ packages/@rescript/runtime/lib/es6/Macro.mjs | 13 +++++++- packages/@rescript/runtime/lib/js/Macro.cjs | 13 +++++++- 4 files changed, 62 insertions(+), 2 deletions(-) diff --git a/compiler-rust/tests/macros.rs b/compiler-rust/tests/macros.rs index 77644d203e..c3219167c1 100644 --- a/compiler-rust/tests/macros.rs +++ b/compiler-rust/tests/macros.rs @@ -962,3 +962,37 @@ let side = Left assert!(expanded.contains("type points = array"), "{expanded}"); assert!(js.contains("origin"), "{js}"); } + +const NAMED: &str = r#" +open Macro + +// A module whose name is an argument of the macro. +@macro +let unit = (name: string, factor: float): decls => + Code.module_( + name, + %code( + type t = float + let toBase = (value: t) => value *. ${Code.float(factor)} + ), + ) +"#; + +#[test] +fn a_module_with_a_computed_name() { + let mut project = Project::new(); + compile_ok(&mut project, "Named.res", NAMED); + let js = compile_ok( + &mut project, + "Main.res", + r#" +%%Named.unit("Feet", 0.3048) + +let height: Feet.t = 6.0 +let meters = Feet.toBase(height) +"#, + ); + let expanded = project.expanded.clone().unwrap(); + assert!(expanded.contains("module Feet = {"), "{expanded}"); + assert!(js.contains("0.3048"), "{js}"); +} diff --git a/packages/@rescript/runtime/Macro.res b/packages/@rescript/runtime/Macro.res index cdfa8ab4ce..309034885d 100644 --- a/packages/@rescript/runtime/Macro.res +++ b/packages/@rescript/runtime/Macro.res @@ -475,6 +475,10 @@ module Code = { /** Several declarations, one after the other. */ let decls = (items: array): decls => build([join(items->Array.map(toNode), "\n")]) + + /** `module Name = { items }`, for a module whose name is computed. */ + let module_ = (name: string, items: decls): decls => + build([text("module " ++ name ++ " = {\n"), toNode(items), text("\n}")]) } module Pat = { diff --git a/packages/@rescript/runtime/lib/es6/Macro.mjs b/packages/@rescript/runtime/lib/es6/Macro.mjs index 9217b09e4f..3928a03f92 100644 --- a/packages/@rescript/runtime/lib/es6/Macro.mjs +++ b/packages/@rescript/runtime/lib/es6/Macro.mjs @@ -558,6 +558,16 @@ function decls(items) { return cat([join(items.map(prim => prim), "\n")]); } +function module_(name, items) { + return cat([ + text("module " + name + " = {\n"), + items, + { + c: "\n}" + } + ]); +} + let Code = { string: string$1, int: int, @@ -580,7 +590,8 @@ let Code = { param: param, labelled: labelled, fn: fn, - decls: decls + decls: decls, + module_: module_ }; let $$var = make; diff --git a/packages/@rescript/runtime/lib/js/Macro.cjs b/packages/@rescript/runtime/lib/js/Macro.cjs index 6389450524..c4246d61ca 100644 --- a/packages/@rescript/runtime/lib/js/Macro.cjs +++ b/packages/@rescript/runtime/lib/js/Macro.cjs @@ -558,6 +558,16 @@ function decls(items) { return cat([join(items.map(prim => prim), "\n")]); } +function module_(name, items) { + return cat([ + text("module " + name + " = {\n"), + items, + { + c: "\n}" + } + ]); +} + let Code = { string: string$1, int: int, @@ -580,7 +590,8 @@ let Code = { param: param, labelled: labelled, fn: fn, - decls: decls + decls: decls, + module_: module_ }; let $$var = make; From 228546b8def36c1715159cb306f3c14c90515330 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 22:09:44 +0000 Subject: [PATCH 34/38] playground: the sql example declares its types in quotes The row types are `type t = ${...}` in a quote and the module of a table is `Code.module_`: the example has no `Code.raw` left. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/os-01a1d178-0260-7bbc-a0b0-6180a8266b98 Signed-off-by: Jaap Frolich --- playground/examples/sql/Sql.res | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/playground/examples/sql/Sql.res b/playground/examples/sql/Sql.res index f7964ce07e..3e34243cee 100644 --- a/playground/examples/sql/Sql.res +++ b/playground/examples/sql/Sql.res @@ -59,8 +59,7 @@ let schema = (): array
    => } ) -let rowType = (name: string, columns: array): decls => - Code.raw(`type ${name} = ${Type.name(Type.record(columns->Array.map(c => c.field)))}`) +let rowType = (columns: array): typ => Type.record(columns->Array.map(c => c.field)) // module Db = %Sql.tables(): a module per table of the schema, with the // type of its rows, all of them, and the one with an id. @@ -69,16 +68,15 @@ let tables = (): decls => Code.decls( schema()->Array.map(table => { let select = "select * from " ++ table.sqlName - Code.decls([ - Code.raw(`module ${capitalize(table.sqlName)} = {`), - rowType("t", table.columns), + Code.module_( + capitalize(table.sqlName), %code( + type t = ${rowType(table.columns)} let all = (db: Sql.db): array => exec(db, ${Code.string(select)}, []) let byId = (db: Sql.db, id: int): option => exec(db, ${Code.string(select ++ " where id = $1")}, [param(id)])[0] ), - Code.raw("}"), - ]) + ) }), ) @@ -142,5 +140,8 @@ let query = (sql: string): decls => { [Code.param("db", %type(Sql.db))]->Array.concat(params->Array.map(((name, typ)) => Code.labelled(name, typ))), %code((exec(db, ${Code.string(numbered)}, [${...values}]): array)), ) - Code.decls([rowType("row", columns), %code(let run = ${run})]) + %code( + type row = ${rowType(columns)} + let run = ${run} + ) } From a3e14fa6290b24f1c88d59e60572d48e9b97b7f3 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 22:09:44 +0000 Subject: [PATCH 35/38] docs: a type hole as the body of a declaration, and `Code.module_` What is missing no longer lists the record type of a quoted declaration. It lists what is left: a type of the macro's own file is not resolved in that file, and a hole cannot be the name of a type or a module. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/os-01a1d178-0260-7bbc-a0b0-6180a8266b98 Signed-off-by: Jaap Frolich --- docs/comptime/IMPLEMENTATION.md | 8 +++++--- docs/comptime/README.md | 15 ++++++++++----- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/docs/comptime/IMPLEMENTATION.md b/docs/comptime/IMPLEMENTATION.md index 9e2a8c508e..8a8de89bad 100644 --- a/docs/comptime/IMPLEMENTATION.md +++ b/docs/comptime/IMPLEMENTATION.md @@ -148,9 +148,11 @@ the macro (an argument arrives with `$o`, the compiler's name for its range). character of the expanded text gets its origin. `__holeCode`, `__holeType` and `__holePat` are identity functions whose types make the hole's expression check as `code<'a>`, `typ` or `pat`; `__holeItem` is for a hole -that stands where a whole declaration does. A quote of declarations lowers -to `__quoteDecls`. At run time a quote is string concatenation, with -parentheses around each filled hole except a declaration. +that stands where a whole declaration does, and `__holeTypeBody` for one +that is the body of a type declaration (`type t = ${body}`). A quote of +declarations lowers to `__quoteDecls`. At run time a quote is string +concatenation, with parentheses around each filled hole except those two: +a record or a variant type cannot be written in parentheses. A splice hole is lowered by the list it is an item of, which the scan of a quote records for each one (`SplicePlace`): diff --git a/docs/comptime/README.md b/docs/comptime/README.md index 8d1d5ab33e..447bc478d7 100644 --- a/docs/comptime/README.md +++ b/docs/comptime/README.md @@ -487,6 +487,9 @@ type userPatch = %Partial.t(user) +A type a macro built can also be the body of a type declaration in a quote: +`%code(type row = ${Type.record(fields)})` declares the record type `row`. + ### Optional fields The `typ` of a field is the type of `value.field`. For `nickname?: string` @@ -855,6 +858,7 @@ compile-time parameter has to be called directly. | `Code.print(code)` | The source text of a piece of code. | | `Code.raw(text)` | Code from source text. Nothing checks it until the macro's result is compiled. | | `Code.decls(items)` | Several declarations in a row. | +| `Code.module_(name, items)` | `module Name = { items }`, for a module whose name is computed. | | `Pat.var(name)`, `Pat.any`, `Pat.string`, `Pat.int` | Patterns. | | `Pat.constructor(c)` | The pattern that matches a constructor and binds its arguments, and the code of each bound argument with its type. | | `Attr.find`, `has`, `string` | Look up an attribute of a field, constructor or declaration. | @@ -1008,11 +1012,12 @@ implemented: - **Splice holes in patterns and types.** `${...items}` stands in lists of expressions. The fields of a record type are built with `Type.record`, and the arguments of a constructor pattern with `Pat.constructor`. -- **Type declarations in a quote.** A hole is written in parentheses, so - `type t = ${row}` is not a record type declaration, and a type of the - macro's own file is not resolved in that file the way a value is. The - `sql` example writes its row types with `Code.raw` and names `Sql.db` in - full. +- **Types of the macro's file in a quote.** A value of the macro's own file + is resolved in that file, and a type is not: the `sql` example names + `Sql.db` in full. +- **Holes for the name of a type or a module.** A hole stands for the name + of a `let`, as `Pat.var`. The name of a type or a module in a quote is + written out; `Code.module_` is for a module whose name is computed. - **Attribute payloads beyond one string.** `@Json.key("user_age")` reaches the macro; `@Json.codec({strict: true})` does not yet pass its argument. - **Parametric types.** `Type.info` of `result` or a record with type From 818aef8dd4530b1c185618bd6c6812795c16a193 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 22:28:47 +0000 Subject: [PATCH 36/38] macros: a hole is the name of a module in a quote Why: A quote wrote the name of a module out, so a macro that makes a module per item of its data went through the builder `Code.module_` and passed the module's contents as an argument. With a hole for the name the module is written in the quote, like the rest of it. `module ${name} = ...` takes a string. The name of a module is a string in the parse tree, so the parser names the module `$hole`, which cannot be written, and keeps the hole as the attribute `res.hole` of the module; no node kind is added. The scan of a quote lowers it to `Macro.__holeModuleName`, which reports a string that cannot be the name of a module at the macro use. Outside a quote the module is reported as a hole is. @macro let unit = (name: string, factor: float): decls => %code( module ${name} = { type t = float let toBase = (value: t) => value *. ${Code.float(factor)} } ) %%Named.unit("Feet", 0.3048) After (expanded): module Feet = { type t = float let toBase = (value: t) => value *. (0.3048) } Diagnostic added (a name that is not one): Example: %%Named.unit("feet") After (error): The name of a module starts with a capital letter, with letters, digits and `_` after it: "feet" cannot be one. This is reported by the macro `Named.unit`. Breaking: `Code.module_(name, items)` is removed. Write `%code(module ${name} = { ... })`. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/os-01a1d178-0260-7bbc-a0b0-6180a8266b98 Signed-off-by: Jaap Frolich --- compiler-rust/src/macros/discover.rs | 35 ++++++++++++++-- compiler-rust/src/macros/quote.rs | 23 ++++++++++- compiler-rust/src/parser/module.rs | 41 +++++++++++++------ compiler-rust/src/types/typemod.rs | 6 ++- compiler-rust/tests/macro_errors.rs | 32 +++++++++++++++ .../tests/macro_errors/moduleNameNotOne.txt | 13 ++++++ .../macro_errors/moduleNameOutsideAQuote.txt | 19 +++++++++ .../tests/macro_errors/moduleNameType.txt | 18 ++++++++ compiler-rust/tests/macros.rs | 9 ++-- packages/@rescript/runtime/Macro.res | 19 +++++++-- packages/@rescript/runtime/lib/es6/Macro.mjs | 30 ++++++++------ packages/@rescript/runtime/lib/js/Macro.cjs | 30 ++++++++------ 12 files changed, 223 insertions(+), 52 deletions(-) create mode 100644 compiler-rust/tests/macro_errors/moduleNameNotOne.txt create mode 100644 compiler-rust/tests/macro_errors/moduleNameOutsideAQuote.txt create mode 100644 compiler-rust/tests/macro_errors/moduleNameType.txt diff --git a/compiler-rust/src/macros/discover.rs b/compiler-rust/src/macros/discover.rs index c8734e454f..a0808578f9 100644 --- a/compiler-rust/src/macros/discover.rs +++ b/compiler-rust/src/macros/discover.rs @@ -19,11 +19,11 @@ use serde_json::{Value, json}; use crate::parse_arena::{ExprIdx, LocIdx, ParseArena}; use crate::parser::ast::{ - ArgLabel, Constant, ExpressionDesc, Extension, PatternDesc, Payload, RecFlag, + ArgLabel, Constant, ExpressionDesc, Extension, ModuleBinding, PatternDesc, Payload, RecFlag, StructureItem as ParsedStructureItem, StructureItemDesc as ParsedStructureItemDesc, }; use crate::parser::longident::Longident; -use crate::parser::module::{HOLE_EXTENSION, SPLICE_HOLE_EXTENSION}; +use crate::parser::module::{HOLE_EXTENSION, HOLE_MODULE_NAME, SPLICE_HOLE_EXTENSION}; use crate::types::context::TypeContext; use crate::types::decl::ValueDescription; use crate::types::env::Env; @@ -2011,9 +2011,38 @@ pub(crate) fn value_item( Some(pending(tctx, loc)) } +/// What stops the typing of an item before it starts: a type item with a +/// macro in an ordinary compilation, and a module whose name is a hole. +pub(crate) fn item_stops_typing( + tctx: &mut TypeCheckContext<'_>, + item: &ParsedStructureItem, +) -> Option { + match &item.pstr_desc { + ParsedStructureItemDesc::Pstr_type(_) => type_item_requires_expansion(tctx, item), + ParsedStructureItemDesc::Pstr_module(binding) => module_name_hole(tctx, binding), + _ => None, + } +} + +/// `module ${name} = ...` outside a quote: the hole is the module's name. +fn module_name_hole( + tctx: &mut TypeCheckContext<'_>, + binding: &ModuleBinding, +) -> Option { + if tctx.arena.get_string(binding.pmb_name.txt) != HOLE_MODULE_NAME { + return None; + } + let loc = binding.pmb_name.loc; + Some(if matches!(tctx.macro_mode, MacroMode::Off) { + required(tctx, loc) + } else { + fail(tctx, loc, HOLE_OUTSIDE_QUOTE) + }) +} + /// Whether a type item carries a macro, for an ordinary compilation to /// stop at. -pub(crate) fn type_item_requires_expansion( +fn type_item_requires_expansion( tctx: &mut TypeCheckContext<'_>, item: &ParsedStructureItem, ) -> Option { diff --git a/compiler-rust/src/macros/quote.rs b/compiler-rust/src/macros/quote.rs index 2dc8d9929d..74055ff4cc 100644 --- a/compiler-rust/src/macros/quote.rs +++ b/compiler-rust/src/macros/quote.rs @@ -34,8 +34,8 @@ use std::collections::{HashMap, HashSet}; use crate::binary_ast::ast_iter::{self, AstIter}; use crate::parse_arena::{CoreTypeIdx, ExprIdx, LocIdx, ParseArena, PatIdx}; use crate::parser::ast::{ - ArgLabel, CoreTypeDesc, ExpressionDesc, Extension, PatternDesc, Payload, StructureItem, - StructureItemDesc, TypeDeclaration, + ArgLabel, CoreTypeDesc, ExpressionDesc, Extension, ModuleBinding, PatternDesc, Payload, + StructureItem, StructureItemDesc, TypeDeclaration, }; use crate::parser::longident::Longident; use crate::parser::module::{HOLE_EXTENSION, SPLICE_HOLE_EXTENSION}; @@ -160,6 +160,8 @@ enum HoleKind { /// The body of a type declaration, `type t = ${body}`. It is not put in /// parentheses: a record or a variant type cannot be. TypeBody, + /// The name of a module, `module ${name} = ...`: a string. + ModuleName, Pat, Item, Splice(SplicePlace), @@ -389,6 +391,22 @@ impl AstIter for QuoteScan<'_> { } ast_iter::walk_type_declaration(self, arena, td); } + + fn module_binding(&mut self, arena: &ParseArena, mb: &ModuleBinding) { + for attribute in mb.pmb_attributes.iter() { + // `module ${name} = ...`: the parser keeps the hole as an + // attribute of the module. + match hole_inner(arena, attribute) { + Some(inner) if !is_splice(arena, attribute) => self.holes.push(Hole { + outer: range(arena, attribute.0.loc), + inner, + kind: HoleKind::ModuleName, + }), + _ => self.attribute(arena, attribute), + } + } + self.module_expr(arena, mb.pmb_expr); + } } /// Finds the quotes of a file that are not inside another quote. @@ -548,6 +566,7 @@ impl QuoteFinder<'_> { HoleKind::Code | HoleKind::SpliceOutOfPlace => "__holeCode", HoleKind::Type => "__holeType", HoleKind::TypeBody => "__holeTypeBody", + HoleKind::ModuleName => "__holeModuleName", HoleKind::Pat => "__holePat", HoleKind::Item => "__holeItem", HoleKind::Splice(SplicePlace::Items) => "__spliceItems", diff --git a/compiler-rust/src/parser/module.rs b/compiler-rust/src/parser/module.rs index ea352d263e..84477b6bf7 100644 --- a/compiler-rust/src/parser/module.rs +++ b/compiler-rust/src/parser/module.rs @@ -3686,21 +3686,31 @@ fn parse_module_definition( /// OCaml `parse_module_binding` (compiler/syntax/src/res_core.ml:7046-7060). fn parse_module_binding( p: &mut Parser<'_>, - attrs: Attributes, + mut attrs: Attributes, start_pos_idx: PosIdx, ) -> ModuleBinding { - let name = match &p.token { - Token::Uident(n) => { - let n = n.clone(); - let loc = p.mk_loc_current(); - p.next(); - let n_idx = p.arena_mut().push_interned_string(&n); - with_loc(n_idx, loc) - } - _ => { - p.err(DiagnosticCategory::Uident(p.token.clone().into_owned())); - let error_idx = p.arena_mut().intern("_"); - mknoloc(error_idx) + // `module ${name} = ...` in a macro quote: the name is a hole. The + // module is named [`HOLE_MODULE_NAME`] and the hole is kept as an + // attribute of it, so no parsetree node kind is added. + let name = if p.token == Token::DollarLbrace && !at_splice_hole(p) { + let hole = parse_hole_extension(p); + let loc = hole.0.loc; + attrs.push(hole); + with_loc(p.arena_mut().intern(HOLE_MODULE_NAME), loc) + } else { + match &p.token { + Token::Uident(n) => { + let n = n.clone(); + let loc = p.mk_loc_current(); + p.next(); + let n_idx = p.arena_mut().push_interned_string(&n); + with_loc(n_idx, loc) + } + _ => { + p.err(DiagnosticCategory::Uident(p.token.clone().into_owned())); + let error_idx = p.arena_mut().intern("_"); + mknoloc(error_idx) + } } }; let body = parse_module_binding_body(p); @@ -4112,6 +4122,11 @@ pub fn parse_extension_id(p: &mut Parser<'_>, start_pos_idx: PosIdx) -> Located< /// Name of the extension a macro quote hole `${expr}` is kept as. pub const HOLE_EXTENSION: &str = "res.hole"; +/// The name of a module whose name is a hole, `module ${name} = ...`: one +/// that cannot be written. The hole is the attribute [`HOLE_EXTENSION`] of +/// the module. +pub const HOLE_MODULE_NAME: &str = "$hole"; + /// Name of the extension a splice hole `${...expr}` is kept as. pub const SPLICE_HOLE_EXTENSION: &str = "res.hole.splice"; diff --git a/compiler-rust/src/types/typemod.rs b/compiler-rust/src/types/typemod.rs index 7b9b3fb544..d42d80204e 100644 --- a/compiler-rust/src/types/typemod.rs +++ b/compiler-rust/src/types/typemod.rs @@ -5594,6 +5594,10 @@ fn check_structure_item_names( arena.get_string(constructor.pext_name.txt), )?; } + // `module ${name} = ...` outside a macro quote: reported as a hole + // when the item is typed, not as a name. + ParsedStructureItemDesc::Pstr_module(mb) + if arena.get_string(mb.pmb_name.txt) == crate::parser::module::HOLE_MODULE_NAME => {} ParsedStructureItemDesc::Pstr_module(mb) => { check_name( &mut names.modules, @@ -16792,7 +16796,7 @@ fn type_structure_item_with_macros<'a>( if let Some(error) = crate::macros::discover::value_item(tctx, env, item) { return Err(TypeModError::CoreError(error)); } - if let Some(error) = crate::macros::discover::type_item_requires_expansion(tctx, item) { + if let Some(error) = crate::macros::discover::item_stops_typing(tctx, item) { return Err(TypeModError::CoreError(error)); } let mut typed = type_structure_item(tctx, env, arena, item)?; diff --git a/compiler-rust/tests/macro_errors.rs b/compiler-rust/tests/macro_errors.rs index 09ce2d9fc8..09f645635a 100644 --- a/compiler-rust/tests/macro_errors.rs +++ b/compiler-rust/tests/macro_errors.rs @@ -268,3 +268,35 @@ fn splice_holes_and_optional_fields() { ); }); } + +const NAMED: &str = r#"open Macro + +@macro +let unit = (name: string): decls => + %code( + module ${name} = { + type t = float + } + ) +"#; + +#[test] +fn the_name_of_a_module() { + on_a_big_stack(|| { + let mut project = Project::new(); + project.compile("Named.res", NAMED).unwrap(); + // The hole takes a string that can be the name of a module. + check(&mut project, "moduleNameNotOne", "%%Named.unit(\"feet\")\n"); + check( + &mut project, + "moduleNameType", + "open Macro\n@macro\nlet f = (n: int): decls => %code(module ${n} = { let x = 1 })\n", + ); + // A hole is the name of a module in a quote, and nowhere else. + check( + &mut project, + "moduleNameOutsideAQuote", + "let name = \"Feet\"\nmodule ${name} = {\n let x = 1\n}\nmodule ${name} = {\n let y = 2\n}\n", + ); + }); +} diff --git a/compiler-rust/tests/macro_errors/moduleNameNotOne.txt b/compiler-rust/tests/macro_errors/moduleNameNotOne.txt new file mode 100644 index 0000000000..dfa2cd0589 --- /dev/null +++ b/compiler-rust/tests/macro_errors/moduleNameNotOne.txt @@ -0,0 +1,13 @@ +%%Named.unit("feet") +---- + + We've found a bug for you! + ModuleNameNotOne.res:1:1-20 + + 1 │ %%Named.unit("feet") + 2 │ + + The name of a module starts with a capital letter, with letters, digits and `_` after it: "feet" cannot be one. + + This is reported by the macro `Named.unit`. + diff --git a/compiler-rust/tests/macro_errors/moduleNameOutsideAQuote.txt b/compiler-rust/tests/macro_errors/moduleNameOutsideAQuote.txt new file mode 100644 index 0000000000..266172a6fe --- /dev/null +++ b/compiler-rust/tests/macro_errors/moduleNameOutsideAQuote.txt @@ -0,0 +1,19 @@ +let name = "Feet" +module ${name} = { + let x = 1 +} +module ${name} = { + let y = 2 +} +---- + + We've found a bug for you! + ModuleNameOutsideAQuote.res:2:8-14 + + 1 │ let name = "Feet" + 2 │ module ${name} = { + 3 │ let x = 1 + 4 │ } + + A hole `${...}` can only be used inside a quote: %code(...), %type(...) or %pat(...). + diff --git a/compiler-rust/tests/macro_errors/moduleNameType.txt b/compiler-rust/tests/macro_errors/moduleNameType.txt new file mode 100644 index 0000000000..992fab8bae --- /dev/null +++ b/compiler-rust/tests/macro_errors/moduleNameType.txt @@ -0,0 +1,18 @@ +open Macro +@macro +let f = (n: int): decls => %code(module ${n} = { let x = 1 }) +---- + + We've found a bug for you! + ModuleNameType.res:3:43 + + 1 │ open Macro + 2 │ @macro + 3 │ let f = (n: int): decls => %code(module ${n} = { let x = 1 }) + 4 │ + + This has type: int + But this function argument is expecting: string + + You can convert int to string with Int.toString. + diff --git a/compiler-rust/tests/macros.rs b/compiler-rust/tests/macros.rs index c3219167c1..1eb4fbea11 100644 --- a/compiler-rust/tests/macros.rs +++ b/compiler-rust/tests/macros.rs @@ -969,17 +969,16 @@ open Macro // A module whose name is an argument of the macro. @macro let unit = (name: string, factor: float): decls => - Code.module_( - name, - %code( + %code( + module ${name} = { type t = float let toBase = (value: t) => value *. ${Code.float(factor)} - ), + } ) "#; #[test] -fn a_module_with_a_computed_name() { +fn a_hole_is_the_name_of_a_module() { let mut project = Project::new(); compile_ok(&mut project, "Named.res", NAMED); let js = compile_ok( diff --git a/packages/@rescript/runtime/Macro.res b/packages/@rescript/runtime/Macro.res index 309034885d..700d2d567e 100644 --- a/packages/@rescript/runtime/Macro.res +++ b/packages/@rescript/runtime/Macro.res @@ -116,6 +116,21 @@ let __holeItem = (value: code<'a>): hole => ofNode({...toNode(value), raw: true} type cannot be written in parentheses. */ let __holeTypeBody = (value: typ): hole => ofNode({...toNode(value), raw: true}) +let isModuleName: string => bool = %raw(`function (text) { + return /^[A-Z][A-Za-z0-9_]*$/.test(text) +}`) +/* The name of a module, `module ${name} = ...`: a string. */ +let __holeModuleName = (name: string): hole => + if isModuleName(name) { + ofNode({c: name, raw: true}) + } else { + host->fail( + "The name of a module starts with a capital letter, with letters, digits and `_` after it: " ++ + JSON.stringify(JSON.Encode.string(name)) ++ " cannot be one.", + None, + ) + } + /* A piece is the text between two holes: parts of the macro's file, each with its line and column there (line 0: text that is not from the file). */ type piece = array<(string, int, int)> @@ -475,10 +490,6 @@ module Code = { /** Several declarations, one after the other. */ let decls = (items: array): decls => build([join(items->Array.map(toNode), "\n")]) - - /** `module Name = { items }`, for a module whose name is computed. */ - let module_ = (name: string, items: decls): decls => - build([text("module " ++ name ++ " = {\n"), toNode(items), text("\n}")]) } module Pat = { diff --git a/packages/@rescript/runtime/lib/es6/Macro.mjs b/packages/@rescript/runtime/lib/es6/Macro.mjs index 3928a03f92..6d19a2c38f 100644 --- a/packages/@rescript/runtime/lib/es6/Macro.mjs +++ b/packages/@rescript/runtime/lib/es6/Macro.mjs @@ -99,6 +99,21 @@ function __holeTypeBody(value) { }; } +let isModuleName = (function (text) { + return /^[A-Z][A-Za-z0-9_]*$/.test(text) +}); + +function __holeModuleName(name) { + if (isModuleName(name)) { + return { + c: name, + raw: true + }; + } else { + return __rescript_macro.fail("The name of a module starts with a capital letter, with letters, digits and `_` after it: " + JSON.stringify(name) + " cannot be one.", undefined); + } +} + let quote = (function (pieces, holes, file) { var parts = []; function add(piece) { @@ -558,16 +573,6 @@ function decls(items) { return cat([join(items.map(prim => prim), "\n")]); } -function module_(name, items) { - return cat([ - text("module " + name + " = {\n"), - items, - { - c: "\n}" - } - ]); -} - let Code = { string: string$1, int: int, @@ -590,8 +595,7 @@ let Code = { param: param, labelled: labelled, fn: fn, - decls: decls, - module_: module_ + decls: decls }; let $$var = make; @@ -660,6 +664,8 @@ export { env, __holeItem, __holeTypeBody, + isModuleName, + __holeModuleName, quote, __quoteCode, __quoteDecls, diff --git a/packages/@rescript/runtime/lib/js/Macro.cjs b/packages/@rescript/runtime/lib/js/Macro.cjs index c4246d61ca..82c30e2cd2 100644 --- a/packages/@rescript/runtime/lib/js/Macro.cjs +++ b/packages/@rescript/runtime/lib/js/Macro.cjs @@ -99,6 +99,21 @@ function __holeTypeBody(value) { }; } +let isModuleName = (function (text) { + return /^[A-Z][A-Za-z0-9_]*$/.test(text) +}); + +function __holeModuleName(name) { + if (isModuleName(name)) { + return { + c: name, + raw: true + }; + } else { + return __rescript_macro.fail("The name of a module starts with a capital letter, with letters, digits and `_` after it: " + JSON.stringify(name) + " cannot be one.", undefined); + } +} + let quote = (function (pieces, holes, file) { var parts = []; function add(piece) { @@ -558,16 +573,6 @@ function decls(items) { return cat([join(items.map(prim => prim), "\n")]); } -function module_(name, items) { - return cat([ - text("module " + name + " = {\n"), - items, - { - c: "\n}" - } - ]); -} - let Code = { string: string$1, int: int, @@ -590,8 +595,7 @@ let Code = { param: param, labelled: labelled, fn: fn, - decls: decls, - module_: module_ + decls: decls }; let $$var = make; @@ -659,6 +663,8 @@ exports.readFile = readFile; exports.env = env; exports.__holeItem = __holeItem; exports.__holeTypeBody = __holeTypeBody; +exports.isModuleName = isModuleName; +exports.__holeModuleName = __holeModuleName; exports.quote = quote; exports.__quoteCode = __quoteCode; exports.__quoteDecls = __quoteDecls; From e1d1edd46c7f340dd6973d0d5eb2019bdae814dc Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 22:28:47 +0000 Subject: [PATCH 37/38] playground: the sql example names its table modules with a hole The module of a table is `module ${capitalize(table.sqlName)} = {...}` in the quote that holds its declarations. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/os-01a1d178-0260-7bbc-a0b0-6180a8266b98 Signed-off-by: Jaap Frolich --- playground/examples/sql/Sql.res | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/playground/examples/sql/Sql.res b/playground/examples/sql/Sql.res index 3e34243cee..413458cde1 100644 --- a/playground/examples/sql/Sql.res +++ b/playground/examples/sql/Sql.res @@ -68,14 +68,13 @@ let tables = (): decls => Code.decls( schema()->Array.map(table => { let select = "select * from " ++ table.sqlName - Code.module_( - capitalize(table.sqlName), - %code( + %code( + module ${capitalize(table.sqlName)} = { type t = ${rowType(table.columns)} let all = (db: Sql.db): array => exec(db, ${Code.string(select)}, []) let byId = (db: Sql.db, id: int): option => exec(db, ${Code.string(select ++ " where id = $1")}, [param(id)])[0] - ), + } ) }), ) From 373bbd40a5b118afab5f36738dbd0d689f77be96 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 22:28:47 +0000 Subject: [PATCH 38/38] docs: a hole for the name of a module The forms, the tour and the implementation notes describe `module ${name} = ...`; `Code.module_` leaves the reference. What is missing keeps the name of a type, which a quote still writes out. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/os-01a1d178-0260-7bbc-a0b0-6180a8266b98 Signed-off-by: Jaap Frolich --- docs/comptime/IMPLEMENTATION.md | 7 +++++++ docs/comptime/README.md | 13 ++++++++----- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/docs/comptime/IMPLEMENTATION.md b/docs/comptime/IMPLEMENTATION.md index 8a8de89bad..253b88a903 100644 --- a/docs/comptime/IMPLEMENTATION.md +++ b/docs/comptime/IMPLEMENTATION.md @@ -154,6 +154,13 @@ declarations lowers to `__quoteDecls`. At run time a quote is string concatenation, with parentheses around each filled hole except those two: a record or a variant type cannot be written in parentheses. +The name of a module is a string in the parse tree, so the hole of +`module ${name} = ...` has no node to be. The parser names such a module +`$hole`, which cannot be written, and keeps the hole as the attribute +`res.hole` of the module. The scan of a quote lowers it to +`__holeModuleName`, which takes a string and checks that it can be the name +of a module. Outside a quote the type checker reports the module as a hole. + A splice hole is lowered by the list it is an item of, which the scan of a quote records for each one (`SplicePlace`): diff --git a/docs/comptime/README.md b/docs/comptime/README.md index 447bc478d7..6b96906be1 100644 --- a/docs/comptime/README.md +++ b/docs/comptime/README.md @@ -610,6 +610,10 @@ let marathon = (miles: float) => Length.milesToMeters(miles) /. 1000.0 +The name of a module in a quote can be a hole, which takes a string: +`%code(module ${name} = { let version = 1 })`. A string that cannot be the +name of a module is an error at the macro use. + ### Computing now `%Macro.eval(expr)` evaluates an expression while compiling and puts the @@ -799,7 +803,7 @@ it is in the expanded source. So is generated code that does not parse: | `%code(...)` | expression | A quoted expression, or quoted declarations when the content is `let`, `type` or `module` items. | | `%type(...)` | expression | A quoted type. | | `%pat(...)` | expression | A quoted pattern. | -| `${...}` | inside a quote | A hole: an expression of type `code`, `typ` or `pat`, by its position. | +| `${...}` | inside a quote | A hole: an expression of type `code`, `typ` or `pat`, by its position. Where the name of a module is written, `module ${name} = ...`, a string. | | `${...items}` | in a list of a quote | A splice hole: an array of the items of the list. The three dots are written. | Everything else is the module `Macro` of the standard library @@ -858,7 +862,6 @@ compile-time parameter has to be called directly. | `Code.print(code)` | The source text of a piece of code. | | `Code.raw(text)` | Code from source text. Nothing checks it until the macro's result is compiled. | | `Code.decls(items)` | Several declarations in a row. | -| `Code.module_(name, items)` | `module Name = { items }`, for a module whose name is computed. | | `Pat.var(name)`, `Pat.any`, `Pat.string`, `Pat.int` | Patterns. | | `Pat.constructor(c)` | The pattern that matches a constructor and binds its arguments, and the code of each bound argument with its type. | | `Attr.find`, `has`, `string` | Look up an attribute of a field, constructor or declaration. | @@ -1015,9 +1018,9 @@ implemented: - **Types of the macro's file in a quote.** A value of the macro's own file is resolved in that file, and a type is not: the `sql` example names `Sql.db` in full. -- **Holes for the name of a type or a module.** A hole stands for the name - of a `let`, as `Pat.var`. The name of a type or a module in a quote is - written out; `Code.module_` is for a module whose name is computed. +- **A hole for the name of a type.** A hole stands for the name of a `let`, + as `Pat.var`, and for the name of a module, as a string. The name of a + type in a quote is written out. - **Attribute payloads beyond one string.** `@Json.key("user_age")` reaches the macro; `@Json.codec({strict: true})` does not yet pass its argument. - **Parametric types.** `Type.info` of `result` or a record with type