From 4a67ebff910a87eb071ed5a26b552809095c16f4 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 21:59:36 +0100 Subject: [PATCH 01/11] macros: a macro runs from the file its name leads to Why: The engine was asked for the module that is the first part of the name at the use. That is not the file of the macro when the name goes through an alias (`module D = Debug`, then `%D.dbg(x)`) or names a module of an opened file: the macro was reported as needing a module that is not available at compile time. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/os-01a1caab-4faf-7817-951e-2b3f9a5dae19 Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- compiler-rust/src/macros/discover.rs | 7 ++++++- compiler-rust/tests/macros.rs | 12 ++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/compiler-rust/src/macros/discover.rs b/compiler-rust/src/macros/discover.rs index a0808578f9..697b0496d2 100644 --- a/compiler-rust/src/macros/discover.rs +++ b/compiler-rust/src/macros/discover.rs @@ -1150,7 +1150,12 @@ fn run_call( return None; } }; - let (module, value) = split_macro_name(name); + // The file the macro is in is where its name leads, which is not always + // its first part: the name can go through an alias (`module D = Debug`) + // or name a module of an opened file. + let resolved = + lookup_value(tctx, env, name).map(|(path, _)| env.normalize_path_prefix(&path).name()); + let (module, value) = split_macro_name(resolved.as_deref().unwrap_or(name)); let request = json!({ "kind": "call", "module": module, diff --git a/compiler-rust/tests/macros.rs b/compiler-rust/tests/macros.rs index 1eb4fbea11..2b96b2199a 100644 --- a/compiler-rust/tests/macros.rs +++ b/compiler-rust/tests/macros.rs @@ -41,6 +41,18 @@ fn expression_macro() { assert!(js.contains("\"age + 1 =\""), "{js}"); } +/// A macro runs from the file that defines it, also when it is named +/// through an alias of that file's module. +#[test] +fn macro_named_through_a_module_alias() { + let mut project = Project::new(); + project.compile("Debug.res", DEBUG).unwrap(); + let js = project + .compile("Main.res", "module D = Debug\nlet age = 41\nlet next = %D.dbg(age + 1)\n") + .unwrap(); + assert!(js.contains("\"age + 1 =\""), "{js}"); +} + const JSON: &str = r#" open Macro From 7edaa40067fd911f711b04c39fb9b6631350f7a4 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 21:59:36 +0100 Subject: [PATCH 02/11] compiler: what a read-eval-print loop needs of a compilation A loop compiles each input as a file of its own with the earlier inputs opened (`CompilerOptions::open_modules`), and runs its JavaScript once. The module `repl` adds the two things a compilation did not give: - `repl::prepare` binds a last item that is an expression to `it`, and lists the top-level opens, which the loop keeps open. - With `capture_intermediates`, the result has `signature_description`: every item the file defines as an interface declares it, and for a value the run-time shape of its type. A JavaScript value does not say what it is in ReScript (`Some(3)` is `3`, a constructor with a payload an object tagged `TAG`); the shape does. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/os-01a1caab-4faf-7817-951e-2b3f9a5dae19 Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- compiler-rust/src/driver.rs | 14 + compiler-rust/src/lib.rs | 1 + compiler-rust/src/macros/reflect.rs | 2 +- compiler-rust/src/repl.rs | 423 ++++++++++++++++++++++ compiler-rust/tests/macros_support/mod.rs | 10 + compiler-rust/tests/repl.rs | 130 +++++++ 6 files changed, 579 insertions(+), 1 deletion(-) create mode 100644 compiler-rust/src/repl.rs create mode 100644 compiler-rust/tests/repl.rs diff --git a/compiler-rust/src/driver.rs b/compiler-rust/src/driver.rs index 8d35e05ab4..023c733eb2 100644 --- a/compiler-rust/src/driver.rs +++ b/compiler-rust/src/driver.rs @@ -12510,6 +12510,9 @@ pub struct InProcessCompileResult { pub typed_tree_sexp: String, pub raw_lambda_sexp: String, pub lambda_sexp: String, + /// What the file defines, as JSON (`repl::describe_signature`); with + /// `CompilerOptions::capture_intermediates`. + pub signature_description: String, /// The intermediate representations requested by `CompilerOptions::dumps`. pub dumps: Vec<(DumpKind, String)>, /// The warning reports the file compile prints to stderr. @@ -12545,6 +12548,9 @@ pub struct InProcessPreJsCompileResult { pub typed_tree_sexp: String, pub raw_lambda_sexp: String, pub lambda_sexp: String, + /// What the file defines, as JSON (`repl::describe_signature`); with + /// `CompilerOptions::capture_intermediates`. + pub signature_description: String, /// The intermediate representations requested by `CompilerOptions::dumps`. pub dumps: Vec<(DumpKind, String)>, /// The warning reports the file compile prints to stderr. @@ -13670,6 +13676,12 @@ pub fn compile_preprocessed_structure_in_process_until_js( } else { String::new() }; + let signature_description = if options.capture_intermediates { + let signature = crate::types::includemod::simplify_signature(&typed_structure.str_type); + crate::repl::describe_signature(&type_ctx, &final_env, &signature).to_string() + } else { + String::new() + }; if !has_interface || gentype_ignore_interface { // With a `.resi`, compiler/gentype/Paths.ml:61-86 makes the @@ -13958,6 +13970,7 @@ pub fn compile_preprocessed_structure_in_process_until_js( loaded_modules, lam_locs, typed_tree_sexp, + signature_description, raw_lambda_sexp, lambda_sexp, dumps, @@ -14192,6 +14205,7 @@ pub fn finish_preprocessed_structure_in_process_from_js_boundary_with_metadata_h cmj_export_lambdas, hoisted_exports: pre_js.hoisted_exports, typed_tree_sexp: pre_js.typed_tree_sexp, + signature_description: pre_js.signature_description, raw_lambda_sexp: pre_js.raw_lambda_sexp, lambda_sexp: pre_js.lambda_sexp, dumps: pre_js.dumps, diff --git a/compiler-rust/src/lib.rs b/compiler-rust/src/lib.rs index 4f621976e4..1f10da63c2 100644 --- a/compiler-rust/src/lib.rs +++ b/compiler-rust/src/lib.rs @@ -54,6 +54,7 @@ pub mod parser; pub mod perf_counters; pub mod process_cwd; pub mod raw_lambda; +pub mod repl; /// Source text decoding helpers. pub mod source_text; pub mod string_literal; diff --git a/compiler-rust/src/macros/reflect.rs b/compiler-rust/src/macros/reflect.rs index ee531a3d71..74c5afd471 100644 --- a/compiler-rust/src/macros/reflect.rs +++ b/compiler-rust/src/macros/reflect.rs @@ -121,7 +121,7 @@ fn tag_text(tag: &LiteralTag) -> String { /// The type of a declaration's member (a field, a constructor argument) at /// the instance `args` of the declaration's parameters. -fn member_type( +pub(crate) fn member_type( ctx: &TypeContext, params: &[TypeExprRef], args: &[TypeExprRef], diff --git a/compiler-rust/src/repl.rs b/compiler-rust/src/repl.rs new file mode 100644 index 0000000000..6d45375532 --- /dev/null +++ b/compiler-rust/src/repl.rs @@ -0,0 +1,423 @@ +//! What a read-eval-print loop needs from the compiler. +//! +//! A loop compiles each input as a file of its own, with the files of the +//! earlier inputs opened, and runs its JavaScript once. Two things are not +//! in an ordinary compilation's result: +//! +//! - [`prepare`] finds what an input is made of: a last item that is an +//! expression is bound to `it`, so that it has a value to print, and the +//! `open`s are listed, so that the loop can keep them open. +//! - [`describe_signature`] says what an input defined: every item as source +//! text, and for a value the run-time shape of its type, which is what +//! turns a JavaScript value back into ReScript (`Some(3)` is `3` at run +//! time, `Circle(1.)` an object tagged `TAG`). + +use ahash::AHashMap; +use serde_json::{Value, json}; + +use crate::parser::ast::StructureItemDesc; +use crate::parser::{Parser, module}; +use crate::types::context::TypeContext; +use crate::types::ctype; +use crate::types::decl::{ + ConstructorArguments, LabelDeclaration, RecordRepresentation, SignatureItem, TypeKind, +}; +use crate::types::env::Env; +use crate::types::predef; +use crate::types::printtyp::{OutSigItem, Printtyp, print_out_sig_item}; +use crate::types::type_expr::{RowField, TypeDesc, TypeExprRef}; +use crate::types::variant_runtime::{Block, ConstructorCase, LiteralTag, Tag}; + +/// The name an input's last expression is bound to. +pub const RESULT_NAME: &str = "it"; + +/// What is written before an input's last expression. +pub const BINDING: &str = "let it = "; + +/// An input, ready to compile. +pub struct Prepared { + /// The input, with `let it = ` before a last item that is an expression. + pub source: String, + /// Where the binding was added, as a line and a column counted from + /// one: a position after it on that line is `BINDING.len()` further + /// than in the input. + pub result_at: Option<(usize, usize)>, + /// The text of each top-level `open`, in order. + pub opens: Vec, +} + +/// Parse `source` (as the compiler reads it: one character per byte) and +/// prepare it. `None` when it does not parse: compiling it as it is gives +/// the error. +pub fn prepare(source: &str, filename: &str) -> Option { + let mut parser = Parser::new(filename, source); + let structure = module::parse_structure(&mut parser); + if parser.has_errors() { + return None; + } + let arena = parser.arena(); + let characters: Vec = source.chars().collect(); + let range = |item: &crate::parser::ast::StructureItem| { + let start = arena.loc_start(item.pstr_loc).cnum.max(0) as usize; + let end = arena.loc_end(item.pstr_loc).cnum.max(0) as usize; + (start.min(characters.len()), end.min(characters.len())) + }; + let opens = structure + .iter() + .filter(|item| matches!(item.pstr_desc, StructureItemDesc::Pstr_open(_))) + .map(|item| { + let (start, end) = range(item); + characters[start..end].iter().collect() + }) + .collect(); + let result_start = structure + .last() + .filter(|item| matches!(item.pstr_desc, StructureItemDesc::Pstr_eval(_))) + .map(|item| range(item).0); + let source = match result_start { + Some(start) => { + let mut text: String = characters[..start].iter().collect(); + text.push_str(BINDING); + text.extend(&characters[start..]); + text + } + None => source.to_string(), + }; + let result_at = result_start.map(|start| { + let before = &characters[..start]; + let line_start = before + .iter() + .rposition(|character| *character == '\n') + .map_or(0, |newline| newline + 1); + let line = before + .iter() + .filter(|character| **character == '\n') + .count() + + 1; + (line, start - line_start + 1) + }); + Some(Prepared { + source, + result_at, + opens, + }) +} + +/// The items of `signature` as +/// `{items: [{kind, name, text, shape?}], defs: [...]}`: `text` is the item +/// as an interface would declare it, `shape` (of a value) the run-time shape +/// of its type, with `{k: "ref", id}` for an index into `defs`. +pub(crate) fn describe_signature( + ctx: &TypeContext, + env: &Env, + signature: &[SignatureItem], +) -> Value { + let mut printer = Printtyp::new(ctx); + printer.set_printing_env(Box::new(move |name| { + env.find_type_with_path(name).ok().map(|(path, _)| path) + })); + let trees = printer.tree_of_signature(signature); + + let mut shapes = Shapes { + ctx, + env, + defs: Vec::new(), + known: AHashMap::new(), + }; + // A name that is bound twice has the type of its last binding. + let value_types: AHashMap<&str, TypeExprRef> = signature + .iter() + .filter_map(|item| match item { + SignatureItem::SigValue(id, description) => Some((id.name(), description.val_type)), + _ => None, + }) + .collect(); + + let items: Vec = trees + .iter() + .filter_map(|tree| { + let (kind, name) = match tree { + OutSigItem::Osig_value(value) => ("value", value.name.clone()), + OutSigItem::Osig_type(declaration, _) => ("type", declaration.name.clone()), + OutSigItem::Osig_module(name, _, _) => ("module", name.clone()), + OutSigItem::Osig_modtype(name, _) => ("moduleType", name.clone()), + OutSigItem::Osig_typext(extension, _) => ("exception", extension.name.clone()), + OutSigItem::Osig_ellipsis | OutSigItem::Osig_class => return None, + }; + let mut item = serde_json::Map::new(); + item.insert("kind".into(), kind.into()); + item.insert("text".into(), print_out_sig_item(tree).into()); + if kind == "value" + && let Some(ty) = value_types.get(name.as_str()) + { + item.insert("shape".into(), shapes.of(*ty, 0)); + } + item.insert("name".into(), name.into()); + Some(Value::Object(item)) + }) + .collect(); + json!({ "items": items, "defs": shapes.defs }) +} + +/// Deeper than this, a value is shown as JavaScript. +const MAX_DEPTH: usize = 48; + +struct Shapes<'a> { + ctx: &'a TypeContext, + env: &'a Env, + /// The shapes of the records and variants met, by index. + defs: Vec, + /// The index of a record or variant type, by its path and arguments. + known: AHashMap, +} + +impl Shapes<'_> { + fn other(&self, ty: TypeExprRef) -> Value { + json!({ "k": "other", "name": crate::macros::reflect::print_type(self.ctx, ty) }) + } + + fn of(&mut self, ty: TypeExprRef, depth: usize) -> Value { + if depth > MAX_DEPTH { + return self.other(ty); + } + let ctx = self.ctx; + let expanded = ctx.repr(ctype::expand_head(ctx, self.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"), + (predef::path_bigint(), "bigint"), + (predef::path_char(), "char"), + ]; + for (predefined, kind) in &simple { + if path.same(predefined) { + return json!({ "k": kind }); + } + } + let containers = [ + (predef::path_option(), "option"), + (predef::path_array(), "array"), + (predef::path_list(), "list"), + (predef::path_dict(), "dict"), + (predef::path_promise(), "promise"), + ]; + for (predefined, kind) in &containers { + if path.same(predefined) && args.len() == 1 { + return json!({ "k": kind, "of": self.of(args[0], depth + 1) }); + } + } + if path.same(&predef::path_result()) && args.len() == 2 { + return json!({ + "k": "result", + "ok": self.of(args[0], depth + 1), + "error": self.of(args[1], depth + 1), + }); + } + self.declared(expanded, path, &args, depth) + } + TypeDesc::Ttuple(elements) => { + let of: Vec = ctx + .type_list(*elements) + .iter() + .map(|element| self.of(element, depth + 1)) + .collect(); + json!({ "k": "tuple", "of": of }) + } + TypeDesc::Tarrow { .. } => json!({ "k": "fn" }), + TypeDesc::Tpoly { body, .. } => self.of(*body, depth + 1), + TypeDesc::Tvariant(row) => { + let row = ctx.row_desc(*row); + let cases: Vec = row + .row_fields + .iter() + .filter_map(|(label, field)| { + let of = match field { + RowField::Rpresent(Some(arg)) => self.of(*arg, depth + 1), + RowField::Rpresent(None) => Value::Null, + RowField::Reither { constant: true, .. } => Value::Null, + RowField::Reither { types, .. } => match types.first() { + Some(arg) => self.of(*arg, depth + 1), + None => Value::Null, + }, + _ => return None, + }; + Some(json!({ "name": label.to_string(), "of": of })) + }) + .collect(); + json!({ "k": "poly", "cases": cases }) + } + _ => self.other(ty), + } + } + + /// A type with a declaration: a record or a variant is described once, + /// in `defs`, so that a type that mentions itself ends. + fn declared( + &mut self, + ty: TypeExprRef, + path: &crate::types::path::Path, + args: &[TypeExprRef], + depth: usize, + ) -> Value { + let ctx = self.ctx; + let Some(decl) = crate::types::typemod::find_type_decl_for_path(self.env, ctx, path) else { + return self.other(ty); + }; + if !matches!( + decl.type_kind, + TypeKind::TypeRecord(..) | TypeKind::TypeVariant(..) + ) { + return self.other(ty); + } + let key = format!( + "{}<{}>", + path.name(), + args.iter() + .map(|arg| crate::macros::reflect::print_type(ctx, *arg)) + .collect::>() + .join(", ") + ); + if let Some(id) = self.known.get(&key) { + return json!({ "k": "ref", "id": id }); + } + let id = self.defs.len(); + self.known.insert(key, id); + self.defs.push(Value::Null); + let params = &decl.type_params; + let def = match &decl.type_kind { + TypeKind::TypeRecord(labels, representation) => json!({ + "k": "record", + "unboxed": matches!(representation, RecordRepresentation::RecordUnboxed(_)), + "fields": self.fields(params, args, labels, depth), + }), + TypeKind::TypeVariant(constructors, layout) => { + let layout = ctx.variant_layout(*layout); + let cases: Vec = constructors + .iter() + .zip(layout.constructors.iter()) + .map(|(constructor, case)| { + let (arguments, fields) = match &constructor.cd_args { + ConstructorArguments::CstrTuple(types) => ( + types + .iter() + .map(|member| { + let member = crate::macros::reflect::member_type( + ctx, params, args, *member, + ); + self.of(member, depth + 1) + }) + .collect::>(), + Value::Null, + ), + ConstructorArguments::CstrRecord(labels) => ( + Vec::new(), + Value::Array(self.fields(params, args, labels, depth)), + ), + }; + let (constant, tag, tag_name, untagged) = match case { + ConstructorCase::Constant(tag) => (true, tag, None, false), + ConstructorCase::Block(Block::Tagged(block)) => { + (false, &block.tag, block.tag_name.clone(), false) + } + ConstructorCase::Block(Block::Untagged { tag, .. }) => { + (false, tag, None, true) + } + }; + json!({ + "name": constructor.cd_id.name(), + "constant": constant, + "tag": literal(tag), + "tagName": tag_name.unwrap_or_else(|| "TAG".into()), + "untagged": untagged, + "args": arguments, + "fields": fields, + }) + }) + .collect(); + json!({ "k": "variant", "unboxed": layout.unboxed, "cases": cases }) + } + _ => unreachable!("checked above"), + }; + self.defs[id] = def; + json!({ "k": "ref", "id": id }) + } + + fn fields( + &mut self, + params: &[TypeExprRef], + args: &[TypeExprRef], + labels: &[LabelDeclaration], + depth: usize, + ) -> Vec { + labels + .iter() + .map(|label| { + let name = label.ld_id.name().to_string(); + let member = + crate::macros::reflect::member_type(self.ctx, params, args, label.ld_type); + let shape = self.of(member, depth + 1); + // An optional field holds the value itself, not an option. + 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() + } +} + +/// The value a constructor is at run time, or the value of its tag: what +/// `@as` states, and the constructor's name when it states nothing. +fn literal(tag: &Tag) -> Value { + match &tag.literal { + None => json!({ "t": "string", "v": tag.name.to_string() }), + Some(LiteralTag::String(text)) => json!({ "t": "string", "v": text }), + Some(LiteralTag::Int(number)) => json!({ "t": "number", "v": number }), + Some(LiteralTag::Float(text)) => json!({ "t": "number", "v": text.parse::().ok() }), + Some(LiteralTag::BigInt(text)) => json!({ "t": "bigint", "v": text }), + Some(LiteralTag::Bool(value)) => json!({ "t": "boolean", "v": value }), + Some(LiteralTag::Null) => json!({ "t": "null" }), + Some(LiteralTag::Undefined) => json!({ "t": "undefined" }), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_last_expression_is_bound() { + let prepared = prepare("let x = 1\n x + 1\n", "Input.res").unwrap(); + assert_eq!(prepared.source, "let x = 1\n let it = x + 1\n"); + assert_eq!(prepared.result_at, Some((2, 3))); + assert!(prepared.opens.is_empty()); + } + + #[test] + fn declarations_are_left_as_written() { + let source = "open Belt\ntype t = A\nConsole.log(1)\nlet x = A\nopen! Stdlib.Array\n"; + let prepared = prepare(source, "Input.res").unwrap(); + assert_eq!(prepared.source, source); + assert_eq!(prepared.result_at, None); + assert_eq!(prepared.opens, ["open Belt", "open! Stdlib.Array"]); + } + + #[test] + fn an_input_that_does_not_parse_is_not_prepared() { + assert!(prepare("let x = (", "Input.res").is_none()); + } +} diff --git a/compiler-rust/tests/macros_support/mod.rs b/compiler-rust/tests/macros_support/mod.rs index b05887a4b6..9604ec5edb 100644 --- a/compiler-rust/tests/macros_support/mod.rs +++ b/compiler-rust/tests/macros_support/mod.rs @@ -28,6 +28,10 @@ pub struct Project { pub expanded: Option, /// The warnings of the last compiled file. pub warnings: String, + /// The modules that are opened in the files compiled from here on. + pub open_modules: Vec, + /// What the last compiled file defines (`repl::describe_signature`). + pub signature: serde_json::Value, } impl Project { @@ -71,6 +75,8 @@ impl Project { host, expanded: None, warnings: String::new(), + open_modules: Vec::new(), + signature: serde_json::Value::Null, }; // 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(); @@ -91,6 +97,8 @@ impl Project { source_filename: Some(filename.to_string()), module_name: Some(module_name.clone()), macro_host: Some(host), + open_modules: self.open_modules.clone(), + capture_intermediates: true, ..Default::default() }; // As the compiler reads a file: one `char` per byte. @@ -128,6 +136,8 @@ impl Project { self.host.invalidate(); self.expanded = compiled.expanded_source.as_deref().map(text); self.warnings = text(&compiled.warnings); + self.signature = serde_json::from_str(&compiled.signature_description) + .unwrap_or(serde_json::Value::Null); Ok(js) } Err(e) => Err( diff --git a/compiler-rust/tests/repl.rs b/compiler-rust/tests/repl.rs new file mode 100644 index 0000000000..a3bccd16d8 --- /dev/null +++ b/compiler-rust/tests/repl.rs @@ -0,0 +1,130 @@ +//! What a read-eval-print loop asks of the compiler: an input is a file of +//! its own with the earlier inputs opened, and the compiler says what it +//! defined and what its values look like at run time. + +mod macros_support; + +use macros_support::Project; +use rescript_compiler::repl; +use serde_json::json; + +/// Compile `input` as the next file of a session. +fn eval(project: &mut Project, input: &str) -> Result { + let name = format!("Repl{}", project.open_modules.len() + 1); + let filename = format!("{name}.res"); + let source = match repl::prepare(input, &filename) { + Some(prepared) => prepared.source, + None => input.to_string(), + }; + project.compile(&filename, &source)?; + project.open_modules.push(name); + Ok(project.signature.clone()) +} + +fn texts(signature: &serde_json::Value) -> Vec { + signature["items"] + .as_array() + .unwrap() + .iter() + .map(|item| item["text"].as_str().unwrap().to_string()) + .collect() +} + +fn session(run: impl FnOnce(&mut Project) + Send + 'static) { + // A debug build of the type checker needs more stack than a test thread + // has. + std::thread::Builder::new() + .stack_size(512 * 1024 * 1024) + .spawn(move || run(&mut Project::new())) + .unwrap() + .join() + .unwrap(); +} + +#[test] +fn an_input_sees_the_inputs_before_it() { + session(|project| { + let first = eval(project, "let x = 20").unwrap(); + assert_eq!(texts(&first), ["let x: int"]); + let second = eval(project, "x + 1").unwrap(); + assert_eq!(texts(&second), ["let it: int"]); + assert_eq!(second["items"][0]["shape"], json!({ "k": "int" })); + let third = eval(project, "it * 2").unwrap(); + assert_eq!(texts(&third), ["let it: int"]); + // A later binding of a name is the one that is seen. + eval(project, "let x = \"now a string\"").unwrap(); + let fifth = eval(project, "x").unwrap(); + assert_eq!(texts(&fifth), ["let it: string"]); + // An input that does not compile leaves the session as it was. + assert!(eval(project, "x + 1").is_err()); + }); +} + +#[test] +fn a_value_is_described_by_its_type() { + session(|project| { + let signature = eval( + project, + "type shape = Circle(float) | Square({side: float}) | @as(\"dot\") Point\n\ + type rec user = {name: string, age?: int, @as(\"best_friend\") friend: option, shape: shape}\n\ + let ada = {name: \"Ada\", friend: None, shape: Point}\n\ + let all = (Some([1]), list{Ok(1.5)}, #a(\"b\"), x => x + 1)\n", + ) + .unwrap(); + assert_eq!( + texts(&signature), + [ + "type shape = Circle(float) | Square({side: float}) | @as(\"dot\") Point", + "type rec user = {name: string, age?: int, friend: option, shape: shape}", + "let ada: user", + "let all: (\n option>,\n list>,\n [> #a(string)],\n int => int,\n)", + ] + ); + let items = signature["items"].as_array().unwrap(); + let defs = signature["defs"].as_array().unwrap(); + // The record refers to itself and to the variant by index. + let user = &defs[items[2]["shape"]["id"].as_u64().unwrap() as usize]; + assert_eq!(user["k"], "record"); + let fields = user["fields"].as_array().unwrap(); + assert_eq!( + fields[1], + json!({ "name": "age", "js": "age", "optional": true, "of": { "k": "int" } }) + ); + assert_eq!(fields[2]["js"], "best_friend"); + assert_eq!( + fields[2]["of"], + json!({ "k": "option", "of": items[2]["shape"] }) + ); + let shape = &defs[fields[3]["of"]["id"].as_u64().unwrap() as usize]; + let cases = shape["cases"].as_array().unwrap(); + assert_eq!(cases[0]["args"], json!([{ "k": "float" }])); + assert_eq!(cases[0]["tag"], json!({ "t": "string", "v": "Circle" })); + assert_eq!(cases[1]["fields"][0]["name"], "side"); + assert_eq!(cases[2]["constant"], true); + assert_eq!(cases[2]["tag"], json!({ "t": "string", "v": "dot" })); + assert_eq!( + items[3]["shape"], + json!({ "k": "tuple", "of": [ + { "k": "option", "of": { "k": "array", "of": { "k": "int" } } }, + { "k": "list", "of": { "k": "result", "ok": { "k": "float" }, "error": { "k": "other", "name": "'a" } } }, + { "k": "poly", "cases": [{ "name": "a", "of": { "k": "string" } }] }, + { "k": "fn" }, + ] }) + ); + }); +} + +#[test] +fn a_macro_of_one_input_is_used_in_the_next() { + session(|project| { + eval( + project, + "module Twice = {\n open Macro\n @macro\n let f = (e: code): code => %code(${e} + ${e})\n}", + ) + .unwrap(); + let signature = eval(project, "%Twice.f(21)").unwrap(); + assert_eq!(texts(&signature), ["let it: int"]); + let expanded = project.expanded.clone().unwrap(); + assert_eq!(expanded.matches("21").count(), 2, "{expanded}"); + }); +} From 4e57ce92e2fcd7362b82f5d53e5f40a599fb4baf 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 21:59:36 +0100 Subject: [PATCH 03/11] playground: a read-eval-print loop in the engine `engine.replStart` and `engine.replEval` keep a session: an input is the file `Repl.res`, compiled by the new `compile_input` with the files of the earlier inputs opened, and run once. What it defined is printed with its type and its value, written as the ReScript that makes it (`src/repl-format.js`, by the shape the compiler gives). An input can await at the top level, an open stays open, a diagnostic is shown for the input as it was written, and an input that raises defines nothing. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/os-01a1caab-4faf-7817-951e-2b3f9a5dae19 Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- playground/crate/src/lib.rs | 54 +++++- playground/src/compiler-worker.js | 10 + playground/src/engine.js | 197 +++++++++++++++++++- playground/src/repl-format.js | 297 ++++++++++++++++++++++++++++++ playground/src/repl-transcript.js | 53 ++++++ 5 files changed, 607 insertions(+), 4 deletions(-) create mode 100644 playground/src/repl-format.js create mode 100644 playground/src/repl-transcript.js diff --git a/playground/crate/src/lib.rs b/playground/crate/src/lib.rs index 3cf68c3973..e145775cea 100644 --- a/playground/crate/src/lib.rs +++ b/playground/crate/src/lib.rs @@ -301,10 +301,55 @@ 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, expanded_raw, formatted, warnings, parse_tree, typed_tree, raw_lambda, lambda }` +/// `{ type: "success", js, expanded, expanded_raw, formatted, warnings, signature, 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 { + compile(source, filename, is_runtime, Vec::new(), Vec::new()) +} + +/// Compile one input of a read-eval-print loop: a file of its own, with the +/// modules `open_modules` (the earlier inputs) opened. The result is the one +/// of [`compile_file`]; its `signature` is what the loop prints. +#[wasm_bindgen] +pub fn compile_input(source: &str, filename: &str, open_modules: Vec) -> String { + // An `open` is for the inputs after it: it is not unused (warning 33) + // when its own input does not use it. + compile(source, filename, false, open_modules, vec!["-33".to_string()]) +} + +/// What a read-eval-print loop compiles for an input. Returns JSON: +/// `{ type: "success", source, result_at, binding, opens }`: `source` has +/// `binding` (`let it = `) before a last expression, at the line and column +/// `result_at` (counted from one, null without such an expression), and +/// `opens` is the text of each top-level `open`. Or `{ type: "error" }` when +/// the input does not parse (compiling it gives the message). +#[wasm_bindgen] +pub fn prepare_input(source: &str, filename: &str) -> String { + match rescript_compiler::repl::prepare(&to_compiler_text(source), filename) { + Some(prepared) => serde_json::json!({ + "type": "success", + "source": from_compiler_text(&prepared.source), + "result_at": prepared.result_at.map(|(line, column)| [line, column]), + "binding": rescript_compiler::repl::BINDING, + "opens": prepared + .opens + .iter() + .map(|open| from_compiler_text(open)) + .collect::>(), + }) + .to_string(), + None => serde_json::json!({ "type": "error" }).to_string(), + } +} + +fn compile( + source: &str, + filename: &str, + is_runtime: bool, + open_modules: Vec, + warning_specs: Vec, +) -> String { let source = to_compiler_text(source); // Diagnostics show a frame of the source file. wasm_vfs::write_file(filename, source.clone()); @@ -322,6 +367,8 @@ pub fn compile_file(source: &str, filename: &str, is_runtime: bool) -> String { capture_loaded_modules: true, output_module_format: Some(ModuleFormat::EsModule), macro_host: Some(host), + open_modules, + warning_specs, ..Default::default() }; @@ -371,6 +418,11 @@ pub fn compile_file(source: &str, filename: &str, is_runtime: bool) -> String { "typed_tree": compiled.typed_tree_sexp, "raw_lambda": compiled.raw_lambda_sexp, "lambda": compiled.lambda_sexp, + // What the file defines (`repl::describe_signature`). + "signature": serde_json::from_str::( + &from_compiler_text(&compiled.signature_description), + ) + .unwrap_or(serde_json::Value::Null), }) .to_string() } diff --git a/playground/src/compiler-worker.js b/playground/src/compiler-worker.js index b1fc228607..538f42f973 100644 --- a/playground/src/compiler-worker.js +++ b/playground/src/compiler-worker.js @@ -21,6 +21,16 @@ self.onmessage = async (event) => { const started = performance.now(); const result = engine.build(message.files); self.postMessage({ type: "built", id: message.id, result, ms: performance.now() - started }); + } else if (message.type === "repl-start") { + // A session of the read-eval-print loop: `libraries` are the modules + // it starts with, `replay` inputs that are evaluated without a word. + const started = engine.replStart(message.libraries, (line) => self.postMessage({ type: "repl-log", line })); + for (const source of message.replay ?? []) await engine.replEval(source); + self.postMessage({ type: "repl-started", id: message.id, ...started }); + } else if (message.type === "repl-eval") { + const started = performance.now(); + const result = await engine.replEval(message.source); + self.postMessage({ type: "repl-result", 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 index efa263cbd6..9eb8feb677 100644 --- a/playground/src/engine.js +++ b/playground/src/engine.js @@ -7,6 +7,8 @@ * in the Node smoke test (scripts/smoke.mjs). */ +import { formatException, formatValue, hideModules } from "./repl-format.js"; + export function moduleNameOf(filename) { const base = filename.split("/").pop(); const dot = base.lastIndexOf("."); @@ -145,7 +147,7 @@ export function createEngine(wasm, stdlib) { * expanded, warnings, ...}`, `{type: "error", message}` or `{type: * "skipped", message}`; `logs` is null when a file did not compile. */ - function build(files) { + function build(files, { execute = true } = {}) { // Start from nothing: a module of the previous build must not be visible. for (const file of projectFiles) { const name = moduleNameOf(file.name); @@ -198,7 +200,196 @@ export function createEngine(wasm, stdlib) { } results[name] = result; } - return { order, results, logs: ok ? run(order) : null }; + return { order, results, logs: ok && execute ? run(order) : null }; + } + + // ── The read-eval-print loop ────────────────────────────────────────────── + // + // An input is compiled as a file of its own, `Repl.res`, with the files + // of the earlier inputs opened, and its JavaScript is run once: what an + // input defined, and what it did, stays. + + let session = null; + const asyncFunction = Object.getPrototypeOf(async () => {}).constructor; + const inputModules = /\bRepl\d+(_open\d+)?\./g; + const hideInputModules = (text) => text.replace(inputModules, ""); + hideModules(inputModules); + + /** + * Start a session with the modules of `libraries` (`[{name, source}]`) + * available. `onLog` gets what the program prints after its input has + * finished (a timer, a promise). Returns `{modules, problems}`. + */ + function replStart(libraries, onLog = () => {}) { + const { order, results } = build(libraries, { execute: false }); + session = { + count: 0, + // What every input opens: earlier inputs, and the modules they opened. + opens: [], + // The modules an input defined: `open` of one is not `open` of a file. + defined: new Set(), + loaded: Object.create(null), + onLog, + }; + return { + modules: order.filter((name) => results[name].type === "success").map(moduleNameOf), + problems: order + .filter((name) => results[name].type !== "success") + .map((name) => ({ file: name, message: results[name].message })), + }; + } + + function replLoad(name, console) { + const loaded = session.loaded; + 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 session.`); + const module = { exports: {} }; + loaded[name] = module; + try { + new Function("require", "exports", "module", "console", toCommonJs(source))( + (specifier) => replLoad(moduleNameOf(specifier), console), + module.exports, + module, + console, + ); + } catch (error) { + delete loaded[name]; + throw error; + } + return module.exports; + } + + /** + * A diagnostic of an input as the input was written: without the name of + * its file, and without the binding of its last expression (`prepared`, + * of `prepare_input`), which moved what is after it on that line. + */ + function replDiagnostic(message, filename, prepared) { + const [line, column] = prepared.result_at ?? [0, 0]; + const width = prepared.binding?.length ?? 0; + const moved = (at, col) => (Number(at) === line && Number(col) >= column ? Math.max(column, Number(col) - width) : col); + const escaped = filename.replace(/[.]/g, "\\."); + let text = message.replace( + new RegExp(`${escaped}:(\\d+):(\\d+)(?:-(\\d+)(?::(\\d+))?)?`, "g"), + (_, startLine, startColumn, end, endColumn) => { + let out = `${startLine}:${moved(startLine, startColumn)}`; + // `l:c-c2` ends on the same line, `l:c-l2:c2` on another one. + if (endColumn !== undefined) out += `-${end}:${moved(end, endColumn)}`; + else if (end !== undefined) out += `-${moved(startLine, end)}`; + return `input:${out}`; + }, + ); + if (line > 0) { + // The line of the binding in a frame of the source: ` 2 │ let it = x`. + text = text.replace(new RegExp(`^(\\s*${line} [│|] .{${column - 1}})${prepared.binding}`, "gm"), "$1"); + } + return text; + } + + /** Keep `open Path` of an input open for the inputs after it. */ + function replKeepOpen(text, input, console) { + const path = text.replace(/^open!?\s*/, "").trim(); + const root = path.split(".")[0]; + const isFile = !session.defined.has(root) && (stdlibModules.has(root) || projectJs[root] !== undefined); + if (isFile && path === root) { + session.opens.push(path); + return null; + } + // Anything else is opened by a file that includes it. + const name = `${input}_open${session.opens.length}`; + const result = JSON.parse(wasm.compile_input(`include ${path}`, `${name}.res`, session.opens)); + if (result.type !== "success") return `\`${text}\` is not kept open for the inputs after this one.`; + projectJs[name] = result.js; + replLoad(name, console); + session.opens.push(name); + return null; + } + + /** + * Compile and run one input. Returns `{output, expanded, javascript}`: + * `output` is a list of `{kind, text}` with kind `value` (a definition, + * with its value when it has one), `log`, `warn`, `error` (printed by the + * program), `problem` (it does not compile, or it raised) or `note`. + */ + async function replEval(source) { + if (!session) replStart([]); + const current = session; + current.count += 1; + const name = `Repl${current.count}`; + const filename = `${name}.res`; + const output = []; + + const prepared = JSON.parse(wasm.prepare_input(source, filename)); + const text = prepared.type === "success" ? prepared.source : source; + let result; + try { + result = JSON.parse(wasm.compile_input(text, filename, current.opens)); + } catch (error) { + // A panic in the compiler: the wasm instance is unusable from here. + return { output, crashed: `The compiler crashed: ${show(error)}` }; + } + const diagnostic = (message) => + replDiagnostic(stripAnsi(message || "").trim(), filename, prepared.type === "success" ? prepared : {}); + if (result.type !== "success") { + output.push({ kind: "problem", text: diagnostic(result.message) }); + return { output }; + } + projectJs[name] = result.js; + + let finished = false; + const log = (kind) => (...values) => { + const line = { kind, text: values.map((value) => show(value)).join(" ") }; + if (finished) current.onLog(line); + else output.push(line); + }; + const console = { log: log("log"), info: log("log"), debug: log("log"), warn: log("warn"), error: log("error") }; + const module = { exports: {} }; + try { + // An input can `await` at the top level. + await new asyncFunction("require", "exports", "module", "console", toCommonJs(result.js))( + (specifier) => replLoad(moduleNameOf(specifier), console), + module.exports, + module, + console, + ); + } catch (error) { + finished = true; + // What it defined before it raised is not kept: part of it is missing. + wasm.forget_module(name); + delete projectJs[name]; + output.push({ kind: "problem", text: `Uncaught ${formatException(error)}` }); + return { output, expanded: result.expanded ?? null, javascript: result.js }; + } + finished = true; + current.loaded[name] = module; + current.opens.push(name); + + const warnings = diagnostic(result.warnings); + if (warnings) output.push({ kind: "warn", text: warnings }); + const { items = [], defs = [] } = result.signature ?? {}; + for (const item of items) { + const declaration = hideInputModules(item.text).replace(/^type exn \+=\s+/, "exception "); + if (item.kind === "module") current.defined.add(item.name); + if (item.kind !== "value" || declaration.startsWith("external ") || !(item.name in module.exports)) { + output.push({ kind: "value", text: declaration }); + continue; + } + // `let it: int` of an expression is written `- : int`. + const head = + item.name === "it" && prepared.result_at ? declaration.replace(/^let it: ?/, "- : ") : declaration; + const last = head.split("\n").pop(); + const value = formatValue(module.exports[item.name], item.shape, defs, 0); + // A value that does not fit after the type starts a line of its own. + const joined = + last.length + 3 + value.split("\n")[0].length <= 80 ? `${head} = ${value}` : `${head} =\n ${formatValue(module.exports[item.name], item.shape, defs, 2)}`; + output.push({ kind: "value", text: joined }); + } + for (const open of prepared.opens ?? []) { + const note = replKeepOpen(open, name, console); + if (note) output.push({ kind: "note", text: note }); + } + return { output, expanded: result.expanded ?? null, javascript: result.js }; } /** @@ -220,5 +411,5 @@ export function createEngine(wasm, stdlib) { build([]); } - return { build, warm }; + return { build, warm, replStart, replEval }; } diff --git a/playground/src/repl-format.js b/playground/src/repl-format.js new file mode 100644 index 0000000000..7cc561e2ad --- /dev/null +++ b/playground/src/repl-format.js @@ -0,0 +1,297 @@ +/** + * A JavaScript value as the ReScript that makes it. + * + * At run time `Some(3)` is `3`, `Red` is `"Red"` and `Circle(1.)` an object + * tagged `TAG`, so the value alone does not say what it is. The compiler + * gives the shape of the value's type (`signature` of a compilation, see + * `repl::describe_signature` in the compiler): `shape` is the type one level + * deep, `defs` the records and variants it refers to with `{k: "ref", id}`. + */ + +const WIDTH = 80; +const MAX_DEPTH = 24; +const MAX_ITEMS = 100; + +/** `value` as source text, broken over lines when it is wider than a line. */ +export function formatValue(value, shape, defs, indent = 0) { + return render(describe(value, shape, defs, 0), indent); +} + +// A value is text, or a group `open item, item close` that is written on one +// line when it fits. +function group(open, items, close) { + return { open, items, close }; +} + +function flat(node) { + if (typeof node === "string") return node; + return node.open + node.items.map(flat).join(", ") + node.close; +} + +function render(node, indent) { + if (typeof node === "string") return node; + const line = flat(node); + if (indent + line.length <= WIDTH || node.items.length === 0) return line; + const inner = " ".repeat(indent + 2); + const items = node.items.map((item) => `${inner}${render(item, indent + 2)},\n`); + return `${node.open}\n${items.join("")}${" ".repeat(indent)}${node.close}`; +} + +/** `key: value`, where the value may be a group. */ +function entry(key, node) { + if (typeof node === "string") return `${key}: ${node}`; + return { ...node, open: `${key}: ${node.open}` }; +} + +/** `Name(arguments)`. */ +function apply(name, nodes) { + if (nodes.length === 0) return name; + // `Some({...})` reads better than a record on a line of its own. + if (nodes.length === 1 && typeof nodes[0] !== "string") { + return { ...nodes[0], open: `${name}(${nodes[0].open}`, close: `${nodes[0].close})` }; + } + return group(`${name}(`, nodes, ")"); +} + +function limited(values, each) { + const nodes = values.slice(0, MAX_ITEMS).map(each); + if (values.length > MAX_ITEMS) nodes.push(`… ${values.length - MAX_ITEMS} more`); + return nodes; +} + +function float(value) { + if (Number.isInteger(value)) return Object.is(value, -0) ? "-0." : `${value}.`; + if (Number.isNaN(value)) return "nan"; + if (value === Infinity) return "infinity"; + if (value === -Infinity) return "neg_infinity"; + return String(value); +} + +function describe(value, shape, defs, depth) { + if (depth > MAX_DEPTH) return "…"; + const next = (inner, of) => describe(inner, of, defs, depth + 1); + switch (shape?.k) { + case "int": + return typeof value === "number" ? String(value) : javascript(value, depth); + case "float": + return typeof value === "number" ? float(value) : javascript(value, depth); + case "string": + return typeof value === "string" ? JSON.stringify(value) : javascript(value, depth); + case "bool": + return String(value); + case "unit": + return "()"; + case "bigint": + return typeof value === "bigint" ? `${value}n` : javascript(value, depth); + case "char": + return typeof value === "number" ? `'${String.fromCodePoint(value)}'` : javascript(value, depth); + case "fn": + return ""; + case "promise": + return ""; + case "option": { + if (value === undefined) return "None"; + // `Some(None)` cannot be `undefined`: it is an object that counts the + // options around the `None`. + const nested = value !== null && typeof value === "object" ? value.BS_PRIVATE_NESTED_SOME_NONE : undefined; + if (nested !== undefined) { + return apply("Some", [next(nested === 0 ? undefined : { BS_PRIVATE_NESTED_SOME_NONE: nested - 1 }, shape.of)]); + } + return apply("Some", [next(value, shape.of)]); + } + case "array": + if (!Array.isArray(value)) return javascript(value, depth); + return group("[", limited(value, (item) => next(item, shape.of)), "]"); + case "tuple": + if (!Array.isArray(value)) return javascript(value, depth); + return group("(", shape.of.map((of, index) => next(value[index], of)), ")"); + case "list": { + const items = []; + let cell = value; + while (cell !== null && typeof cell === "object" && "hd" in cell && items.length <= MAX_ITEMS) { + items.push(cell.hd); + cell = cell.tl; + } + return group("list{", limited(items, (item) => next(item, shape.of)), "}"); + } + case "dict": { + if (value === null || typeof value !== "object") return javascript(value, depth); + const keys = Object.keys(value); + return group("dict{", limited(keys, (key) => entry(JSON.stringify(key), next(value[key], shape.of))), "}"); + } + case "result": { + if (value === null || typeof value !== "object") return javascript(value, depth); + return value.TAG === "Ok" ? apply("Ok", [next(value._0, shape.ok)]) : apply("Error", [next(value._0, shape.error)]); + } + case "poly": { + if (value !== null && typeof value === "object" && "NAME" in value) { + const found = shape.cases.find((candidate) => candidate.name === String(value.NAME)); + return apply(`#${polyName(value.NAME)}`, [next(value.VAL, found?.of ?? null)]); + } + return `#${polyName(value)}`; + } + case "ref": + return declared(value, defs[shape.id], defs, depth); + default: + // A lazy value is an object that says whether it has run. + if (value !== null && typeof value === "object" && "LAZY_DONE" in value) return ""; + return javascript(value, depth); + } +} + +function polyName(name) { + const text = String(name); + return /^[A-Za-z_][A-Za-z0-9_']*$|^[0-9]+$/.test(text) ? text : JSON.stringify(text); +} + +function fields(value, list, defs, depth) { + const nodes = []; + for (const field of list) { + const item = value[field.js]; + if (field.optional && item === undefined) continue; + nodes.push(entry(field.name, describe(item, field.of, defs, depth + 1))); + } + return group("{", nodes, "}"); +} + +function isLiteral(value, tag) { + switch (tag.t) { + case "null": + return value === null; + case "undefined": + return value === undefined; + case "bigint": + return typeof value === "bigint" && String(value) === tag.v; + default: + return typeof value === tag.t && value === tag.v; + } +} + +/** Whether a value can be the payload of a constructor without a tag. */ +function fits(value, shape, defs) { + const kind = shape?.k === "ref" ? defs[shape.id]?.k : shape?.k; + switch (kind) { + case "int": + case "float": + return typeof value === "number"; + case "string": + return typeof value === "string"; + case "bool": + return typeof value === "boolean"; + case "bigint": + return typeof value === "bigint"; + case "array": + case "tuple": + return Array.isArray(value); + case "fn": + return typeof value === "function"; + case "record": + case "dict": + return value !== null && typeof value === "object" && !Array.isArray(value); + default: + return true; + } +} + +function declared(value, def, defs, depth) { + if (!def) return javascript(value, depth); + if (def.k === "record") { + // An unboxed record is its one field. + if (def.unboxed && def.fields.length === 1) { + return group("{", [entry(def.fields[0].name, describe(value, def.fields[0].of, defs, depth + 1))], "}"); + } + if (value === null || typeof value !== "object") return javascript(value, depth); + return fields(value, def.fields, defs, depth); + } + const payload = (found, object) => { + if (found.fields) return apply(found.name, [fields(object, found.fields, defs, depth)]); + return apply(found.name, found.args.map((of, index) => describe(object[`_${index}`], of, defs, depth + 1))); + }; + const constant = def.cases.find((candidate) => candidate.constant && isLiteral(value, candidate.tag)); + if (constant) return constant.name; + if (value !== null && typeof value === "object") { + const tagged = def.cases.find( + (candidate) => !candidate.constant && !candidate.untagged && isLiteral(value[candidate.tagName], candidate.tag), + ); + if (tagged) return payload(tagged, value); + } + // A constructor without a tag is its payload: the first one it can be. + const untagged = def.cases.filter((candidate) => candidate.untagged); + const found = + untagged.find((candidate) => + candidate.fields ? value !== null && typeof value === "object" : fits(value, candidate.args[0], defs), + ) ?? untagged[0]; + if (!found) return javascript(value, depth); + if (found.fields) return apply(found.name, [fields(value, found.fields, defs, depth)]); + return apply(found.name, [describe(value, found.args[0], defs, depth + 1)]); +} + +/** + * A value whose type says nothing about its representation (an abstract + * type, a type variable, a JavaScript object), as JavaScript. + */ +function javascript(value, depth) { + if (depth > MAX_DEPTH) return "…"; + if (value === undefined) return "undefined"; + if (value === null) return "null"; + switch (typeof value) { + case "string": + return JSON.stringify(value); + case "bigint": + return `${value}n`; + case "function": + return ""; + case "symbol": + return value.toString(); + case "object": + break; + default: + return String(value); + } + const next = (inner) => javascript(inner, depth + 1); + if (Array.isArray(value)) return group("[", limited(value, next), "]"); + if (value instanceof Date) return Number.isNaN(value.getTime()) ? "Date(invalid)" : `Date(${value.toISOString()})`; + if (value instanceof RegExp) return String(value); + if (value instanceof Error) return `${value.name}(${JSON.stringify(value.message)})`; + if (value instanceof Promise) return ""; + if (value instanceof Map) { + return group("Map{", limited([...value.entries()], ([key, item]) => entry(flat(next(key)), next(item))), "}"); + } + if (value instanceof Set) return group("Set{", limited([...value.values()], next), "}"); + // An exception of ReScript. + if (typeof value.RE_EXN_ID === "string") { + const args = Object.keys(value) + .filter((key) => /^_\d+$/.test(key)) + .map((key) => next(value[key])); + return apply(exceptionName(value.RE_EXN_ID), args); + } + const keys = Object.keys(value); + return group("{", limited(keys, (key) => entry(/^[A-Za-z_$][\w$]*$/.test(key) ? key : JSON.stringify(key), next(value[key]))), "}"); +} + +/** `Module.Name/3` is `Name` of a module that is opened, or of this file. */ +function exceptionName(id) { + const name = id.replace(/\/\d+$/, ""); + return hiddenModules ? name.replace(hiddenModules, "") : name; +} + +let hiddenModules = null; + +/** + * Leave the modules whose name matches `pattern` (a prefix with its dot) + * out of the names of exceptions: the files of a read-eval-print loop. + */ +export function hideModules(pattern) { + hiddenModules = pattern; +} + +/** What was raised, for the line under an input that failed. */ +export function formatException(error) { + if (error !== null && typeof error === "object" && typeof error.RE_EXN_ID === "string") { + // `throw` of a JavaScript error is wrapped. + if (error.RE_EXN_ID === "JsExn" && error._1 !== undefined) return formatException(error._1); + return flat(javascript(error, 0)); + } + if (error instanceof Error) return `${error.name}: ${error.message}`; + return flat(javascript(error, 0)); +} diff --git a/playground/src/repl-transcript.js b/playground/src/repl-transcript.js new file mode 100644 index 0000000000..1b78ee1516 --- /dev/null +++ b/playground/src/repl-transcript.js @@ -0,0 +1,53 @@ +/** + * A session of the read-eval-print loop as text, the way a terminal shows + * it: `> ` before an input, `. ` before its other lines, and what the loop + * answered below. docs/comptime/README.md shows the opening session of the + * page like this, and scripts/smoke.mjs checks that it is what the loop says. + */ + +/** The modules a session starts with: every file of the examples but their programs. */ +export function sessionLibraries(examples) { + const seen = new Set(); + const libraries = []; + for (const example of examples) { + for (const file of example.files) { + if (file.name === "Main.res" || seen.has(file.name)) continue; + seen.add(file.name); + libraries.push(file); + } + } + return libraries; +} + +export function transcriptOf(entries) { + return entries + .map((entry) => { + const input = entry.input + .split("\n") + .map((line, index) => `${index === 0 ? ">" : "."} ${line}`.trimEnd()) + .join("\n"); + const output = entry.output.map((line) => line.text).join("\n"); + return output ? `${input}\n${output}` : input; + }) + .join("\n\n"); +} + +/** Evaluate `inputs` in a new session of `engine`. */ +export async function runSession(engine, libraries, inputs) { + const started = engine.replStart(libraries); + if (started.problems.length > 0) { + throw new Error(started.problems.map((problem) => `${problem.file}:\n${problem.message}`).join("\n\n")); + } + const entries = []; + for (const input of inputs) { + const result = await engine.replEval(input); + if (result.crashed) throw new Error(result.crashed); + entries.push({ + input, + output: result.output, + expanded: result.expanded ?? null, + javascript: result.javascript ?? null, + }); + } + return entries; +} From ca0d3ee269058aa29e1024fb8c89b3d72fb383f7 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 21:59:36 +0100 Subject: [PATCH 04/11] site: a read-eval-print loop on the RFC page The block between `` and `` of the RFC is a session: Enter runs an input (or continues one that is not finished), the arrows walk the earlier inputs, and each answer can show the expansion and the JavaScript of its input. The macro modules of the examples and the standard library are loaded. It opens with a session that was run when the site was built (`examples/repl.json`), so the page reads without the compiler; the compiler runs that session again when it is loaded. The loop has a worker of its own: an input that does not end is stopped after 20 seconds without stopping the examples. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/os-01a1caab-4faf-7817-951e-2b3f9a5dae19 Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- playground/examples/repl.json | 38 +++ playground/scripts/prebuild-examples.mjs | 12 +- playground/src/rfc/Markdown.jsx | 11 +- playground/src/rfc/Page.jsx | 9 + playground/src/rfc/Repl.jsx | 406 +++++++++++++++++++++++ playground/src/rfc/repl-session.js | 106 ++++++ playground/src/rfc/rfc.css | 248 ++++++++++++++ 7 files changed, 825 insertions(+), 5 deletions(-) create mode 100644 playground/examples/repl.json create mode 100644 playground/src/rfc/Repl.jsx create mode 100644 playground/src/rfc/repl-session.js diff --git a/playground/examples/repl.json b/playground/examples/repl.json new file mode 100644 index 0000000000..580dfc62c2 --- /dev/null +++ b/playground/examples/repl.json @@ -0,0 +1,38 @@ +{ + "intro": [ + "let price = 12.5 and quantity = 3", + "%Debug.log(price *. Int.toFloat(quantity))", + "type user = {name: string, age: int, email?: string}", + "Json.encode({name: \"Ada\", age: 36})" + ], + "tries": [ + { + "label": "the last value", + "source": "it" + }, + { + "label": "a derive", + "source": "@Enum.derive\ntype size = Small | Medium | Large" + }, + { + "label": "use the derive", + "source": "sizeValues->Array.map(sizeToString)" + }, + { + "label": "a staged power", + "source": "let cube = x => Power.pow(x, 3)\ncube(1.5)" + }, + { + "label": "%Macro.eval", + "source": "%Macro.eval(Sieve.primesBelow(40))" + }, + { + "label": "write a macro", + "source": "module Twice = {\n open Macro\n\n @macro\n let run = (e: code<'a>): code<('a, 'a)> => %code((${e}, ${e}))\n}" + }, + { + "label": "use the macro", + "source": "%Twice.run(Math.sqrt(price))" + } + ] +} diff --git a/playground/scripts/prebuild-examples.mjs b/playground/scripts/prebuild-examples.mjs index 2e78c568eb..b428fbc252 100644 --- a/playground/scripts/prebuild-examples.mjs +++ b/playground/scripts/prebuild-examples.mjs @@ -2,12 +2,14 @@ /** * 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. + * source and the JavaScript, and the program's output; and the session the + * read-eval-print loop opens with. */ 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"; +import { runSession, sessionLibraries } from "../src/repl-transcript.js"; const root = join(import.meta.dirname, ".."); wasm.initSync({ module: await readFile(join(root, "crate/pkg/rescript_playground_wasm_bg.wasm")) }); @@ -15,11 +17,13 @@ const stdlib = JSON.parse(await readFile(join(root, "public/stdlib.json"), "utf- const engine = createEngine(wasm, stdlib); const prebuilt = {}; +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 { order, results, logs } = engine.build(files); const failed = order.find((name) => results[name]?.type !== "success"); if (failed || logs === null) { @@ -43,5 +47,9 @@ for (const example of JSON.parse(await readFile(join(root, "examples/index.json" ), }; } +// The session the read-eval-print loop of the page opens with. +const session = JSON.parse(await readFile(join(root, "examples/repl.json"), "utf-8")); +prebuilt.$repl = await runSession(engine, sessionLibraries(examples), session.intro); + await writeFile(join(root, "src/rfc/prebuilt.json"), JSON.stringify(prebuilt)); -console.log(`Prebuilt ${Object.keys(prebuilt).length} examples -> src/rfc/prebuilt.json`); +console.log(`Prebuilt ${examples.length} examples and the session -> src/rfc/prebuilt.json`); diff --git a/playground/src/rfc/Markdown.jsx b/playground/src/rfc/Markdown.jsx index 5e5f31d324..20db51bb07 100644 --- a/playground/src/rfc/Markdown.jsx +++ b/playground/src/rfc/Markdown.jsx @@ -141,15 +141,20 @@ function block(token, index, links) { * 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. + * `` is replaced by a chart of the table in between; + * `` up to `` by the read-eval-print loop, whose + * opening session is the transcript in between. */ export function segments(markdown) { const out = []; - const marker = /[\s\S]*?|[\s\S]*?/g; + const marker = + /[\s\S]*?|[\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] }); + if (match[1]) out.push({ type: "example", id: match[1] }); + else if (match[2]) out.push({ type: "chart", id: match[2] }); + else out.push({ type: "repl" }); position = match.index + match[0].length; } if (position < markdown.length) out.push({ type: "markdown", text: markdown.slice(position) }); diff --git a/playground/src/rfc/Page.jsx b/playground/src/rfc/Page.jsx index 3175bb89d8..f08f0c4a53 100644 --- a/playground/src/rfc/Page.jsx +++ b/playground/src/rfc/Page.jsx @@ -1,13 +1,19 @@ import React, { useEffect, useMemo, useState } from "react"; import { examples } from "../examples.js"; import prebuilt from "./prebuilt.json"; +import session from "../../examples/repl.json"; +import { sessionLibraries } from "../repl-transcript.js"; import { Example } from "./Example.jsx"; +import { Repl } from "./Repl.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"; +// The modules a session of the read-eval-print loop starts with. +const libraries = sessionLibraries(examples); + function useTheme() { const [theme, setTheme] = useState(() => localStorage.getItem("theme") ?? "auto"); useEffect(() => { @@ -138,6 +144,9 @@ export function Page({ markdown, title, lede, pages, current }) { {parts.map((part, index) => { if (part.type === "markdown") return ; if (part.type === "chart") return ; + if (part.type === "repl") { + return ; + } const example = examples.find((candidate) => candidate.id === part.id); if (!example) return null; return ; diff --git a/playground/src/rfc/Repl.jsx b/playground/src/rfc/Repl.jsx new file mode 100644 index 0000000000..090525cb7c --- /dev/null +++ b/playground/src/rfc/Repl.jsx @@ -0,0 +1,406 @@ +import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { EditorState, Prec } from "@codemirror/state"; +import { EditorView, drawSelection, highlightSpecialChars, keymap, placeholder } from "@codemirror/view"; +import { defaultKeymap, history, historyKeymap } from "@codemirror/commands"; +import { bracketMatching, indentUnit, syntaxHighlighting } from "@codemirror/language"; +import { classHighlighter } from "@lezer/highlight"; +import { codemirrorLanguage, highlight } from "./highlight.jsx"; +import { createSession } from "./repl-session.js"; + +/** + * How many brackets `text` leaves open, or null when it ends inside a + * string or a comment. + */ +function openBrackets(text) { + let depth = 0; + let index = 0; + while (index < text.length) { + const char = text[index]; + const two = text.slice(index, index + 2); + if (two === "//") { + const end = text.indexOf("\n", index); + index = end < 0 ? text.length : end; + } else if (two === "/*") { + let open = 1; + index += 2; + while (index < text.length && open > 0) { + if (text.startsWith("/*", index)) (open += 1), (index += 2); + else if (text.startsWith("*/", index)) (open -= 1), (index += 2); + else index += 1; + } + if (open > 0) return null; + } else if (char === '"' || char === "`") { + index += 1; + while (index < text.length && text[index] !== char) index += text[index] === "\\" ? 2 : 1; + if (index >= text.length) return null; + index += 1; + } else { + if ("([{".includes(char)) depth += 1; + else if (")]}".includes(char)) depth -= 1; + index += 1; + } + } + return depth; +} + +/** + * Whether Enter ends an input: its brackets, strings and comments are + * closed, and it does not end in something that needs what follows (an + * operator, an attribute). + */ +export function isComplete(text) { + const depth = openBrackets(text); + if (depth === null || depth > 0) return false; + const end = text.replace(/\/\/[^\n]*$/, ""); + if (/(=>|->|[=|,+\-*/:]|&&|\|\|)\s*$/.test(end)) return false; + return !/(^|\n)\s*@@?[A-Za-z_][\w.]*(\([^()]*\))?\s*$/.test(end); +} + +function Source({ code }) { + const nodes = useMemo(() => highlight(code, "rescript"), [code]); + return {nodes}; +} + +/** The input line: an editor where Enter evaluates and the arrows walk the history. */ +function Prompt({ onSubmit, past, viewRef, onFocus }) { + const host = useRef(null); + const state = useRef({ onSubmit, past, onFocus }); + state.current = { onSubmit, past, onFocus }; + // Where in the history the arrows are, and what was typed before them. + const walk = useRef({ at: null, draft: "" }); + + useEffect(() => { + const replace = (view, text) => { + view.dispatch({ + changes: { from: 0, to: view.state.doc.length, insert: text }, + selection: { anchor: text.length }, + scrollIntoView: true, + }); + }; + // A new line starts two spaces in for every bracket that is open. + const newline = (view) => { + const { from, to } = view.state.selection.main; + const depth = openBrackets(view.state.sliceDoc(0, from)) ?? 0; + const insert = `\n${" ".repeat(Math.max(0, depth))}`; + view.dispatch({ + changes: { from, to, insert }, + selection: { anchor: from + insert.length }, + scrollIntoView: true, + userEvent: "input", + }); + return true; + }; + const submit = (view, always) => { + const text = view.state.doc.toString(); + if (text.trim() === "") return true; + if (!always && !isComplete(text)) return newline(view); + walk.current = { at: null, draft: "" }; + state.current.onSubmit(text.replace(/\s+$/, "")); + replace(view, ""); + return true; + }; + // A closing bracket that starts a line goes back to where its line opened. + const closing = EditorView.inputHandler.of((view, from, to, text) => { + if (text.length !== 1 || !")]}".includes(text)) return false; + const line = view.state.doc.lineAt(from); + if (view.state.sliceDoc(line.from, from).trim() !== "") return false; + const depth = openBrackets(view.state.sliceDoc(0, line.from)); + if (depth === null) return false; + const insert = " ".repeat(Math.max(0, depth - 1)) + text; + view.dispatch({ + changes: { from: line.from, to, insert }, + selection: { anchor: line.from + insert.length }, + userEvent: "input.type", + }); + return true; + }); + const older = (view) => { + const { past } = state.current; + const head = view.state.selection.main.head; + if (view.state.doc.lineAt(head).number !== 1 || past.length === 0) return false; + const at = walk.current.at === null ? past.length - 1 : walk.current.at - 1; + if (at < 0) return true; + if (walk.current.at === null) walk.current.draft = view.state.doc.toString(); + walk.current.at = at; + replace(view, past[at]); + return true; + }; + const newer = (view) => { + const { past } = state.current; + const head = view.state.selection.main.head; + if (walk.current.at === null || view.state.doc.lineAt(head).number !== view.state.doc.lines) return false; + const at = walk.current.at + 1; + walk.current.at = at >= past.length ? null : at; + replace(view, at >= past.length ? walk.current.draft : past[at]); + return true; + }; + const view = new EditorView({ + parent: host.current, + state: EditorState.create({ + doc: "", + extensions: [ + highlightSpecialChars(), + history(), + drawSelection(), + bracketMatching(), + closing, + indentUnit.of(" "), + EditorState.tabSize.of(2), + syntaxHighlighting(classHighlighter), + codemirrorLanguage("rescript"), + placeholder("Type ReScript and press Enter"), + Prec.highest( + keymap.of([ + { key: "Enter", run: (target) => submit(target, false), shift: newline }, + { key: "Mod-Enter", run: (target) => submit(target, true) }, + { key: "ArrowUp", run: older }, + { key: "ArrowDown", run: newer }, + ]), + ), + keymap.of([...defaultKeymap, ...historyKeymap]), + EditorView.updateListener.of((update) => { + if (update.focusChanged && update.view.hasFocus) state.current.onFocus?.(); + }), + EditorView.contentAttributes.of({ + "aria-label": "An input for the ReScript session", + spellcheck: "false", + autocapitalize: "off", + autocorrect: "off", + }), + ], + }), + }); + viewRef.current = { view, replace: (text) => replace(view, text), submit: () => submit(view, true) }; + return () => { + viewRef.current = null; + view.destroy(); + }; + }, [viewRef]); + + return
; +} + +function Entry({ entry }) { + const [open, setOpen] = useState(null); + const lines = entry.input === null ? [] : entry.input.split("\n"); + return ( +
+ {entry.input !== null && ( +
+          {lines.map((line, index) => (
+            
+              
+              
+            
+          ))}
+        
+ )} + {entry.pending &&
…
} + {entry.output.map((line, index) => + line.kind === "value" ? ( +
+            
+          
+ ) : ( +
+            {line.text}
+          
+ ), + )} + {(entry.expanded || entry.javascript) && ( +
+ {entry.expanded && ( + + )} + {entry.javascript && ( + + )} +
+ )} + {open === "expanded" && ( +
+          
+        
+ )} + {open === "javascript" && ( +
+          {highlight(programOf(entry.javascript), "javascript")}
+        
+ )} +
+ ); +} + +/** The JavaScript of an input without the header every file has. */ +function programOf(javascript) { + return javascript.replace(/^\/\/ Generated by ReScript[^\n]*\n+/, "").trim(); +} + +/** + * A read-eval-print loop. `intro` is a session that was run when the page + * was built: it is what the loop shows first, and the compiler runs it again + * (without a word) when it is loaded, so that its definitions are there. + * + * @param libraries `[{name, source}]`: the modules every session starts with + * @param intro `[{input, output, expanded, javascript}]` + * @param tries `[{label, source}]`: inputs offered below the loop + */ +export function Repl({ libraries, intro, tries }) { + const [entries, setEntries] = useState(intro); + const [busy, setBusy] = useState(false); + const [status, setStatus] = useState("idle"); + const [note, setNote] = useState(null); + const [tried, setTried] = useState(0); + const screen = useRef(null); + const prompt = useRef(null); + const nextKey = useRef(intro.length); + const session = useRef(null); + const queue = useRef(Promise.resolve()); + + const append = useCallback((entry) => { + setEntries((current) => current.concat({ ...entry, key: nextKey.current++, fresh: true })); + }, []); + + if (session.current === null) { + session.current = createSession({ + libraries, + replay: intro.map((entry) => entry.input), + onStatus: setStatus, + // What a timer or a promise of an earlier input prints. + onLog: (line) => append({ input: null, output: [line] }), + }); + } + useEffect(() => () => session.current.dispose(), []); + + // Keep the last line in view. + useEffect(() => { + const element = screen.current; + if (element && entries !== intro) element.scrollTop = element.scrollHeight; + }, [entries, intro]); + + const evaluate = useCallback((source) => { + const key = nextKey.current++; + setEntries((current) => current.concat({ key, input: source, output: [], pending: true, fresh: true })); + setBusy(true); + const finish = (result) => { + setEntries((current) => current.map((entry) => (entry.key === key ? { ...entry, ...result, pending: false } : entry))); + }; + // One input at a time, in the order they were entered. + queue.current = queue.current.then(() => + session.current + .evaluate(source) + .then((result) => { + finish(result); + setNote(`Compiled and run in ${Math.max(1, Math.round(result.ms))} ms, in your browser.`); + }) + .catch((error) => { + finish({ + output: [ + { kind: "problem", text: error.message }, + { kind: "note", text: "The session starts again: what it had defined is gone." }, + ], + }); + setNote(null); + }) + .finally(() => setBusy(false)), + ); + }, []); + + const reset = () => { + session.current.reset(); + queue.current = Promise.resolve(); + setEntries(intro); + setBusy(false); + setNote(null); + setTried(0); + prompt.current?.replace(""); + }; + + const past = useMemo(() => entries.filter((entry) => entry.input !== null).map((entry) => entry.input), [entries]); + const warmUp = () => session.current.warmUp(); + const next = tries[tried] ?? null; + + let foot = "The compiler is loaded when you start typing."; + if (status === "loading") foot = "Loading the compiler…"; + else if (status === "failed") foot = "The compiler could not be loaded."; + else if (busy) foot = "Running…"; + else if (note) foot = note; + else if (status === "ready") foot = "Ready."; + + return ( +
+
+
+ REPL + A session + Every input is compiled and run. What it defines stays for the next one. +
+
+ {entries !== intro && ( + + )} +
+
+ +
{ + // A click on the empty part of the screen is a click on the input. + if (event.target === event.currentTarget || event.target.classList.contains("repl-input")) prompt.current?.view.focus(); + }} + > + {entries.map((entry, index) => ( + + ))} +
+ + + +
+
+ +
+ Loaded + + {libraries + .filter((file) => file.name.endsWith(".res")) + .map((file) => file.name.replace(/\.res$/, "")) + .join(" · ")} + + {next && ( + + )} +
+ +
+ + {foot} + + Enter runs, or continues an open bracket · Shift+Enter new line · ↑ earlier inputs + +
+
+ ); +} diff --git a/playground/src/rfc/repl-session.js b/playground/src/rfc/repl-session.js new file mode 100644 index 0000000000..b81654f962 --- /dev/null +++ b/playground/src/rfc/repl-session.js @@ -0,0 +1,106 @@ +/** + * The page's side of the read-eval-print loop: a compiler worker of its + * own, so that what the loop has defined is not touched by the examples of + * the page, and so that an input that does not end can be stopped without + * stopping them. + */ + +const TIME_LIMIT = 20_000; + +/** + * @param libraries `[{name, source}]`: the modules the session starts with + * @param replay inputs that are evaluated before the first one of the reader + * @param onLog what the program prints after its input has finished + * @param onStatus `idle`, `loading`, `ready` or `failed` + */ +export function createSession({ libraries, replay, onLog, onStatus }) { + let worker = null; + let ready = null; // a promise, once the worker is started + let nextId = 1; + const pending = new Map(); // id -> {resolve, reject, timer} + + function settle(id, outcome, value) { + const request = pending.get(id); + if (!request) return; + pending.delete(id); + clearTimeout(request.timer); + request[outcome](value); + } + + function stop(message) { + if (worker) worker.terminate(); + worker = null; + ready = null; + for (const id of [...pending.keys()]) settle(id, "reject", new Error(message)); + onStatus("idle"); + } + + function start() { + if (ready) return ready; + onStatus("loading"); + worker = new Worker(new URL("../compiler-worker.js", import.meta.url), { type: "module" }); + ready = new Promise((resolve, reject) => { + worker.onmessage = (event) => { + const message = event.data; + if (message.type === "ready") { + worker.postMessage({ type: "repl-start", libraries, replay }); + } else if (message.type === "repl-started") { + onStatus("ready"); + resolve(message); + } else if (message.type === "repl-result") { + if (message.result.crashed) { + stop(message.result.crashed); + } else { + settle(message.id, "resolve", { ...message.result, ms: message.ms }); + } + } else if (message.type === "repl-log") { + onLog(message.line); + } else if (message.type === "failed") { + const text = `The compiler failed: ${message.message}`; + reject(new Error(text)); + stop(text); + onStatus("failed"); + } + }; + worker.onerror = (event) => { + const text = `The compiler failed: ${event.message || "it could not be loaded"}`; + reject(new Error(text)); + stop(text); + onStatus("failed"); + }; + }); + // Nothing waits for a session that is only warming up. + ready.catch(() => {}); + worker.postMessage({ type: "init", stdlibUrl: new URL("stdlib.json", document.baseURI).href }); + return ready; + } + + return { + /** Load the compiler and the session's modules, if they are not. */ + warmUp() { + start(); + }, + /** + * Evaluate one input. Resolves with `{output, expanded, javascript, ms}`; + * rejects when the session had to be stopped, and is then a new one. + */ + async evaluate(source) { + await start(); + return new Promise((resolve, reject) => { + const id = nextId++; + const timer = setTimeout(() => { + stop(`Stopped after ${TIME_LIMIT / 1000} seconds: the input probably does not end.`); + }, TIME_LIMIT); + pending.set(id, { resolve, reject, timer }); + worker.postMessage({ type: "repl-eval", id, source }); + }); + }, + /** Forget everything the session has defined. */ + reset() { + stop("The session was reset."); + }, + dispose() { + stop("The page was closed."); + }, + }; +} diff --git a/playground/src/rfc/rfc.css b/playground/src/rfc/rfc.css index b4f536c33b..88d5b40dcf 100644 --- a/playground/src/rfc/rfc.css +++ b/playground/src/rfc/rfc.css @@ -825,6 +825,233 @@ td:first-child { } } +/* The read-eval-print loop */ +.repl-screen { + max-height: 520px; + min-height: 220px; + overflow: auto; + padding: 14px 0 6px; + background: var(--sunken); + font-family: var(--mono); + font-size: 13px; + line-height: 1.6; + cursor: text; +} + +.repl-entry { + padding: 0 18px 12px; +} + +.repl-entry.fresh { + animation: repl-in 0.18s ease-out; +} + +@keyframes repl-in { + from { + opacity: 0; + transform: translateY(3px); + } +} + +.repl-source, +.repl-out, +.repl-detail { + margin: 0; + font: inherit; + tab-size: 2; + white-space: pre; + overflow-x: auto; +} + +.prose .repl-screen code { + padding: 0; + border: 0; + background: none; + font: inherit; +} + +.repl-row { + display: block; +} + +.repl-mark { + display: inline-block; + width: 18px; + flex-shrink: 0; + color: var(--accent); + font-weight: 700; + user-select: none; +} + +.repl-out { + padding-left: 18px; +} + +.repl-out.value { + color: var(--ink); +} + +.repl-out.log, +.repl-out.warn, +.repl-out.error, +.repl-out.problem, +.repl-out.note { + white-space: pre-wrap; + word-break: break-word; +} + +.repl-out.log { + color: var(--muted); +} + +.repl-out.warn { + color: var(--warn); +} + +.repl-out.error, +.repl-out.problem { + color: var(--error); +} + +.repl-out.note { + color: var(--muted); + font-style: italic; +} + +.repl-wait { + padding-left: 18px; + color: var(--muted); + animation: pulse 0.9s ease-in-out infinite; +} + +.repl-more { + display: flex; + gap: 12px; + padding: 2px 0 0 18px; +} + +.repl-more button { + padding: 0; + border: 0; + background: none; + font-family: var(--sans); + font-size: 10px; + font-weight: 700; + letter-spacing: 0.1em; + text-transform: uppercase; + color: var(--muted); + cursor: pointer; + opacity: 0.75; +} + +.repl-more button:hover, +.repl-more button.on { + color: var(--accent); + opacity: 1; +} + +.repl-more button::before { + content: "+ "; +} + +.repl-more button.on::before { + content: "− "; +} + +.repl-detail { + margin: 6px 0 2px 18px; + padding: 10px 14px; + border-left: 3px solid var(--generated-edge); + background: var(--generated); + font-size: 12.5px; +} + +.repl-input { + display: flex; + align-items: flex-start; + padding: 0 18px 10px; +} + +.repl-editor { + flex: 1 1 auto; + min-width: 0; +} + +.editor.repl-editor .cm-content { + padding: 0; +} + +.editor.repl-editor .cm-line { + padding: 0; +} + +.repl-editor .cm-placeholder { + color: var(--muted); + opacity: 0.7; +} + +.repl-run { + display: none; + flex-shrink: 0; + margin-left: 10px; + padding: 3px 9px; + border: 1px solid var(--line-strong); + background: transparent; + font-family: var(--sans); + font-size: 11px; + font-weight: 600; + cursor: pointer; +} + +.repl-tries { + display: flex; + align-items: center; + gap: 10px; + padding: 8px 16px; + border-top: 1px solid var(--line); + font-size: 12px; +} + +.repl-tries-label { + flex-shrink: 0; + text-transform: uppercase; + letter-spacing: 0.12em; + font-size: 9.5px; + font-weight: 700; + color: var(--muted); +} + +.repl-modules { + flex: 1 1 auto; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-family: var(--mono); + font-size: 11.5px; + color: var(--muted); +} + +.repl-try { + flex-shrink: 0; + background: var(--lime); + border-color: transparent; + color: #18201d; +} + +.repl-keys { + margin-left: auto; + white-space: nowrap; +} + +.repl-keys kbd { + padding: 0 4px; + border: 1px solid var(--line-strong); + border-radius: 3px; + font-family: var(--sans); + font-size: 10px; +} + /* The editor */ .editor .cm-editor { background: transparent; @@ -1271,6 +1498,27 @@ td:first-child { align-items: flex-start; } + .repl-screen { + max-height: 440px; + font-size: 12px; + } + + .repl-run { + display: block; + } + + .repl-keys { + display: none; + } + + .repl-tries { + flex-wrap: wrap; + } + + .repl-modules { + flex-basis: 60%; + } + .flow, .sequence, .chart { From 3653abb940f464b51185563bfaaaada16ddd54c7 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 21:59:36 +0100 Subject: [PATCH 05/11] docs: the session of the RFC, checked against the loop The RFC shows the opening session of the read-eval-print loop as text. `npm run smoke` runs that session and the inputs the page offers, and fails when the text is not what the loop says. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/os-01a1caab-4faf-7817-951e-2b3f9a5dae19 Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- docs/comptime/README.md | 40 ++++++++++++++++++++++++++++++++++-- playground/README.md | 20 ++++++++++++++++-- playground/scripts/smoke.mjs | 37 +++++++++++++++++++++++++++++++-- 3 files changed, 91 insertions(+), 6 deletions(-) diff --git a/docs/comptime/README.md b/docs/comptime/README.md index 6b96906be1..7eb8d2e9e6 100644 --- a/docs/comptime/README.md +++ b/docs/comptime/README.md @@ -75,6 +75,41 @@ 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. +### A session + +A read-eval-print loop with the macro modules of the examples below loaded +(`Debug`, `Json`, `Enum`, `Power` and the others) and the whole standard +library. Each input is compiled as a file of its own, with the earlier +inputs opened, and run once: a name, a type or a module that an input +defines is there for the next one, and `it` is the value of the last +expression. A macro cannot be used in the file that defines it, and an input +is a file: write a macro in a module in one input, and use it in the next. + + + +```text +> let price = 12.5 and quantity = 3 +let price: float = 12.5 +let quantity: int = 3 + +> %Debug.log(price *. Int.toFloat(quantity)) +price *. Int.toFloat(quantity) = 37.5 +- : float = 37.5 + +> type user = {name: string, age: int, email?: string} +type user = {name: string, age: int, email?: string} + +> Json.encode({name: "Ada", age: 36}) +- : JSON.t = + Object(dict{"name": String("Ada"), "age": Number(36.), "email": Null}) +``` + + + +The loop prints a value as the ReScript that makes it, which the JavaScript +value alone does not say (`Some(3)` is `3` at run time): the compiler gives +the shape of each value's type with the compiled input. + ### Quotes and holes `%code(...)` is a quote: a piece of ReScript that is not evaluated, a value @@ -1070,5 +1105,6 @@ npm run build:wasm npm run dev ``` -The playground's main page is this document with the examples live; the -full playground, with any number of files, is `playground.html`. +The playground's main page is this document with the examples and the +read-eval-print loop live; the full playground, with any number of files, is +`playground.html`. diff --git a/playground/README.md b/playground/README.md index d3f5d151ba..ac9e552cac 100644 --- a/playground/README.md +++ b/playground/README.md @@ -7,7 +7,7 @@ compiled program is run. | 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. | +| `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. The `` block becomes a read-eval-print loop. | | `implementation.html` | [docs/comptime/IMPLEMENTATION.md](../docs/comptime/IMPLEMENTATION.md). | | `playground.html` | The full playground: any number of files, share links. | @@ -42,11 +42,27 @@ 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/rfc/` | The RFC pages: the Markdown renderer, the live example, the read-eval-print loop, the diagrams. `scripts/prebuild-examples.mjs` writes the results they start from. | +| `src/repl-format.js`, `src/repl-transcript.js` | A JavaScript value as ReScript, by the shape of its type; a session as text. | | `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; the RFC page and the playground both show them. | +## The read-eval-print loop + +`engine.replStart` and `engine.replEval` are the loop. An input is compiled +as a file `Repl.res` with the files of the earlier inputs opened +(`compile_input` of the crate), and its JavaScript is run once. Before that, +`prepare_input` binds a last expression to `it`; after it, the compilation's +`signature` says what the input defined and what shape each value has, and +`src/repl-format.js` writes the JavaScript values as ReScript with it. The +loop has a compiler worker of its own (`src/rfc/repl-session.js`). + +`examples/repl.json` has the session the loop opens with (`intro`) and the +inputs it offers after that (`tries`). The opening session is also in the RFC +as text: `npm run smoke -- --write-transcript` writes it there, and +`npm run smoke` fails when the two differ. + ## Adding an example Add a directory under `examples/` with the files, and an entry in diff --git a/playground/scripts/smoke.mjs b/playground/scripts/smoke.mjs index b2d20968f6..d52767a7e4 100644 --- a/playground/scripts/smoke.mjs +++ b/playground/scripts/smoke.mjs @@ -4,12 +4,18 @@ * 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] + * It also runs the session the read-eval-print loop of the RFC page opens + * with, and the inputs it offers after that: none may fail, and the opening + * session has to be the transcript docs/comptime/README.md shows + * (`--write-transcript` puts it there). + * + * node scripts/smoke.mjs [example-id] [--show] [--write-transcript] */ -import { readFile } from "fs/promises"; +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"; +import { runSession, sessionLibraries, transcriptOf } from "../src/repl-transcript.js"; const root = join(import.meta.dirname, ".."); wasm.initSync({ module: await readFile(join(root, "crate/pkg/rescript_playground_wasm_bg.wasm")) }); @@ -52,4 +58,31 @@ for (const example of examples) { if (logs) console.log(logs.map((log) => ` | ${log.text}`).join("\n")); failed ||= !ok; } + +if (!only) { + const session = JSON.parse(await readFile(join(root, "examples/repl.json"), "utf-8")); + const inputs = [...session.intro, ...session.tries.map((entry) => entry.source)]; + const started = performance.now(); + const entries = await runSession(engine, sessionLibraries(examples), inputs); + const broken = entries.filter((entry) => entry.output.some((line) => line.kind === "problem" || line.kind === "warn")); + console.log(`${broken.length === 0 ? "ok " : "FAIL"} repl (${Math.round(performance.now() - started)} ms)`); + if (showAll || broken.length > 0) console.log(transcriptOf(showAll ? entries : broken)); + failed ||= broken.length > 0; + + // The opening session is in the RFC as text. + const readmePath = join(root, "../docs/comptime/README.md"); + const readme = await readFile(readmePath, "utf-8"); + const block = /(\n\n```text\n)([\s\S]*?)(\n```\n\n)/; + const transcript = transcriptOf(entries.slice(0, session.intro.length)); + const found = readme.match(block); + if (process.argv.includes("--write-transcript") && found) { + await writeFile(readmePath, readme.replace(block, (_, before, _old, after) => before + transcript + after)); + console.log("ok repl transcript written to docs/comptime/README.md"); + } else if (!found || found[2] !== transcript) { + console.log(`FAIL repl transcript: docs/comptime/README.md does not show this session\n${transcript}`); + failed = true; + } else { + console.log("ok repl transcript"); + } +} process.exit(failed ? 1 : 0); From 7d763b5fb870d1b04202aa3966e44a58d6056f23 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:46:02 +0100 Subject: [PATCH 06/11] site: the read-eval-print loop is the first section of the RFC Why: The loop was the first part of the tour, three screens down, and was missed. It is now the section "Try it" before "Why", the header has a link "REPL" to it, and the title has a chip that goes there. The section that says how to build the site is "Building it". A link to a heading from another page is followed once the page has rendered: the heading does not exist before that. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/os-01a1caab-4faf-7817-951e-2b3f9a5dae19 Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- docs/comptime/README.md | 76 +++++++++++++++++++------------------ playground/src/rfc/Page.jsx | 12 +++++- playground/src/rfc/rfc.css | 12 ++++++ 3 files changed, 62 insertions(+), 38 deletions(-) diff --git a/docs/comptime/README.md b/docs/comptime/README.md index 7eb8d2e9e6..bef78df7de 100644 --- a/docs/comptime/README.md +++ b/docs/comptime/README.md @@ -29,6 +29,7 @@ with tests (`compiler-rust/tests/macros.rs`) and a browser playground [What is missing](#what-is-missing). [IMPLEMENTATION.md](IMPLEMENTATION.md) describes the compiler side. +- [Try it](#try-it) - [Why](#why) - [A tour](#a-tour) - [Reference](#reference) @@ -37,7 +38,43 @@ describes the compiler side. - [Compared with](#compared-with) - [What is missing](#what-is-missing) - [Open questions](#open-questions) -- [Trying it](#trying-it) +- [Building it](#building-it) + +## Try it + +A read-eval-print loop with the macro modules of the examples in +[the tour](#a-tour) loaded (`Debug`, `Json`, `Enum`, `Power` and the others) +and the whole standard library. Each input is compiled as a file of its own, +with the earlier inputs opened, and run once: a name, a type or a module +that an input defines is there for the next one, and `it` is the value of +the last expression. A macro cannot be used in the file that defines it, and +an input is a file: write a macro in a module in one input, and use it in +the next. + + + +```text +> let price = 12.5 and quantity = 3 +let price: float = 12.5 +let quantity: int = 3 + +> %Debug.log(price *. Int.toFloat(quantity)) +price *. Int.toFloat(quantity) = 37.5 +- : float = 37.5 + +> type user = {name: string, age: int, email?: string} +type user = {name: string, age: int, email?: string} + +> Json.encode({name: "Ada", age: 36}) +- : JSON.t = + Object(dict{"name": String("Ada"), "age": Number(36.), "email": Null}) +``` + + + +The loop prints a value as the ReScript that makes it, which the JavaScript +value alone does not say (`Some(3)` is `3` at run time): the compiler gives +the shape of each value's type with the compiled input. ## Why @@ -75,41 +112,6 @@ 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. -### A session - -A read-eval-print loop with the macro modules of the examples below loaded -(`Debug`, `Json`, `Enum`, `Power` and the others) and the whole standard -library. Each input is compiled as a file of its own, with the earlier -inputs opened, and run once: a name, a type or a module that an input -defines is there for the next one, and `it` is the value of the last -expression. A macro cannot be used in the file that defines it, and an input -is a file: write a macro in a module in one input, and use it in the next. - - - -```text -> let price = 12.5 and quantity = 3 -let price: float = 12.5 -let quantity: int = 3 - -> %Debug.log(price *. Int.toFloat(quantity)) -price *. Int.toFloat(quantity) = 37.5 -- : float = 37.5 - -> type user = {name: string, age: int, email?: string} -type user = {name: string, age: int, email?: string} - -> Json.encode({name: "Ada", age: 36}) -- : JSON.t = - Object(dict{"name": String("Ada"), "age": Number(36.), "email": Null}) -``` - - - -The loop prints a value as the ReScript that makes it, which the JavaScript -value alone does not say (`Some(3)` is `3` at run time): the compiler gives -the shape of each value's type with the compiled input. - ### Quotes and holes `%code(...)` is a quote: a piece of ReScript that is not evaluated, a value @@ -1092,7 +1094,7 @@ implemented: much more code. The measurement that decides is a large project with many derives. -## Trying it +## Building it ```bash # the tests diff --git a/playground/src/rfc/Page.jsx b/playground/src/rfc/Page.jsx index f08f0c4a53..f6b7cb4bf6 100644 --- a/playground/src/rfc/Page.jsx +++ b/playground/src/rfc/Page.jsx @@ -63,6 +63,12 @@ export function Page({ markdown, title, lede, pages, current }) { const active = useActiveHeading(ids); const activeSection = toc.find((entry) => entry.id === active)?.section; + // A link to a heading from another page: the heading is there only now. + useEffect(() => { + const id = decodeURIComponent(window.location.hash.slice(1)); + if (id) document.getElementById(id)?.scrollIntoView(); + }, []); + // Load the compiler once the page has settled, so the first edit is quick. useEffect(() => { if (!parts.some((part) => part.type === "example")) return undefined; @@ -90,11 +96,12 @@ export function Page({ markdown, title, lede, pages, current }) { RFC + REPL Implementation Playground - + GitHub ↗
diff --git a/playground/src/rfc/Repl.jsx b/playground/src/rfc/Repl.jsx index 090525cb7c..28a7defa88 100644 --- a/playground/src/rfc/Repl.jsx +++ b/playground/src/rfc/Repl.jsx @@ -3,7 +3,16 @@ import { EditorState, Prec } from "@codemirror/state"; import { EditorView, drawSelection, highlightSpecialChars, keymap, placeholder } from "@codemirror/view"; import { defaultKeymap, history, historyKeymap } from "@codemirror/commands"; import { bracketMatching, indentUnit, syntaxHighlighting } from "@codemirror/language"; +import { + acceptCompletion, + closeCompletion, + completionStatus, + moveCompletionSelection, + selectedCompletion, + startCompletion, +} from "@codemirror/autocomplete"; import { classHighlighter } from "@lezer/highlight"; +import { completion } from "./completion.js"; import { codemirrorLanguage, highlight } from "./highlight.jsx"; import { createSession } from "./repl-session.js"; @@ -62,10 +71,10 @@ function Source({ code }) { } /** The input line: an editor where Enter evaluates and the arrows walk the history. */ -function Prompt({ onSubmit, past, viewRef, onFocus }) { +function Prompt({ onSubmit, past, viewRef, onFocus, complete }) { const host = useRef(null); - const state = useRef({ onSubmit, past, onFocus }); - state.current = { onSubmit, past, onFocus }; + const state = useRef({ onSubmit, past, onFocus, complete }); + state.current = { onSubmit, past, onFocus, complete }; // Where in the history the arrows are, and what was typed before them. const walk = useRef({ at: null, draft: "" }); @@ -90,7 +99,20 @@ function Prompt({ onSubmit, past, viewRef, onFocus }) { }); return true; }; + // With the list of completions open, Enter takes the chosen one; when + // that is what is written already, Enter is for the input. + const choose = (view) => { + if (completionStatus(view.state) !== "active") return false; + const chosen = selectedCompletion(view.state); + const head = view.state.selection.main.head; + const written = /[A-Za-z0-9_'.]*$/.exec(view.state.sliceDoc(view.state.doc.lineAt(head).from, head))[0]; + if (chosen && written !== chosen.label && !written.endsWith(`.${chosen.label}`)) return acceptCompletion(view); + closeCompletion(view); + return false; + }; const submit = (view, always) => { + if (!always && choose(view)) return true; + closeCompletion(view); const text = view.state.doc.toString(); if (text.trim() === "") return true; if (!always && !isComplete(text)) return newline(view); @@ -115,6 +137,7 @@ function Prompt({ onSubmit, past, viewRef, onFocus }) { return true; }); const older = (view) => { + if (completionStatus(view.state) === "active") return moveCompletionSelection(false)(view); const { past } = state.current; const head = view.state.selection.main.head; if (view.state.doc.lineAt(head).number !== 1 || past.length === 0) return false; @@ -126,6 +149,7 @@ function Prompt({ onSubmit, past, viewRef, onFocus }) { return true; }; const newer = (view) => { + if (completionStatus(view.state) === "active") return moveCompletionSelection(true)(view); const { past } = state.current; const head = view.state.selection.main.head; if (walk.current.at === null || view.state.doc.lineAt(head).number !== view.state.doc.lines) return false; @@ -149,10 +173,15 @@ function Prompt({ onSubmit, past, viewRef, onFocus }) { syntaxHighlighting(classHighlighter), codemirrorLanguage("rescript"), placeholder("Type ReScript and press Enter"), + // Enter and the arrows are the loop's: they choose from the list when it is open. + completion((...request) => state.current.complete(...request), { keys: false }), Prec.highest( keymap.of([ { key: "Enter", run: (target) => submit(target, false), shift: newline }, { key: "Mod-Enter", run: (target) => submit(target, true) }, + { key: "Tab", run: acceptCompletion }, + { key: "Escape", run: closeCompletion }, + { key: "Ctrl-Space", run: startCompletion }, { key: "ArrowUp", run: older }, { key: "ArrowDown", run: newer }, ]), @@ -365,7 +394,13 @@ export function Repl({ libraries, intro, tries }) { - + session.current.complete(source, offset, explicit)} + /> @@ -398,7 +433,8 @@ export function Repl({ libraries, intro, tries }) { {foot} - Enter runs, or continues an open bracket · Shift+Enter new line · ↑ earlier inputs + Enter runs, or continues an open bracket · Shift+Enter new line · Tab completes ·{" "} + ↑ earlier inputs diff --git a/playground/src/rfc/compiler.js b/playground/src/rfc/compiler.js index b8163ef46f..727d944d09 100644 --- a/playground/src/rfc/compiler.js +++ b/playground/src/rfc/compiler.js @@ -12,6 +12,8 @@ let ready = false; let running = null; // {id, key, resolve, reject, timer} const waiting = new Map(); // key -> {files, resolve, reject} let nextId = 1; +const completions = new Map(); // id -> resolve +const whenReady = []; // what is sent once the compiler has loaded const listeners = new Set(); let status = "idle"; // idle | loading | ready | failed @@ -38,6 +40,7 @@ function start() { if (message.type === "ready") { ready = true; setStatus("ready"); + for (const send of whenReady.splice(0)) send(); next(); } else if (message.type === "built") { if (!running || running.id !== message.id) return; @@ -51,6 +54,11 @@ function start() { done.resolve({ result: message.result, ms: message.ms }); } next(); + } else if (message.type === "completed") { + const resolve = completions.get(message.id); + completions.delete(message.id); + if (message.result?.crashed) restart(); + resolve?.(message.result?.crashed ? null : message.result); } else if (message.type === "failed") { fail(`The compiler failed: ${message.message}`); } @@ -71,6 +79,8 @@ function fail(message) { function restart() { if (worker) worker.terminate(); + for (const resolve of completions.values()) resolve(null); + completions.clear(); start(); } @@ -104,3 +114,25 @@ export function build(key, files) { next(); }); } + +/** + * What can be written at `offset` of the file `name` of the project + * `files`. Resolves with `{from, options, validFor}` or null. + */ +export function complete(files, name, offset, explicit) { + warmUp(); + return new Promise((resolve) => { + const id = nextId++; + const timer = setTimeout(() => { + completions.delete(id); + resolve(null); + }, 3000); + completions.set(id, (result) => { + clearTimeout(timer); + resolve(result); + }); + const send = () => worker.postMessage({ type: "complete", id, request: { mode: "project", files, name, offset, explicit } }); + if (ready) send(); + else whenReady.push(send); + }); +} diff --git a/playground/src/rfc/completion.js b/playground/src/rfc/completion.js new file mode 100644 index 0000000000..295bab32f0 --- /dev/null +++ b/playground/src/rfc/completion.js @@ -0,0 +1,21 @@ +/** + * Completion for an editor of the page. The answers come from the compiler + * (src/complete.js), through `request(source, offset, explicit)`, which + * resolves with `{from, options, validFor}` or null. + */ +import { autocompletion } from "@codemirror/autocomplete"; + +// Where a completion starts by itself: in a name, after `.`, `->`, `%`, `@`. +const TRIGGER = /(?:[A-Za-z_][A-Za-z0-9_']*|\.|->\s*|[%@])$/; + +/** `keys: false` leaves the keys of the list to the editor that has it. */ +export function completion(request, { keys = true } = {}) { + const source = async (context) => { + const line = context.state.doc.lineAt(context.pos); + if (!context.explicit && !TRIGGER.test(context.state.sliceDoc(line.from, context.pos))) return null; + const result = await request(context.state.doc.toString(), context.pos, context.explicit); + if (context.aborted || !result) return null; + return { from: result.from, options: result.options, validFor: new RegExp(result.validFor) }; + }; + return autocompletion({ override: [source], activateOnTypingDelay: 40, maxRenderedOptions: 120, defaultKeymap: keys }); +} diff --git a/playground/src/rfc/repl-session.js b/playground/src/rfc/repl-session.js index b81654f962..2caa3cd22d 100644 --- a/playground/src/rfc/repl-session.js +++ b/playground/src/rfc/repl-session.js @@ -6,6 +6,7 @@ */ const TIME_LIMIT = 20_000; +const COMPLETION_LIMIT = 3_000; /** * @param libraries `[{name, source}]`: the modules the session starts with @@ -53,6 +54,13 @@ export function createSession({ libraries, replay, onLog, onStatus }) { } else { settle(message.id, "resolve", { ...message.result, ms: message.ms }); } + } else if (message.type === "completed") { + if (message.result?.crashed) { + onLog({ kind: "problem", text: `${message.result.crashed}\nThe session starts again: what it had defined is gone.` }); + stop(message.result.crashed); + } else { + settle(message.id, "resolve", message.result); + } } else if (message.type === "repl-log") { onLog(message.line); } else if (message.type === "failed") { @@ -95,6 +103,24 @@ export function createSession({ libraries, replay, onLog, onStatus }) { worker.postMessage({ type: "repl-eval", id, source }); }); }, + /** + * What can be written at `offset` of the input `source`: resolves with + * `{from, options, validFor}` or null. + */ + async complete(source, offset, explicit) { + try { + await start(); + } catch { + return null; + } + return new Promise((resolve) => { + const id = nextId++; + // An input that is still running keeps the compiler busy. + const timer = setTimeout(() => settle(id, "resolve", null), COMPLETION_LIMIT); + pending.set(id, { resolve, reject: () => resolve(null), timer }); + worker.postMessage({ type: "complete", id, request: { mode: "repl", source, offset, explicit } }); + }); + }, /** Forget everything the session has defined. */ reset() { stop("The session was reset."); diff --git a/playground/src/rfc/rfc.css b/playground/src/rfc/rfc.css index c0831b4dd4..a56ea035ee 100644 --- a/playground/src/rfc/rfc.css +++ b/playground/src/rfc/rfc.css @@ -1097,6 +1097,68 @@ td:first-child { outline: 1px solid var(--line-strong); } +/* Completions */ +.editor .cm-editor .cm-tooltip { + border: 1px solid var(--line-strong); + background: var(--surface); + color: var(--ink); + box-shadow: 0 14px 34px -18px rgba(24, 32, 29, 0.55); +} + +.editor .cm-editor .cm-tooltip.cm-tooltip-autocomplete > ul { + max-height: 15.5em; + min-width: 220px; + max-width: min(620px, 92vw); + font-family: var(--mono); + font-size: 12.5px; + line-height: 1.5; +} + +.editor .cm-editor .cm-tooltip.cm-tooltip-autocomplete > ul > li { + display: flex; + align-items: baseline; + margin: 0; + padding: 2px 10px 2px 6px; + line-height: 1.5; + color: var(--ink); +} + +.editor .cm-editor .cm-tooltip.cm-tooltip-autocomplete > ul > li[aria-selected] { + background: var(--lime); + color: #18201d; +} + +.editor .cm-editor .cm-completionIcon { + flex-shrink: 0; + width: 1.2em; + padding-right: 0.5em; + opacity: 0.55; + font-size: 90%; +} + +.editor .cm-editor .cm-completionLabel { + flex-shrink: 0; +} + +.editor .cm-editor .cm-completionMatchedText { + text-decoration: none; + font-weight: 700; +} + +.editor .cm-editor .cm-completionDetail { + min-width: 0; + margin-left: 1.4em; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-style: normal; + color: var(--muted); +} + +.editor .cm-editor li[aria-selected] .cm-completionDetail { + color: rgba(24, 32, 29, 0.7); +} + /* Internals: the trees */ .tree-root { padding: 12px 10px; From c8c23229ec2ac61c406680843074ad3063a506d9 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:46:03 +0100 Subject: [PATCH 10/11] docs: completion in the RFC and the playground's README Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/os-01a1caab-4faf-7817-951e-2b3f9a5dae19 Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- docs/comptime/README.md | 8 ++++++++ playground/README.md | 16 +++++++++++++++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/docs/comptime/README.md b/docs/comptime/README.md index bef78df7de..f8e1d7a118 100644 --- a/docs/comptime/README.md +++ b/docs/comptime/README.md @@ -76,6 +76,14 @@ The loop prints a value as the ReScript that makes it, which the JavaScript value alone does not say (`Some(3)` is `3` at run time): the compiler gives the shape of each value's type with the compiled input. +The loop and the editors of the examples complete what is being written: +the members of a module after `Json.`, the macros of a module after +`%Debug.` and `@Enum.`, the fields of a record after `user.`, and after +`users->` the functions that take an array first. The type before a `.` or +a `->` is the one the compiler gives the expression where it stands, so a +function parameter completes like a top-level name. Tab or Enter takes a +completion. + ## Why ReScript code generation is done by PPXs today: native executables, written diff --git a/playground/README.md b/playground/README.md index ac9e552cac..165b2b627d 100644 --- a/playground/README.md +++ b/playground/README.md @@ -44,6 +44,7 @@ and the compiled program import. `npm run build` bundles both into | `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 read-eval-print loop, the diagrams. `scripts/prebuild-examples.mjs` writes the results they start from. | | `src/repl-format.js`, `src/repl-transcript.js` | A JavaScript value as ReScript, by the shape of its type; a session as text. | +| `src/complete.js` | Completion: what can be written at a place in a file, asked of the compiler. | | `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; the RFC page and the playground both show them. | @@ -59,10 +60,23 @@ as a file `Repl.res` with the files of the earlier inputs opened loop has a compiler worker of its own (`src/rfc/repl-session.js`). `examples/repl.json` has the session the loop opens with (`intro`) and the -inputs it offers after that (`tries`). The opening session is also in the RFC +inputs it offers after that (`tries`), and completions that have to be +offered after those (`completions`: an input and a label). The opening session is also in the RFC as text: `npm run smoke -- --write-transcript` writes it there, and `npm run smoke` fails when the two differ. +## Completion + +The compiler has no completion of its own. `src/complete.js` gets the +answers by compiling small files with it: `include Path` for the members of +a module, the file up to the item being written for the names in scope, and +the expression before a `.` or a `->` with a type it cannot have, in its +place, for its type (the error says which type it has). `engine.complete` +is the entry point; the worker answers a `complete` message with it. The +editors of the RFC page use it through `src/rfc/completion.js`, the +playground through a Monaco completion provider in `src/App.jsx`. +`npm run smoke` asks for the completions listed in `examples/repl.json`. + ## Adding an example Add a directory under `examples/` with the files, and an entry in From 171f40fefacf8a31397bb2e42edfb50cf96731a1 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 23:19:41 +0100 Subject: [PATCH 11/11] playground: a function prints in the input that calls it Why: Every input had a console of its own, which stopped collecting when the input finished. A function of an earlier input kept that console, so what it printed when a later input called it was shown as late output, below the answer of the input, or not with it at all. Before: > let shout = text => Console.log(text ++ "!") let shout: string => unit = > shout("hi") - : unit = () hi! After: > shout("hi") hi! - : unit = () A session has one console. What is printed while an input runs is that input's output; what is printed between inputs (a timer, a promise) is still shown on a line of its own. The names of the input modules are not used a second time by a later session of the same compiler instance: the compiler keeps what it knows of an opened module by its name, and the second session saw the first one's `Repl1`. `npm run smoke` runs a second session to check both. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/os-01a1caab-4faf-7817-951e-2b3f9a5dae19 Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- playground/scripts/smoke.mjs | 9 ++++++ playground/src/engine.js | 63 +++++++++++++++++++++++------------- 2 files changed, 50 insertions(+), 22 deletions(-) diff --git a/playground/scripts/smoke.mjs b/playground/scripts/smoke.mjs index 202ea114fd..1b5dc2bdf0 100644 --- a/playground/scripts/smoke.mjs +++ b/playground/scripts/smoke.mjs @@ -70,6 +70,15 @@ if (!only) { if (showAll || broken.length > 0) console.log(transcriptOf(showAll ? entries : broken)); failed ||= broken.length > 0; + // A function prints where it is called, not where it was defined. + const printed = await runSession(engine, [], ['let shout = text => Console.log(text ++ "!")', 'shout("hi")']); + const wanted = '> let shout = text => Console.log(text ++ "!")\nlet shout: string => unit = \n\n> shout("hi")\nhi!\n- : unit = ()'; + const same = transcriptOf(printed) === wanted; + console.log(`${same ? "ok " : "FAIL"} repl output of a function of an earlier input${same ? "" : `\n${transcriptOf(printed)}`}`); + failed ||= !same; + engine.replStart(sessionLibraries(examples)); + for (const input of inputs) await engine.replEval(input); + // What the editors offer after those inputs, and in a file of a project. const missing = []; const offered = (request, label) => { diff --git a/playground/src/engine.js b/playground/src/engine.js index b59f999291..0eea489f50 100644 --- a/playground/src/engine.js +++ b/playground/src/engine.js @@ -214,20 +214,31 @@ export function createEngine(wasm, stdlib) { // input defined, and what it did, stays. let session = null; + // Counts the inputs of every session: the compiler keeps what it knows of + // an opened module by its name, so a name is not used a second time. + let inputs = 0; const asyncFunction = Object.getPrototypeOf(async () => {}).constructor; const inputModules = /\bRepl\d+(_open\d+)?\./g; const hideInputModules = (text) => text.replace(inputModules, ""); hideModules(inputModules); + /** End the session: its inputs are gone. */ + function replEnd() { + for (const name of session?.files ?? []) wasm.forget_module(name); + session = null; + } + /** * Start a session with the modules of `libraries` (`[{name, source}]`) * available. `onLog` gets what the program prints after its input has * finished (a timer, a promise). Returns `{modules, problems}`. */ function replStart(libraries, onLog = () => {}) { + replEnd(); const { order, results } = build(libraries, { execute: false }); session = { - count: 0, + // The modules the inputs were compiled as. + files: [], // What the inputs defined, by name: the names an input can use. scope: new Map(), // What every input opens: earlier inputs, and the modules they opened. @@ -235,8 +246,19 @@ export function createEngine(wasm, stdlib) { // The modules an input defined: `open` of one is not `open` of a file. defined: new Set(), loaded: Object.create(null), - onLog, + // The output of the input that is running, or null between inputs. + printing: null, + }; + // One console for the whole session: a function prints where it is + // called, which is not always the input that defined it. Between inputs + // (a timer, a promise) the line goes to `onLog`. + const current = session; + const log = (kind) => (...values) => { + const line = { kind, text: values.map((value) => show(value)).join(" ") }; + if (current.printing) current.printing.push(line); + else onLog(line); }; + session.console = { log: log("log"), info: log("log"), debug: log("log"), warn: log("warn"), error: log("error") }; return { modules: order.filter((name) => results[name].type === "success").map(moduleNameOf), problems: order @@ -245,8 +267,8 @@ export function createEngine(wasm, stdlib) { }; } - function replLoad(name, console) { - const loaded = session.loaded; + function replLoad(name) { + const { loaded, console } = session; 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 session.`); @@ -254,7 +276,7 @@ export function createEngine(wasm, stdlib) { loaded[name] = module; try { new Function("require", "exports", "module", "console", toCommonJs(source))( - (specifier) => replLoad(moduleNameOf(specifier), console), + (specifier) => replLoad(moduleNameOf(specifier)), module.exports, module, console, @@ -294,7 +316,7 @@ export function createEngine(wasm, stdlib) { } /** Keep `open Path` of an input open for the inputs after it. */ - function replKeepOpen(text, input, console) { + function replKeepOpen(text, input) { const path = text.replace(/^open!?\s*/, "").trim(); const root = path.split(".")[0]; const isFile = !session.defined.has(root) && (stdlibModules.has(root) || projectJs[root] !== undefined); @@ -307,7 +329,8 @@ export function createEngine(wasm, stdlib) { const result = JSON.parse(wasm.compile_input(`include ${path}`, `${name}.res`, session.opens)); if (result.type !== "success") return `\`${text}\` is not kept open for the inputs after this one.`; projectJs[name] = result.js; - replLoad(name, console); + session.files.push(name); + replLoad(name); session.opens.push(name); return null; } @@ -321,8 +344,9 @@ export function createEngine(wasm, stdlib) { async function replEval(source) { if (!session) replStart([]); const current = session; - current.count += 1; - const name = `Repl${current.count}`; + inputs += 1; + const name = `Repl${inputs}`; + current.files.push(name); const filename = `${name}.res`; const output = []; @@ -343,31 +367,26 @@ export function createEngine(wasm, stdlib) { } projectJs[name] = result.js; - let finished = false; - const log = (kind) => (...values) => { - const line = { kind, text: values.map((value) => show(value)).join(" ") }; - if (finished) current.onLog(line); - else output.push(line); - }; - const console = { log: log("log"), info: log("log"), debug: log("log"), warn: log("warn"), error: log("error") }; const module = { exports: {} }; + // What is printed while the input runs is its output, whoever prints it. + current.printing = output; try { // An input can `await` at the top level. await new asyncFunction("require", "exports", "module", "console", toCommonJs(result.js))( - (specifier) => replLoad(moduleNameOf(specifier), console), + (specifier) => replLoad(moduleNameOf(specifier)), module.exports, module, - console, + current.console, ); } catch (error) { - finished = true; + current.printing = null; // What it defined before it raised is not kept: part of it is missing. wasm.forget_module(name); delete projectJs[name]; output.push({ kind: "problem", text: `Uncaught ${formatException(error)}` }); return { output, expanded: result.expanded ?? null, javascript: result.js }; } - finished = true; + current.printing = null; current.loaded[name] = module; current.opens.push(name); @@ -393,7 +412,7 @@ export function createEngine(wasm, stdlib) { output.push({ kind: "value", text: joined }); } for (const open of prepared.opens ?? []) { - const note = replKeepOpen(open, name, console); + const note = replKeepOpen(open, name); if (note) output.push({ kind: "note", text: note }); } return { output, expanded: result.expanded ?? null, javascript: result.js }; @@ -457,7 +476,7 @@ export function createEngine(wasm, stdlib) { file.name === projectFiles[index].name && (file.name === name || file.source === projectFiles[index].source), ); if (!built) { - session = null; + replEnd(); const outcome = build(files, { execute: false }); if (outcome.crashed) return { crashed: outcome.crashed }; }