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/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/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.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 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}"); + }); +} diff --git a/docs/comptime/README.md b/docs/comptime/README.md index 6b96906be1..f8e1d7a118 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,51 @@ 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. + +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 @@ -1057,7 +1102,7 @@ implemented: much more code. The measurement that decides is a large project with many derives. -## Trying it +## Building it ```bash # the tests @@ -1070,5 +1115,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..165b2b627d 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,41 @@ 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/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. | +## 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`), 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 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/examples/repl.json b/playground/examples/repl.json new file mode 100644 index 0000000000..1bc43ad1ba --- /dev/null +++ b/playground/examples/repl.json @@ -0,0 +1,80 @@ +{ + "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))" + }, + { + "label": "a query checked against schema.sql", + "source": "module Vips = %Sql.query(\"select name, city from customers where vip = :vip\")" + } + ], + "completions": [ + [ + "price->", + "Float.toFixed" + ], + [ + "Json.", + "encode" + ], + [ + "%Debug.", + "log" + ], + [ + "@Enum.", + "derive" + ], + [ + "[1, 2]->Array.map(n => n + 1)->", + "Array.length" + ], + [ + "sizeValues->Array.map(size => size->", + "sizeToString" + ], + [ + "let ada: user = {name: \"Ada\", age: 36}\n[ada]->Array.map(u => u.", + "email" + ], + [ + "Vips.", + "run" + ], + [ + "pri", + "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/scripts/smoke.mjs b/playground/scripts/smoke.mjs index b2d20968f6..1b5dc2bdf0 100644 --- a/playground/scripts/smoke.mjs +++ b/playground/scripts/smoke.mjs @@ -4,12 +4,19 @@ * 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). After that session it asks for the + * completions of examples/repl.json, and for some in a file of a project. + * + * 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 +59,60 @@ 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; + + // 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) => { + const result = engine.complete(request); + if (result?.crashed || !result?.options.some((option) => option.label === label)) { + missing.push(`${JSON.stringify(request.source ?? request.name)}: ${label} is not offered`); + } + }; + for (const [source, label] of session.completions) offered({ mode: "repl", source, offset: source.length }, label); + const project = examples.find((example) => example.id === "json"); + const written = (name, text) => { + const files = project.files.map((file) => (file.name === name ? { ...file, source: file.source + text } : file)); + return { mode: "project", files, name, offset: files.find((file) => file.name === name).source.length }; + }; + offered(written("Main.res", "\nlet n = alice."), "avatar"); + offered(written("Main.res", "\nlet n = team->"), "Array.map"); + offered(written("Json.res", "\nlet f = (field: Type.field) => field."), "jsName"); + console.log(`${missing.length === 0 ? "ok " : "FAIL"} completions${missing.map((line) => `\n ${line}`).join("")}`); + failed ||= missing.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); diff --git a/playground/src/App.jsx b/playground/src/App.jsx index 906c76cc27..b789e70ea6 100644 --- a/playground/src/App.jsx +++ b/playground/src/App.jsx @@ -8,11 +8,52 @@ import { isSourceFile } from "./engine.js"; import { examples } from "./examples.js"; import { decodeProject, encodeProject } from "./share.js"; +// What the page answers a completion request with: set by the App, which +// has the project and the compiler. `(name, offset, explicit, source)`. +let completeAt = null; + +const COMPLETION_KINDS = { + function: "Function", + variable: "Variable", + type: "Struct", + namespace: "Module", + interface: "Interface", + class: "Class", + property: "Field", + keyword: "Keyword", + text: "Text", +}; + // Register ReScript language with Monaco before any editor mounts let monacoInstance = null; loader.init().then((monaco) => { monacoInstance = monaco; registerRescriptLanguage(monaco); + // Completions come from the compiler (src/complete.js). + monaco.languages.registerCompletionItemProvider(languageId, { + triggerCharacters: [".", ">", "%", "@"], + async provideCompletionItems(model, position, context) { + if (!completeAt) return { suggestions: [] }; + // The model's path is `/`. + const name = model.uri.path.split("/").pop(); + const explicit = context.triggerKind === monaco.languages.CompletionTriggerKind.Invoke; + const result = await completeAt(name, model.getOffsetAt(position), explicit, model.getValue()); + if (!result) return { suggestions: [] }; + const start = model.getPositionAt(result.from); + const range = new monaco.Range(start.lineNumber, start.column, position.lineNumber, position.column); + return { + suggestions: result.options.map((option, index) => ({ + label: option.label, + kind: monaco.languages.CompletionItemKind[COMPLETION_KINDS[option.type] ?? "Text"], + detail: option.detail, + insertText: option.label, + // More local names first, then the order the compiler gave. + sortText: `${String(9 - Math.min(9, (option.boost ?? 0) + 3))}${String(index).padStart(5, "0")}`, + range, + })), + }; + }, + }); }); const TABS = [ @@ -34,6 +75,8 @@ const EDITOR_OPTIONS = { automaticLayout: true, padding: { top: 12 }, renderLineHighlight: "gutter", + // The compiler completes; words of the file would be listed twice. + wordBasedSuggestions: "off", }; const READONLY_OPTIONS = { @@ -112,7 +155,17 @@ export default function App() { }); compilerRef.current = compiler; compiler.build(filesRef.current); - return () => compiler.dispose(); + completeAt = (name, offset, explicit, source) => + compiler.complete( + filesRef.current.map((file) => (file.name === name ? { ...file, source } : file)), + name, + offset, + explicit, + ); + return () => { + completeAt = null; + compiler.dispose(); + }; }, []); const requestBuild = useCallback((nextFiles, delay) => { diff --git a/playground/src/compiler-client.js b/playground/src/compiler-client.js index 3c1ca8befb..f588501466 100644 --- a/playground/src/compiler-client.js +++ b/playground/src/compiler-client.js @@ -12,6 +12,8 @@ export function createCompiler({ onReady, onResult, onFailure }) { let running = null; // {id, timer} let waiting = null; // files let nextId = 1; + const completions = new Map(); // id -> resolve + const whenReady = []; // what is sent once the compiler has loaded function start() { ready = false; @@ -21,6 +23,7 @@ export function createCompiler({ onReady, onResult, onFailure }) { if (message.type === "ready") { ready = true; onReady(); + for (const send of whenReady.splice(0)) send(); next(); } else if (message.type === "built") { if (!running || running.id !== message.id) return; @@ -34,6 +37,11 @@ export function createCompiler({ onReady, onResult, onFailure }) { onResult(message.result, 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") { if (running) clearTimeout(running.timer); running = null; @@ -51,6 +59,8 @@ export function createCompiler({ onReady, onResult, onFailure }) { function restart() { worker.terminate(); + for (const resolve of completions.values()) resolve(null); + completions.clear(); start(); } @@ -77,6 +87,27 @@ export function createCompiler({ onReady, onResult, onFailure }) { waiting = files; next(); }, + /** + * What can be written at `offset` of the file `name` of the project + * `files`. Resolves with `{from, options, validFor}` or null. + */ + complete(files, name, offset, explicit) { + 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); + }); + }, dispose() { if (running) clearTimeout(running.timer); worker.terminate(); diff --git a/playground/src/compiler-worker.js b/playground/src/compiler-worker.js index b1fc228607..e087245e10 100644 --- a/playground/src/compiler-worker.js +++ b/playground/src/compiler-worker.js @@ -21,6 +21,26 @@ 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 === "complete") { + // What can be written at a place: see engine.complete. + let result = null; + try { + if (engine) result = engine.complete(message.request); + } catch (error) { + // No completion is better than a compiler that is started again. + console.error(error); + } + self.postMessage({ type: "completed", id: message.id, result }); + } 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/complete.js b/playground/src/complete.js new file mode 100644 index 0000000000..80ff54f2c0 --- /dev/null +++ b/playground/src/complete.js @@ -0,0 +1,563 @@ +/** + * Completion: what can be written at a place in a file. + * + * The compiler has no completion of its own, so the answers come from + * compiling small files with it: + * + * - the members of a module are what a file `include Path` defines; + * - the names in scope are what the file up to the item being written + * defines, and the members of what it opens; + * - the type of the expression before a `.` or a `->` is what the compiler + * says when that expression is given a type it cannot have, in the place + * where it is written, so that function parameters and other local names + * have their types. From that type come the fields of a record, and the + * functions that take it first, for a pipe. + * + * This file has no dependency on the page: `contextAt` is the lexical half, + * `createCompleter` the half that asks the compiler. + */ + +const KEYWORDS = [ + "and", "as", "assert", "async", "await", "catch", "constraint", "else", "exception", "external", "false", "for", + "if", "in", "include", "let", "module", "mutable", "of", "open", "private", "rec", "switch", "true", "try", + "type", "when", "while", "with", +]; +const KEYWORD_SET = new Set(KEYWORDS); +// After these a name is being given, not used. +const BINDERS = new Set(["let", "rec", "type", "module", "exception", "external", "and", "as", "open", "include"]); +// A line that starts with one of these continues the item before it. +const CONTINUES = /^(?:and|else|catch)\b/; +const CLOSERS = { "(": ")", "[": "]", "{": "}" }; + +/** + * The tokens of `text`, the brackets that are open at its end, and the + * offsets where a top-level item starts. `inside` is "string" or "comment" + * when the text ends in one. + */ +export function tokenize(text) { + const tokens = []; + const stack = []; + const starts = []; + let inside = null; + const length = text.length; + const consider = (at) => { + const char = text[at]; + if (char === undefined || /\s/.test(char) || ")]}|.,:?&+*/<>=-".includes(char)) return; + if (CONTINUES.test(text.slice(at, at + 6))) return; + starts.push(at); + }; + const push = (t, s, e, extra) => tokens.push({ t, s, e, v: text.slice(s, e), ...extra }); + consider(0); + let i = 0; + while (i < length) { + const char = text[i]; + if (char === "\n") { + if (stack.length === 0) consider(i + 1); + i += 1; + } else if (/\s/.test(char)) { + i += 1; + } else if (text.startsWith("//", i)) { + const end = text.indexOf("\n", i); + if (end < 0) { + inside = "comment"; + break; + } + i = end; + } else if (text.startsWith("/*", i)) { + let open = 1; + i += 2; + while (i < length && open > 0) { + if (text.startsWith("/*", i)) (open += 1), (i += 2); + else if (text.startsWith("*/", i)) (open -= 1), (i += 2); + else i += 1; + } + if (open > 0) { + inside = "comment"; + break; + } + } else if (char === '"' || char === "`") { + const start = i; + i += 1; + while (i < length && text[i] !== char) i += text[i] === "\\" ? 2 : 1; + if (i >= length) { + inside = "string"; + break; + } + i += 1; + push("str", start, i); + } else if (char === "'") { + const literal = /^'(?:\\[^']*|[^\\'])'/.exec(text.slice(i, i + 12)); + const variable = /^'[A-Za-z_][A-Za-z0-9_]*/.exec(text.slice(i, i + 64)); + const end = i + (literal ? literal[0].length : variable ? variable[0].length : 1); + push(literal ? "str" : variable ? "tv" : "op", i, end); + i = end; + } else if (/[0-9]/.test(char)) { + const number = /^\d[\d_]*(?:\.[\d_]*)?(?:[eE][+-]?\d+)?n?/.exec(text.slice(i, i + 64)); + push("num", i, i + number[0].length); + i += number[0].length; + } else if (/[A-Za-z_]/.test(char)) { + let end = i + 1; + while (end < length && /[A-Za-z0-9_']/.test(text[end])) end += 1; + push(/[A-Z]/.test(char) ? "up" : "id", i, end); + i = end; + } else if ("([{".includes(char)) { + stack.push(tokens.length); + push("open", i, i + 1); + i += 1; + } else if (")]}".includes(char)) { + const match = stack.length > 0 ? stack.pop() : -1; + push("close", i, i + 1, { match }); + i += 1; + } else { + const end = text.startsWith("->", i) || text.startsWith("=>", i) ? i + 2 : text.startsWith("...", i) ? i + 3 : i + 1; + push("op", i, end); + i = end; + } + } + return { tokens, stack, starts, inside }; +} + +/** + * The token an expression that ends with the token `k` starts with: names + * and literals joined by `.` and `->`, with their calls and brackets. -1 + * when no expression ends there. + */ +function operandStart(tokens, k) { + let i = k; + for (;;) { + const token = tokens[i]; + if (!token) return -1; + if (token.t === "close") { + if (token.match < 0) return -1; + i = token.match; + // `f(x)`, `list{...}`: what is called or indexed. + const before = tokens[i - 1]; + if (before && before.e === tokens[i].s && (before.t === "id" || before.t === "up" || before.t === "close")) { + i -= 1; + continue; + } + } else if (!["id", "up", "num", "str"].includes(token.t)) { + return -1; + } else if (token.t === "id" && KEYWORD_SET.has(token.v) && token.v !== "true" && token.v !== "false") { + return -1; + } + const joint = tokens[i - 1]; + if (joint && joint.t === "op" && (joint.v === "." || joint.v === "->") && tokens[i - 2]) { + i -= 2; + continue; + } + if (joint && joint.t === "op" && joint.v === "#" && joint.e === tokens[i].s) return i - 1; + return i; + } +} + +/** + * What is being written at `offset` of `source`: + * + * - `{kind: "member", path, sigil}` after `Path.`, with the `%` or `@` + * before the path; + * - `{kind: "field", operand}` after `expression.`; + * - `{kind: "pipe", operand}` after `expression->`; + * - `{kind: "sigil", sigil}` after `%` or `@`; + * - `{kind: "name"}` for a name. + * + * `from` is where the word being written starts and `partial` that word; + * `start` is where the top-level item around it starts; `operand` is the + * range of the expression and `closers` what closes the brackets that are + * open there. Null inside a string or a comment, and where a name is given. + */ +export function contextAt(source, offset) { + const { tokens, stack, starts, inside } = tokenize(source.slice(0, offset)); + if (inside) return null; + + // The item starts at the last line that starts one; an attribute on a + // line of its own belongs to the item below it. + let at = starts.length - 1; + while (at > 0 && /^(?:@@?[A-Za-z_][\w.]*(?:\([^()]*\))?\s*)+$/.test(source.slice(starts[at - 1], starts[at]))) at -= 1; + const start = starts[at] ?? 0; + + let last = tokens.length - 1; + let partial = ""; + let from = offset; + const word = tokens[last]; + if (word && (word.t === "id" || word.t === "up") && word.e === offset) { + partial = word.v; + from = word.s; + last -= 1; + } + const base = { from, partial, start }; + const prev = tokens[last]; + const sigilBefore = (index) => { + const token = tokens[index]; + const next = tokens[index + 1]; + if (!token || token.t !== "op" || !next || token.e !== next.s) return null; + return token.v === "%" || token.v === "@" ? token.v : null; + }; + const withOperand = (kind, end) => { + const first = operandStart(tokens, end); + if (first < 0 || tokens[first].s < start) return null; + const closers = stack + .map((index) => CLOSERS[tokens[index].v]) + .reverse() + .join(""); + return { ...base, kind, operand: { s: tokens[first].s, e: tokens[end].e }, closers }; + }; + + if (prev && prev.t === "op" && prev.v === "." && prev.e === from) { + // A module path: `Json.`, `Intl.NumberFormat.`. + const segments = []; + let index = last - 1; + while (tokens[index]?.t === "up" && tokens[index].e === tokens[index + 1].s) { + segments.unshift(tokens[index].v); + const dot = tokens[index - 1]; + if (dot?.t === "op" && dot.v === "." && tokens[index - 2]?.t === "up") index -= 2; + else break; + } + if (segments.length > 0) { + const before = tokens[index - 1]; + const isField = before?.t === "op" && before.v === "." && before.e === tokens[index].s; + if (!isField) return { ...base, kind: "member", path: segments.join("."), sigil: sigilBefore(index - 1) }; + } + return withOperand("field", last - 1); + } + if (prev && prev.t === "op" && prev.v === "->") return withOperand("pipe", last - 1); + if (prev && prev.t === "op" && prev.e === from) { + if (prev.v === "%" || prev.v === "@") return { ...base, kind: "sigil", sigil: prev.v }; + if (prev.v === "~" || prev.v === "#") return null; + } + if (prev && prev.t === "id" && BINDERS.has(prev.v)) return null; + return { ...base, kind: "name" }; +} + +// ── Reading what the compiler printed ─────────────────────────────────────── + +const SCRATCH = /\b(?:Repl\d+(?:_open\d+)?|Complete__[HP]\d*)\./g; + +function stripAnsi(text) { + return text.replace(/\u001b\[[0-9;]*m/g, ""); +} + +function oneLine(text) { + return text.replace(/\s+/g, " ").trim(); +} + +/** The type of a value from its declaration: `let f: t`, `@send external f: t = "f"`. */ +export function typeOfDeclaration(text) { + const declaration = /^(?:@[\w.]+(?:\([^)]*\))?\s+)*(?:let|external)\s+\S+?:\s*([\s\S]*)$/.exec(text); + if (!declaration) return null; + return oneLine(declaration[1]) + .replace(/ = "[^"]*"$/, "") + .replace(SCRATCH, ""); +} + +/** `text` up to the first `separator` that is not inside brackets. */ +function upTo(text, separators) { + let depth = 0; + for (let i = 0; i < text.length; i++) { + const char = text[i]; + if ("(<[{".includes(char)) depth += 1; + else if (char === ">" && text[i - 1] === "=") continue; + else if (")>]}".includes(char)) depth -= 1; + else if (depth === 0 && separators.some((separator) => text.startsWith(separator, i))) return text.slice(0, i); + } + return text; +} + +/** The name a type starts with: `array` of `array`, `Map.t` of `Map.t`. */ +export function typeHead(type) { + const text = type.trim(); + const head = /^[A-Za-z_][\w.']*/.exec(text); + return head ? head[0] : null; +} + +/** The type of the first parameter of a function type, or null. */ +export function firstParameter(type) { + const text = type.trim(); + if (!text.includes("=>")) return null; + let first; + if (text.startsWith("(")) { + // `(a, b) => c`, unless the brackets are a tuple that is the only parameter. + let depth = 0; + let end = -1; + for (let i = 0; i < text.length; i++) { + if ("(<[{".includes(text[i])) depth += 1; + else if (text[i] === ">" && text[i - 1] === "=") continue; + else if (")>]}".includes(text[i])) { + depth -= 1; + if (depth === 0) { + end = i; + break; + } + } + } + if (end < 0) return null; + first = upTo(text.slice(1, end), [","]); + } else { + first = upTo(text, [" =>"]); + } + first = first.trim(); + // A labelled parameter is not what a pipe fills. + if (first.startsWith("~")) return null; + return first; +} + +// The module with the functions of a type the compiler has built in. +const TYPE_MODULES = { + array: "Array", string: "String", int: "Int", float: "Float", bool: "Bool", bigint: "BigInt", option: "Option", + result: "Result", list: "List", dict: "Dict", promise: "Promise", exn: "Exn", +}; + +function isName(name) { + return /^[A-Za-z_][A-Za-z0-9_']*$/.test(name); +} + +function optionOf(item, extra = {}) { + const collapsed = oneLine(item.text).replace(SCRATCH, ""); + let type = "variable"; + let detail = ""; + if (item.kind === "value") { + detail = typeOfDeclaration(item.text) ?? ""; + if (item.shape?.k === "fn") type = "function"; + } else if (item.kind === "type") { + type = "type"; + detail = collapsed.replace(/^(?:@[\w.]+(?:\([^)]*\))?\s+)*type\s+(?:rec\s+)?/, ""); + } else if (item.kind === "module") { + type = "namespace"; + detail = "module"; + } else if (item.kind === "moduleType") { + type = "interface"; + detail = "module type"; + } else if (item.kind === "exception") { + type = "class"; + detail = collapsed.replace(/^type exn \+=\s*/, "exception "); + } + if (detail.length > 120) detail = `${detail.slice(0, 117)}…`; + return { label: item.name, type, detail, ...extra }; +} + +export class CompilerCrash extends Error {} + +/** + * @param wasm the initialized wasm-bindgen module of playground/crate + */ +export function createCompleter(wasm) { + const PROBE = "Complete__P"; + // The file up to the item being written is a module that probes open. It + // has a new name every time it changes: the compiler keeps what it knows + // of an opened module by its name. + let heads = 0; + // The standard library does not change: what it gives every file. + let globals = null; + let cacheKey = null; + let members = new Map(); + let head = null; // {text, name, module, items, opens} + + function dropHead() { + if (head) wasm.forget_module(head.name); + head = null; + members = new Map(); + } + + function compile(text, name, opens) { + try { + return JSON.parse(wasm.compile_input(text, `${name}.res`, opens)); + } catch (error) { + // A panic in the compiler: the wasm instance is unusable from here. + throw new CompilerCrash(`The compiler crashed: ${String(error?.message ?? error)}`); + } + } + + function probe(text, opens) { + const result = compile(text, PROBE, opens); + wasm.forget_module(PROBE); + return result; + } + + function itemsOf(result) { + return result.type === "success" ? (result.signature?.items ?? []) : null; + } + + /** What `env` gives a probe: the modules it opens, and the `open`s of the file. */ + function scopeOf(env) { + return { + opens: head?.module ? [...env.opens, head.module] : env.opens, + text: head && head.opens.length > 0 ? `${head.opens.join("\n")}\n` : "", + }; + } + + /** The items of the module `path`, or null when there is no such module. */ + function membersOf(path, env) { + const scope = scopeOf(env); + const key = `${path}\n${scope.opens.join(",")}\n${scope.text}`; + if (!members.has(key)) members.set(key, itemsOf(probe(`${scope.text}include ${path}`, scope.opens))); + return members.get(key); + } + + /** Compile the file up to the item being written, for what it defines. */ + function readHead(text, env) { + if (head ? head.text === text : text.trim() === "") return; + dropHead(); + if (text.trim() === "") return; + heads += 1; + const name = `Complete__H${heads}`; + const prepared = JSON.parse(wasm.prepare_input(text, `${name}.res`)); + const opens = prepared.type === "success" ? prepared.opens : []; + const result = compile(text, name, env.opens); + head = { + text, + name, + opens, + module: result.type === "success" ? name : null, + items: itemsOf(result) ?? [], + }; + } + + /** + * The type of the expression `at.operand`: in its place, then alone, for + * when the item around it does not compile. + */ + function typeOfOperand(at, source, env) { + const scope = scopeOf(env); + const operand = source.slice(at.operand.s, at.operand.e); + const item = `${source.slice(at.start, at.operand.s)}(${operand}: complete__)${at.closers}`; + const placed = probe(`${scope.text}type complete__\n${item}`, scope.opens); + if (placed.type === "error") { + const said = /This has type: ([\s\S]*?)\n\s*But [^\n]*\bcomplete__/.exec(stripAnsi(placed.message ?? "")); + if (said) return oneLine(said[1]); + } + const alone = itemsOf(probe(`${scope.text}let it = (${operand})`, scope.opens)); + const it = alone?.find((candidate) => candidate.name === "it"); + return it ? typeOfDeclaration(it.text) : null; + } + + /** The fields of the record type `type`, each with its type. */ + function fields(type, env) { + const scope = scopeOf(env); + const declaration = `${scope.text}external complete__v: ${type} = "v"\n`; + const described = probe(declaration, scope.opens); + if (described.type !== "success") return null; + const shape = described.signature?.items?.find((item) => item.name === "complete__v")?.shape; + const record = shape?.k === "ref" ? described.signature.defs[shape.id] : null; + if (record?.k !== "record") return null; + const names = record.fields.map((field) => field.name); + const typed = itemsOf( + probe(declaration + names.map((name, index) => `let f${index} = complete__v.${name}`).join("\n"), scope.opens), + ); + return names.map((name, index) => ({ + label: name, + type: "property", + // In the order of the declaration. + boost: 1 - index / names.length, + detail: typeOfDeclaration(typed?.find((item) => item.name === `f${index}`)?.text ?? "") ?? "", + })); + } + + /** + * The names a file can use without a module path. `own` leaves out what + * every file has: the keywords and the standard library. + */ + function names(env, statement, own = false) { + if (!globals) { + globals = [...(itemsOf(probe("include Pervasives", [])) ?? []), ...(itemsOf(probe("include Stdlib", [])) ?? [])]; + } + const found = new Map(); + const add = (option) => { + if (isName(option.label)) found.set(option.label, option); + }; + if (!own) { + for (const keyword of KEYWORDS) add({ label: keyword, type: "keyword", boost: -2 }); + // Names of the item being written: parameters, local bindings. + for (const token of tokenize(statement).tokens) { + if (token.t === "id" && !KEYWORD_SET.has(token.v)) add({ label: token.v, type: "text", boost: -1 }); + } + for (const item of globals) add(optionOf(item)); + } + for (const name of ["Macro", ...env.modules]) add({ label: name, type: "namespace", detail: "module" }); + const opened = [...env.opened, ...(head?.opens ?? []).map((open) => open.replace(/^open!?\s*/, "").trim())]; + for (const path of opened) for (const item of membersOf(path, env) ?? []) add(optionOf(item, { boost: 1 })); + for (const item of env.scope) add(optionOf(item, { boost: 2 })); + for (const item of head?.items ?? []) add(optionOf(item, { boost: 2 })); + return [...found.values()]; + } + + /** Functions that take a `type` first: what can follow `value->`. */ + function pipes(type, env, statement) { + const headName = typeHead(type); + if (!headName) return null; + const clean = headName.replace(SCRATCH, ""); + const dot = clean.lastIndexOf("."); + const module = dot > 0 ? clean.slice(0, dot) : TYPE_MODULES[clean]; + const takes = (item, accepted) => { + const signature = item.kind === "value" ? typeOfDeclaration(item.text) : null; + const first = signature && firstParameter(signature); + const firstHead = first && typeHead(first); + // A type variable takes anything, which says nothing about this type. + return firstHead ? accepted.includes(firstHead) : false; + }; + const options = []; + if (module) { + const accepted = [clean, dot > 0 ? clean.slice(dot + 1) : "t"]; + for (const item of membersOf(module, env) ?? []) { + if (isName(item.name) && takes(item, accepted)) options.push(optionOf(item, { label: `${module}.${item.name}` })); + } + } + for (const option of names(env, statement)) { + if (option.type !== "function") continue; + const first = firstParameter(option.detail ?? ""); + if (first && typeHead(first) === clean) options.push({ ...option, boost: 3 }); + } + return options; + } + + /** + * The completions at `offset` of `source`: `{from, options, validFor}` + * with `options` of `{label, type, detail, boost}`, or null. + * + * @param env `{key, opens, opened, modules, scope}`: what identifies the + * state of the project; the modules every file of it has open; the + * module paths that are open besides those; the names of its modules; + * and the items that are in scope without a path. + */ + function complete(env, source, offset, explicit) { + const at = contextAt(source, offset); + if (!at) return null; + if (cacheKey !== env.key) { + cacheKey = env.key; + dropHead(); + } + readHead(source.slice(0, at.start), env); + const statement = source.slice(at.start, at.from); + const word = "^[A-Za-z0-9_']*$"; + const answer = (options, validFor = word) => + options && options.length > 0 ? { from: at.from, options, validFor } : null; + + if (at.kind === "member") { + let items = membersOf(at.path, env); + if (!items) return null; + // After `%` and `@` only what a macro returns: code, a type, a pattern, declarations. + if (at.sigil) items = items.filter((item) => item.kind === "module" || /\bMacro\.|\b(?:code|typ|pat|decls)\b/.test(item.text)); + return answer(items.filter((item) => isName(item.name)).map((item) => optionOf(item))); + } + if (at.kind === "sigil") { + const forms = + at.sigil === "%" + ? [["code", "a quoted expression"], ["type", "a quoted type"], ["pat", "a quoted pattern"], ["Macro.eval", "the value of an expression, computed while compiling"], ["raw", "JavaScript"], ["re", "a regular expression"]] + : [["macro", "the function is a macro"], ["generic", "a macro that is called like a function"], ["as", ""], ["unboxed", ""], ["deprecated", ""], ["module", ""], ["val", ""], ["send", ""], ["new", ""], ["get", ""], ["set", ""], ["scope", ""], ["variadic", ""], ["tag", ""], ["inline", ""], ["warning", ""]]; + // Macros are in the modules of the project, not in the standard library. + const modules = names(env, statement, true).filter((option) => option.type === "namespace" && option.label !== "Macro"); + return answer( + [...forms.map(([label, detail]) => ({ label, type: "keyword", detail, boost: 1 })), ...modules], + "^[A-Za-z0-9_'.]*$", + ); + } + if (at.kind === "field" || at.kind === "pipe") { + const type = typeOfOperand(at, source, env); + if (!type) return null; + return at.kind === "field" ? answer(fields(type, env)) : answer(pipes(type, env, statement), "^[A-Za-z0-9_'.]*$"); + } + if (at.partial === "" && !explicit) return null; + return answer(names(env, statement)); + } + + return { complete }; +} diff --git a/playground/src/engine.js b/playground/src/engine.js index efa263cbd6..0eea489f50 100644 --- a/playground/src/engine.js +++ b/playground/src/engine.js @@ -7,6 +7,9 @@ * in the Node smoke test (scripts/smoke.mjs). */ +import { CompilerCrash, createCompleter } from "./complete.js"; +import { formatException, formatValue, hideModules } from "./repl-format.js"; + export function moduleNameOf(filename) { const base = filename.split("/").pop(); const dot = base.lastIndexOf("."); @@ -93,6 +96,8 @@ export function createEngine(wasm, stdlib) { // Compiled JavaScript of the project, by module name. let projectJs = Object.create(null); let projectFiles = []; + // Counts the builds: what a completion found is of one build. + let projectVersion = 0; const javascriptOf = (name) => projectJs[name] ?? stdlib.javascript[name]; // The macro engine is this JavaScript engine: host.js gets the compiled @@ -145,7 +150,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); @@ -157,6 +162,7 @@ export function createEngine(wasm, stdlib) { } } projectFiles = files; + projectVersion += 1; projectJs = Object.create(null); macroCall({ kind: "reset" }); // Other files are what `Macro.readFile` reads. @@ -198,7 +204,218 @@ 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; + // 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 = { + // 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. + opens: [], + // The modules an input defined: `open` of one is not `open` of a file. + defined: new Set(), + loaded: Object.create(null), + // 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 + .filter((name) => results[name].type !== "success") + .map((name) => ({ file: name, message: results[name].message })), + }; + } + + 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.`); + const module = { exports: {} }; + loaded[name] = module; + try { + new Function("require", "exports", "module", "console", toCommonJs(source))( + (specifier) => replLoad(moduleNameOf(specifier)), + 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) { + 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; + session.files.push(name); + replLoad(name); + 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; + inputs += 1; + const name = `Repl${inputs}`; + current.files.push(name); + 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; + + 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)), + module.exports, + module, + current.console, + ); + } catch (error) { + 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 }; + } + current.printing = null; + 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); + current.scope.set(item.name, item); + 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); + if (note) output.push({ kind: "note", text: note }); + } + return { output, expanded: result.expanded ?? null, javascript: result.js }; } /** @@ -220,5 +437,68 @@ export function createEngine(wasm, stdlib) { build([]); } - return { build, warm }; + // ── Completion ──────────────────────────────────────────────────────────── + + const completer = createCompleter(wasm); + + /** + * What can be written at `offset`. In a session of the read-eval-print + * loop (`{mode: "repl", source, offset}`) the input sees the inputs before + * it; in a project (`{mode: "project", files, name, offset}`) the file + * `name` sees the files it depends on, which are compiled if they are not. + * Returns `{from, options, validFor}`, null, or `{crashed}`. + */ + function complete(request) { + try { + if (request.mode === "repl") { + if (!session) replStart([]); + const inputs = /^Repl\d+$/; + return completer.complete( + { + key: `repl/${projectVersion}/${session.opens.length}`, + opens: session.opens, + // What an `open` of an input opened. + opened: session.opens.filter((name) => !inputs.test(name)), + modules: projectFiles.filter((file) => isSourceFile(file.name)).map((file) => moduleNameOf(file.name)), + scope: [...session.scope.values()], + }, + request.source, + request.offset, + request.explicit, + ); + } + const { files, name } = request; + const built = + !session && + files.length === projectFiles.length && + files.every( + (file, index) => + file.name === projectFiles[index].name && (file.name === name || file.source === projectFiles[index].source), + ); + if (!built) { + replEnd(); + const outcome = build(files, { execute: false }); + if (outcome.crashed) return { crashed: outcome.crashed }; + } + const file = files.find((candidate) => candidate.name === name); + if (!file || !isSourceFile(name)) return null; + return completer.complete( + { + key: `project/${projectVersion}`, + opens: [], + opened: [], + modules: files.filter((other) => isSourceFile(other.name) && other.name !== name).map((other) => moduleNameOf(other.name)), + scope: [], + }, + file.source, + request.offset, + request.explicit, + ); + } catch (error) { + if (error instanceof CompilerCrash) return { crashed: error.message }; + throw error; + } + } + + return { build, warm, replStart, replEval, complete }; } 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; +} diff --git a/playground/src/rfc/CodeEditor.jsx b/playground/src/rfc/CodeEditor.jsx index 5acf34a9e6..b26a793b31 100644 --- a/playground/src/rfc/CodeEditor.jsx +++ b/playground/src/rfc/CodeEditor.jsx @@ -3,18 +3,20 @@ import { EditorState } from "@codemirror/state"; import { EditorView, keymap, drawSelection, highlightSpecialChars } from "@codemirror/view"; import { defaultKeymap, history, historyKeymap, indentWithTab } from "@codemirror/commands"; import { bracketMatching, indentOnInput, indentUnit, syntaxHighlighting } from "@codemirror/language"; -import { closeBrackets, closeBracketsKeymap } from "@codemirror/autocomplete"; +import { acceptCompletion, closeBrackets, closeBracketsKeymap } from "@codemirror/autocomplete"; import { classHighlighter } from "@lezer/highlight"; import { codemirrorLanguage } from "./highlight.jsx"; +import { completion } from "./completion.js"; /** * An editor for one file. The document is created from `value` once: the - * parent gives the editor a new `key` to replace it. + * parent gives the editor a new `key` to replace it. With `complete`, the + * editor offers completions. */ -export function CodeEditor({ value, language, onChange, onCursor, onFocus, viewRef }) { +export function CodeEditor({ value, language, onChange, onCursor, onFocus, complete, viewRef }) { const host = useRef(null); - const handlers = useRef({ onChange, onCursor, onFocus }); - handlers.current = { onChange, onCursor, onFocus }; + const handlers = useRef({ onChange, onCursor, onFocus, complete }); + handlers.current = { onChange, onCursor, onFocus, complete }; useEffect(() => { const languageExtension = codemirrorLanguage(language); @@ -33,7 +35,17 @@ export function CodeEditor({ value, language, onChange, onCursor, onFocus, viewR EditorState.tabSize.of(2), syntaxHighlighting(classHighlighter), languageExtension ? [languageExtension] : [], - keymap.of([...closeBracketsKeymap, ...defaultKeymap, ...historyKeymap, indentWithTab]), + // The compiler completes ReScript: `complete(source, offset, explicit)`. + language === "rescript" && complete + ? completion((...request) => handlers.current.complete?.(...request) ?? Promise.resolve(null)) + : [], + keymap.of([ + { key: "Tab", run: acceptCompletion }, + ...closeBracketsKeymap, + ...defaultKeymap, + ...historyKeymap, + indentWithTab, + ]), EditorView.updateListener.of((update) => { if (update.docChanged) handlers.current.onChange?.(update.state.doc.toString()); if (update.selectionSet || update.docChanged) { diff --git a/playground/src/rfc/Example.jsx b/playground/src/rfc/Example.jsx index 4ded4c1f09..05473b9cf6 100644 --- a/playground/src/rfc/Example.jsx +++ b/playground/src/rfc/Example.jsx @@ -2,7 +2,7 @@ import React, { useCallback, useEffect, useMemo, useRef, useState } from "react" import TreeView from "../TreeView.jsx"; import { isSourceFile } from "../engine.js"; import { encodeProject } from "../share.js"; -import { build as buildProject, compilerStatus, onCompilerStatus, warmUp } from "./compiler.js"; +import { build as buildProject, compilerStatus, complete as completeProject, onCompilerStatus, warmUp } from "./compiler.js"; import { CodeEditor, selectRange } from "./CodeEditor.jsx"; import { addedLines, Code, languageOf } from "./highlight.jsx"; @@ -165,6 +165,14 @@ export function Example({ example, prebuilt }) { onChange={edit} onCursor={setCursor} onFocus={warmUp} + complete={(source, offset, explicit) => + completeProject( + filesRef.current.map((file) => (file.name === activeFile.name ? { ...file, source } : file)), + activeFile.name, + offset, + explicit, + ) + } viewRef={editorView} /> 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..f6b7cb4bf6 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(() => { @@ -57,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; @@ -84,11 +96,12 @@ export function Page({ markdown, title, lede, pages, current }) { RFC + REPL Implementation Playground - + GitHub ↗ + )} + {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) => ( + + ))} +
+ + session.current.complete(source, offset, explicit)} + /> + +
+
+ +
+ 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 · 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 new file mode 100644 index 0000000000..2caa3cd22d --- /dev/null +++ b/playground/src/rfc/repl-session.js @@ -0,0 +1,132 @@ +/** + * 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; +const COMPLETION_LIMIT = 3_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 === "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") { + 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 }); + }); + }, + /** + * 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."); + }, + dispose() { + stop("The page was closed."); + }, + }; +} diff --git a/playground/src/rfc/rfc.css b/playground/src/rfc/rfc.css index b4f536c33b..a56ea035ee 100644 --- a/playground/src/rfc/rfc.css +++ b/playground/src/rfc/rfc.css @@ -154,6 +154,7 @@ select { .topbar nav a { text-decoration: none; + white-space: nowrap; padding: 4px 0; border-bottom: 1px solid transparent; } @@ -241,6 +242,12 @@ select { white-space: nowrap; } +.chip.lime { + background: var(--lime); + color: #18201d; + border-color: transparent; +} + .chip.solid { background: var(--ink); color: var(--paper); @@ -825,6 +832,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; @@ -863,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; @@ -1237,6 +1533,11 @@ td:first-child { font-size: 12px; } + /* The pull request is linked below the title too. */ + .topbar nav a.away { + display: none; + } + .brand span { display: none; } @@ -1271,6 +1572,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 {