diff --git a/docs/getting-started.md b/docs/getting-started.md index 589798632..c543b185c 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -242,7 +242,7 @@ The `--watch` / `-w` flag works with `run`, `check`, `disasm`, and `test` to re- `silt check` reports what is wrong with the whole file: a declaration that does not parse is one error, and the declarations behind it are read and checked all the same, as is the text behind a character that belongs to no token. At most fifty syntax errors of a file are shown, with a count of the rest. A file that ends inside a string or a `{- -}` comment that is not closed reports that and nothing else. A file with a syntax error is never run or formatted. -`silt repl` checks each input as `silt check` checks a file, and runs it. It sees the directory it was started in as a script does: `import shapes` loads `shapes.silt` beside it, or `src/shapes.silt` and the dependencies of the package there. An input sees what the inputs before it define; an input with an error is dropped and changes nothing. Defining a function or a `let` again makes a new definition for the inputs after it: code from earlier inputs keeps the definition it was written against. Errors are shown at `:line:col`, the `n`th input. A module is read the first time an input imports it and kept for the session: edits to its file are seen after a restart. In a package, the REPL updates `silt.lock` as `silt run` does. +`silt repl` checks each input as `silt check` checks a file, and runs it. It sees the directory it was started in as a script does: `import shapes` loads `shapes.silt` beside it, or `src/shapes.silt` and the dependencies of the package there. An input sees what the inputs before it define; an input with an error is dropped and changes nothing. Defining a function or a `let` again makes a new definition for the inputs after it: code from earlier inputs keeps the definition it was written against. Errors are shown at `:line:col`, the `n`th input. A module is read the first time an input imports it and kept for the session: edits to its file are seen after a restart. In a package, the REPL updates `silt.lock` as `silt run` does. `:type ` shows the type of an expression without running it (`:type Some` is `Fn(a) -> Option(a)`; its expression is checked as an input, and counts as one), and `:doc ` what a builtin is: a function's signature, the declaration of a type, a trait or a variant's enum, with what its docs say first, or all a module declares (`:doc list.map`, `:doc Option`, `:doc string`); `:help` lists the commands. ### Staying up to date diff --git a/docs/stdlib/globals.md b/docs/stdlib/globals.md index f8ac3cabb..7911485fa 100644 --- a/docs/stdlib/globals.md +++ b/docs/stdlib/globals.md @@ -14,7 +14,7 @@ No import or qualification needed. |------|-----------|-------------| | `print` | `(a) -> () where a: Display` | Print a value without trailing newline | | `println` | `(a) -> () where a: Display` | Print a value with trailing newline | -| `panic` | `(a) -> b where a: Display` | Crash with an error message | +| `panic` | `(a) -> Never where a: Display` | Crash with an error message | | `Ok` | `(a) -> Result(a, e)` | Construct a success Result | | `Err` | `(e) -> Result(a, e)` | Construct an error Result | | `Some` | `(a) -> Option(a)` | Construct a present Option | @@ -108,12 +108,15 @@ fn main() { ## `panic` ``` -panic(value: a) -> b where a: Display +panic(message: a) -> Never where a: Display ``` Terminates execution with an error message. Accepts any value that implements -`Display`. The return type is polymorphic because `panic` never returns -- it -can appear anywhere a value is expected. +`Display`. It never returns: its result is of type `Never`, the type of an expression +that does not return (`return`, `loop(...)`), which goes with every type, so +`panic` can stand wherever a value is expected and ends an `else` block that +must leave. `Never` is not written in an annotation (see [the Never +type](../language/error-handling.md#never-type)). ```silt -- noexec diff --git a/src/builtins/registry/docs.rs b/src/builtins/registry/docs.rs index 376a8a0b6..3a0be5504 100644 --- a/src/builtins/registry/docs.rs +++ b/src/builtins/registry/docs.rs @@ -10,7 +10,10 @@ //! (`## \`list.map\``); //! - in a table whose second column is headed `Type argument`, that //! cell of each decoding builtin's row: what its type argument may be -//! ([`Decoding::type_arguments`](super::Decoding::type_arguments)). +//! ([`Decoding::type_arguments`](super::Decoding::type_arguments)); +//! - on a page that is no module's (`globals.md`), the same of the +//! prelude's functions: their rows of a table of functions, which +//! lists all of them, and the signature blocks of their sections. //! //! `tests/meta/stdlib_reference_tests.rs` renders every page and //! compares it with the file (`SILT_BLESS=1` rewrites the files). @@ -372,6 +375,263 @@ pub fn signature_block(module: &str, name: &str) -> Option { Some(section_signature(module, row)) } +// ── Declarations, as the language card and the REPL's `:doc` write them + +/// The lines that state the module `module`: its types and traits as +/// declarations (without `pub`), its opaque types, then each function +/// and constant in the order of their names, as its signature block +/// writes it; a row of a cargo feature beyond its module's says so. +pub fn module_lines(module: &Module) -> Vec { + let mut lines = declarations(module.types); + lines.extend(declarations(module.traits)); + lines.extend((module.opaque.iter()).map(|(name, arity)| opaque_line(name, *arity))); + let mut rows: Vec<&Row> = module.rows.iter().collect(); + rows.sort_by_key(|row| row.name); + lines.extend(rows.into_iter().map(|row| { + let line = section_signature(module, row); + match row.feature { + Some(feature) => format!("{line} -- cargo feature `{feature}`"), + None => line, + } + })); + lines +} + +/// The lines that state the prelude: its types, its opaque types and +/// its functions, as [`module_lines`] writes a module's. +pub fn prelude_lines() -> Vec { + let mut lines = declarations(super::PRELUDE_TYPES); + lines.extend( + (super::PRELUDE_OPAQUE.iter()) + .filter(|(name, _)| *name != crate::defs::TYPE_OF) + .map(|(name, arity)| opaque_line(name, *arity)), + ); + let mut rows: Vec<&Row> = registry().prelude.iter().collect(); + rows.sort_by_key(|row| row.name); + lines.extend(rows.into_iter().map(prelude_signature)); + lines +} + +/// The signature block of a function of the prelude: `println(value: +/// a) -> () where a: Display`. +fn prelude_signature(row: &Row) -> String { + row.signature.trim_start_matches("fn ").to_string() +} + +/// The declarations of a module's text of types or traits, one a line, +/// without `pub`. +fn declarations(text: &str) -> Vec { + (text.lines()) + .map(|line| line.trim().trim_start_matches("pub ").to_string()) + .filter(|line| !line.is_empty()) + .collect() +} + +/// The line of an opaque type: `type Handle(a) -- opaque`, a type +/// whose values only the module's functions make and take. +fn opaque_line(name: &str, arity: usize) -> String { + let params: Vec = (b'a'..) + .take(arity) + .map(|c| char::from(c).to_string()) + .collect(); + match params.is_empty() { + true => format!("type {name} -- opaque"), + false => format!("type {name}({}) -- opaque", params.join(", ")), + } +} + +/// The line among `lines` that declares `keyword name`: `type Value { +/// ... }` for `("type", "Value")`, also `type Handle(a) -- opaque`. +fn declaring<'a>(lines: &'a [String], keyword: &str, name: &str) -> Option<&'a String> { + lines.iter().find(|line| { + line.strip_prefix(keyword) + .and_then(|rest| rest.strip_prefix(' ')) + .and_then(|rest| rest.strip_prefix(name)) + .is_some_and(|rest| matches!(rest.chars().next(), None | Some(' ' | '(' | ':'))) + }) +} + +/// The lines of the module part of `qualified` (`json` of +/// `json.Value`), or the prelude's for a bare name, with the name +/// after the module. +fn lines_of(qualified: &str) -> Option<(Vec, &str)> { + match qualified.split_once('.') { + Some((module, name)) => Some((module_lines(registry().module(module)?), name)), + None => Some((prelude_lines(), qualified)), + } +} + +/// The declaration of the builtin type `name` as [`module_lines`] +/// writes it: a type of the prelude by its bare name (`Option`), a +/// module's with its module (`json.Value`, `task.Handle`). +pub fn type_line(name: &str) -> Option { + let (lines, name) = lines_of(name)?; + declaring(&lines, "type", name).cloned() +} + +/// The declaration of the builtin trait `name`: a trait of a module +/// as its module states it (`json.Encode`), one of the prelude +/// (`Display`) as the checker declares it, on one line. +pub fn trait_line(name: &str) -> Option { + if name.contains('.') { + let (lines, name) = lines_of(name)?; + return declaring(&lines, "trait", name).cloned(); + } + let decl = (crate::typechecker::builtin_trait_decls().into_iter()) + .find(|t| crate::intern::resolve(t.name) == name)?; + Some(trait_text(&decl)) +} + +/// What the documentation of the prelude's trait `name` says first: its +/// first sentence. +pub fn prelude_trait_summary(name: &str) -> Option { + let decl = (crate::typechecker::builtin_trait_decls().into_iter()) + .find(|t| crate::intern::resolve(t.name) == name)?; + summary(decl.doc.as_deref()?) +} + +/// `trait Compare: Equal { fn compare(self, other: Self) -> Int }`. +fn trait_text(decl: &crate::ast::TraitDecl) -> String { + use crate::ast::{PatternKind, TypeExpr, TypeExprKind}; + fn ty(te: &TypeExpr) -> String { + let all = |types: &[TypeExpr]| types.iter().map(ty).collect::>().join(", "); + match &te.kind { + TypeExprKind::Named { name, .. } => crate::intern::resolve(*name), + TypeExprKind::Generic { name, args, .. } => { + format!("{}({})", crate::intern::resolve(*name), all(args)) + } + TypeExprKind::Tuple(elems) => format!("({})", all(elems)), + TypeExprKind::Function(params, ret) => format!("Fn({}) -> {}", all(params), ty(ret)), + TypeExprKind::SelfType => "Self".to_string(), + _ => "_".to_string(), + } + } + let mut header = format!("trait {}", decl.name); + if !decl.supertraits.is_empty() { + let supers: Vec = (decl.supertraits.iter()) + .map(|s| crate::intern::resolve(s.name)) + .collect(); + header.push_str(&format!(": {}", supers.join(" + "))); + } + let methods: Vec = (decl.methods.iter()) + .map(|f| { + let params: Vec = (f.params.iter()) + .map(|p| { + let name = match &p.pattern.kind { + PatternKind::Ident(name) => crate::intern::resolve(*name), + _ => "_".to_string(), + }; + match &p.ty { + Some(t) => format!("{name}: {}", ty(t)), + None => name, + } + }) + .collect(); + let ret = f.return_type.as_ref().map_or("()".to_string(), ty); + format!("fn {}({}) -> {ret}", f.name, params.join(", ")) + }) + .collect(); + match methods.is_empty() { + true => format!("{header} {{}}"), + false => format!("{header} {{ {} }}", methods.join("; ")), + } +} + +/// The enum the builtin variant `name` is of, as [`type_line`] writes +/// it, and its name as [`type_line`] takes it: a variant of the prelude +/// by its bare name (`Some`), a module's with its module +/// (`channel.Message`) or with its module and its enum +/// (`time.Weekday.Monday`). +pub fn variant_enum(name: &str) -> Option<(String, String)> { + let registry = registry(); + let (module, ty, variant) = match name.split('.').collect::>()[..] { + [variant] => (None, None, variant), + [module, variant] => (Some(module), None, variant), + [module, ty, variant] => (Some(module), Some(ty), variant), + _ => return None, + }; + let decls = match module { + Some(module) => ®istry.module(module)?.type_decls, + None => ®istry.prelude_types, + }; + let decl = (decls.iter()) + .filter(|decl| ty.is_none_or(|ty| decl.name == ty)) + .find(|decl| decl.variants().iter().any(|(v, _)| *v == variant))?; + let name = match module { + Some(module) => format!("{module}.{}", decl.name), + None => decl.name.to_string(), + }; + Some((type_line(&name)?, name)) +} + +/// The summary of the builtin type `name` (`json.Value`): the first +/// sentence of what documents it ([`type_docs`]). +pub fn type_summary(name: &str) -> Option { + summary(type_docs().get(name)?) +} + +/// The summary of the variant `variant` of the builtin enum `ty` +/// (`io.IoError`, `NotFound`) where its docs are a table of the +/// variants (an error enum's): the last cell of its row. +pub fn variant_meaning(ty: &str, variant: &str) -> Option { + let body = type_docs().get(ty)?; + body.lines().find_map(|line| { + let cells = table_cells(line)?; + let first = cells.first()?.trim_matches('`'); + let name = first.split_once('(').map_or(first, |(name, _)| name); + (name == variant && cells.len() >= 2).then(|| cells[cells.len() - 1].clone()) + }) +} + +/// The summary of `key` from its own section of a reference page +/// (`## \`json.Value\``, `## \`Some\``): the first sentence below the +/// section's signature block. +pub fn section_summary(key: &str) -> Option { + (pages().into_iter()) + .flat_map(|(_, page)| iter_sections(page)) + .find(|(keys, _)| keys.iter().any(|k| k == key)) + .and_then(|(_, body)| summary(&body)) +} + +/// The first sentence of the prose of `text`, past its code blocks, +/// headings and tables, on one line; a sentence that only says whose +/// variant a name is and how to write it (`A variant of \`channel\`: +/// write \`channel.Closed\`.`) does not count. +fn summary(text: &str) -> Option { + let mut paragraphs: Vec = Vec::new(); + let mut current: Vec<&str> = Vec::new(); + let mut fence = false; + for line in text.lines() { + let fence_line = line.trim_start().starts_with("```"); + fence ^= fence_line; + let prose = + !fence_line && !fence && !line.trim().is_empty() && !line.starts_with(['#', '|']); + if prose { + current.extend(line.split_whitespace()); + } else if !current.is_empty() { + paragraphs.push(current.join(" ")); + current.clear(); + } + } + if !current.is_empty() { + paragraphs.push(current.join(" ")); + } + paragraphs.iter().find_map(|paragraph| { + let mut rest = paragraph.as_str(); + while !rest.is_empty() { + let (sentence, after) = match rest.find(". ") { + Some(end) => (&rest[..=end], &rest[end + 2..]), + None => (rest, ""), + }; + if !sentence.starts_with("A variant of `") { + return Some(sentence.to_string()); + } + rest = after; + } + None + }) +} + /// The module whose part of a page a `# ` heading opens (`# postgres /// (opt-in feature)`), if it opens one. fn heading_module(line: &str) -> Option<&'static Module> { @@ -421,9 +681,13 @@ pub fn render_page(page: &str) -> Result> { let mut listed: HashSet<(&str, &str)> = HashSet::new(); let mut listed_decoders: HashSet<(&str, &str)> = HashSet::new(); let mut modules: Vec<&'static Module> = Vec::new(); - // The row whose section has just opened: its signature block is - // the first fence, if a plain one comes before any prose. - let mut pending: Option<(&'static Module, &'static Row)> = None; + // The functions of the prelude a table lists, on a page that is no + // module's (`globals.md`). + let mut listed_prelude: HashSet<&str> = HashSet::new(); + // The row whose section has just opened (of a module, or of the + // prelude): its signature block is the first fence, if a plain one + // comes before any prose. + let mut pending: Option<(Option<&'static Module>, &'static Row)> = None; let mut replacing = false; for line in page.lines() { if replacing { @@ -439,7 +703,10 @@ pub fn render_page(page: &str) -> Result> { && line.trim() == "```" { out.push(line.to_string()); - out.push(section_signature(m, row)); + out.push(match m { + Some(m) => section_signature(m, row), + None => prelude_signature(row), + }); replacing = true; continue; } @@ -471,13 +738,18 @@ pub fn render_page(page: &str) -> Result> { return None; }; // `## \`list.map\``, or the bare `## \`map\`` in the - // part of the page that is the module's. - let (m, f) = match key.split_once('.') { - Some((m, f)) => (registry().module(m)?, f), - None => (module?, key.as_str()), + // part of the page that is the module's; `## \`println\`` + // in no module's part. + let (m, f) = match (key.split_once('.'), module) { + (Some((m, f)), _) => (registry().module(m)?, f), + (None, Some(m)) => (m, key.as_str()), + (None, None) => { + let row = registry().prelude.iter().find(|row| row.name == *key)?; + return Some((None, row)); + } }; let row = m.rows.iter().find(|row| row.name == f)?; - Some((m, row)) + Some((Some(m), row)) }); } else if !line.trim().is_empty() { pending = None; @@ -508,6 +780,24 @@ pub fn render_page(page: &str) -> Result> { )), } } + if in_summary + && module.is_none() + && let Some(cells) = table_cells(line) + && let Some(name) = cells[0].strip_prefix('`').and_then(|c| c.strip_suffix('`')) + && let Some(row) = registry().prelude.iter().find(|row| row.name == name) + { + listed_prelude.insert(row.name); + let mut cells = cells.clone(); + if cells.len() >= 2 { + cells[1] = format!("`{}`", summary_signature(row)); + } + if cells.len() >= 3 { + let last = cells.len() - 1; + cells[last] = row.summary.to_string(); + } + out.push(format!("| {} |", cells.join(" | "))); + continue; + } if in_type_arguments && let Some(m) = module && let Some(cells) = table_cells(line) @@ -531,6 +821,13 @@ pub fn render_page(page: &str) -> Result> { } out.push(line.to_string()); } + if !listed_prelude.is_empty() { + for row in ®istry().prelude { + if !listed_prelude.contains(row.name) { + problems.push(format!("no table of the page lists `{}`", row.name)); + } + } + } for m in modules { for row in &m.rows { if !listed.contains(&(m.name, row.name)) { @@ -750,4 +1047,38 @@ mod tests { assert!(files.contains(&"int-float.md".to_string()), "{files:?}"); assert!(files.contains(&"io-fs.md".to_string()), "{files:?}"); } + + /// On a page that is no module's, the prelude's functions are + /// written from their rows: a table's signature and summary cells, + /// a section's signature block; a table that lists some of them + /// lists all of them. + #[test] + fn the_prelude_s_functions_are_written_from_the_rows() { + let page = "# Globals\n\n| Name | Signature | Description |\n|---|---|---|\n\ + | `print` | `stale` | stale |\n| `println` | `stale` | stale |\n\ + | `panic` | `stale` | stale |\n| `Ok` | `(a) -> Result(a, e)` | kept |\n\n\ + ## `panic`\n\n```\nstale\n```\n"; + let page = render_page(page).expect("a page"); + assert!( + page.contains( + "| `println` | `(a) -> () where a: Display` | Print a value with trailing newline |" + ), + "{page}" + ); + assert!( + page.contains("| `Ok` | `(a) -> Result(a, e)` | kept |"), + "{page}" + ); + assert!( + page.contains("```\npanic(message: a) -> Never where a: Display\n```"), + "{page}" + ); + let problems = + render_page("| Name | Signature | Description |\n|---|---|---|\n| `print` | x | y |\n") + .expect_err("problems"); + assert!( + problems.contains(&"no table of the page lists `println`".to_string()), + "{problems:?}" + ); + } } diff --git a/src/builtins/registry/modules.rs b/src/builtins/registry/modules.rs index 6909360d1..aa34ccf2e 100644 --- a/src/builtins/registry/modules.rs +++ b/src/builtins/registry/modules.rs @@ -26,17 +26,17 @@ pub(super) fn prelude() -> Vec { vec![ f( "fn print(value: a) -> () where a: Display", - "Write a value to stdout", + "Print a value without trailing newline", prelude::print, ), f( "fn println(value: a) -> () where a: Display", - "Write a value and a newline to stdout", + "Print a value with trailing newline", prelude::println, ), f( "fn panic(message: a) -> Never where a: Display", - "Stop the program with an error", + "Crash with an error message", prelude::panic, ), ] diff --git a/src/repl.rs b/src/repl.rs index 4508e760c..77c82ce4b 100644 --- a/src/repl.rs +++ b/src/repl.rs @@ -1,4 +1,5 @@ use std::cell::RefCell; +use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::rc::Rc; @@ -10,6 +11,7 @@ use rustyline::history::DefaultHistory; use rustyline::validate::Validator; use rustyline::{Context, Editor, Helper}; +use crate::builtins::registry::docs::signature_block; use crate::defs::DefTable; use crate::diagnostic::{Diagnostic, Located, SourceView, render_human}; use crate::intern; @@ -17,6 +19,7 @@ use crate::lexer::Lexer; use crate::session::{Config, Entry, LockPolicy, ModuleId, ProjectSetup, Session}; use crate::source::{FileId, SourceMap, SourceName, Span}; use crate::typechecker::names::{Binding, Exports, ModuleScope}; +use crate::types::{Pred, RigidId, Scheme, TyVar, Type, free_vars_in, substitute_vars}; use crate::value::Value; use crate::vm::Vm; @@ -171,6 +174,9 @@ pub fn run_repl() { // string or a block comment of it is (not because a line ended in // an operator). let mut delimiter_open = false; + // Whether the entry being read is the expression of a `:type` + // command, which more lines can finish as they can any entry. + let mut typing = false; loop { let prompt = if buffer.is_empty() { @@ -184,7 +190,7 @@ pub fn run_repl() { // back before the process ends.) match crate::scheduler::unwinding(|| rl.readline(prompt)) { Ok(line) => { - let line = line.trim_end(); + let mut line = line.trim_end(); if buffer.is_empty() { match line.trim() { @@ -194,6 +200,19 @@ pub fn run_repl() { continue; } "" => continue, + other if command(other, ":type") == Some("") => { + show_type(&mut rl, &mut repl.borrow_mut(), ""); + continue; + } + other if command(other, ":type").is_some() => { + typing = true; + line = command(other, ":type").unwrap_or_default(); + } + other if command(other, ":doc").is_some() => { + let _ = rl.add_history_entry(other); + show_doc(command(other, ":doc").unwrap_or_default()); + continue; + } other if other.starts_with(':') && !other.starts_with("::") => { crate::scheduler::report(|| { eprintln!("unknown REPL command '{other}'; type :help for the list") @@ -231,18 +250,25 @@ pub fn run_repl() { } let input = std::mem::take(&mut buffer); - evaluate(&mut rl, &mut repl.borrow_mut(), input.trim()); + match std::mem::take(&mut typing) { + true => show_type(&mut rl, &mut repl.borrow_mut(), input.trim()), + false => evaluate(&mut rl, &mut repl.borrow_mut(), input.trim()), + } } Err(ReadlineError::Interrupted) => { buffer.clear(); delimiter_open = false; + typing = false; println!("^C"); } // The input ends: an entry that was still being read is - // evaluated as it is, and says what it lacks. + // evaluated (or typed) as it is, and says what it lacks. Err(ReadlineError::Eof) => { let input = std::mem::take(&mut buffer); - evaluate(&mut rl, &mut repl.borrow_mut(), input.trim()); + match typing { + true => show_type(&mut rl, &mut repl.borrow_mut(), input.trim()), + false => evaluate(&mut rl, &mut repl.borrow_mut(), input.trim()), + } break; } Err(err) => { @@ -262,6 +288,49 @@ pub fn run_repl() { } } +/// What follows the command `name` on the line `line` (`:type 1 + 2` +/// for `:type`: `1 + 2`), if the line is that command. +fn command<'a>(line: &'a str, name: &str) -> Option<&'a str> { + let rest = line.strip_prefix(name)?; + match rest.chars().next() { + None => Some(""), + Some(c) if c.is_whitespace() => Some(rest.trim()), + Some(_) => None, + } +} + +/// `:type input`: the diagnostics of the expression `input` and its +/// type. +fn show_type(rl: &mut Editor, repl: &mut Repl, input: &str) { + let _ = rl.add_history_entry(format!(":type {input}").trim_end()); + if input.is_empty() { + crate::scheduler::report(|| eprintln!(":type needs an expression, as in :type [1, 2]")); + return; + } + let Ok(typed) = repl.type_of(input) else { + crate::scheduler::report(|| eprintln!(":type takes an expression, not a declaration")); + return; + }; + let errors: Vec = typed.diagnostics.iter().map(|d| repl.render(d)).collect(); + crate::scheduler::report(|| { + for error in &errors { + eprintln!("{error}"); + } + if let Some(ty) = &typed.ty { + println!("{ty}"); + } + }); +} + +/// `:doc name`: what [`doc_text`] says of the builtin `name`. +fn show_doc(name: &str) { + crate::scheduler::report(|| match (name, doc_text(name)) { + ("", _) => eprintln!(":doc needs a name, as in :doc list.map"), + (_, Some(text)) => println!("{text}"), + (_, None) => eprintln!("no builtin named '{name}'"), + }); +} + /// Evaluate the entry `input`, and show its diagnostics and its value. fn evaluate(rl: &mut Editor, repl: &mut Repl, input: &str) { if input.is_empty() { @@ -288,6 +357,157 @@ fn evaluate(rl: &mut Editor, repl: &mut Repl, input: }); } +/// What `:type` found: the diagnostics of the expression, warnings too, +/// and its type, when it has no error. +pub struct Typed { + pub diagnostics: Vec, + pub ty: Option, +} + +/// `:type` was given declarations, not an expression. +#[derive(Debug)] +pub struct NotAnExpression; + +/// The type `scheme` stands for as `:type` writes it: its type variables +/// as letters, in the order they first appear, and what it asks of them +/// (`Fn(List(a)) -> List(a) where a: Compare`), the bounds of one +/// variable joined by `+` as the reference pages write them (`where a: +/// Equal + Display`). A variable the scheme does not quantify is `_`, as +/// in a diagnostic. +pub fn written_scheme(scheme: &Scheme) -> String { + let letters: HashMap = free_vars_in(&scheme.ty) + .into_iter() + .filter(|var| scheme.vars.contains(var)) + .zip(b'a'..=b'z') + .map(|(var, letter)| { + let name = intern::intern(&char::from(letter).to_string()); + (var, Type::Rigid(RigidId { var, name })) + }) + .collect(); + let mut text = substitute_vars(&scheme.ty, &letters).to_string(); + // Each lettered variable's bounds, in the order of the letters. + let mut bounds: Vec<(String, Vec)> = Vec::new(); + for pred in &scheme.preds { + let Pred::Trait { + tr, args, subject, .. + } = pred + else { + continue; + }; + let subject = substitute_vars(subject, &letters); + if !matches!(subject, Type::Rigid(_)) { + continue; + } + let mut bound = tr.to_string(); + if !args.is_empty() { + let args: Vec = (args.iter()) + .map(|arg| substitute_vars(arg, &letters).to_string()) + .collect(); + bound.push_str(&format!("({})", args.join(", "))); + } + let subject = subject.to_string(); + match bounds.iter_mut().find(|(s, _)| *s == subject) { + Some((_, traits)) if traits.contains(&bound) => {} + Some((_, traits)) => traits.push(bound), + None => bounds.push((subject, vec![bound])), + } + } + bounds.sort_by(|(a, _), (b, _)| a.cmp(b)); + if !bounds.is_empty() { + let bounds: Vec = (bounds.iter()) + .map(|(subject, traits)| format!("{subject}: {}", traits.join(" + "))) + .collect(); + text.push_str(&format!(" where {}", bounds.join(", "))); + } + text +} + +/// What `:doc name` shows of the builtin `name`, a line that states it +/// and, where the docs have one, a line that says what it is: +/// - a function or a constant: its signature and its summary; +/// - a module (`string`): its types, traits and opaque types, then the +/// signature of each of its functions, in the order of their names; +/// - a type (`Option`, `json.Value`) or a trait (`Display`, +/// `json.Encode`): its declaration, as the language card writes it, +/// and the first paragraph of its section of the reference pages; +/// - a variant (`Some`, `channel.Message`): the declaration of its +/// enum, and the first paragraph of its section, or else its enum's; +/// - a type of the language (`Int`, `List`): its name and arguments, +/// and what the page of its module says first. +/// +/// Of a function or a module whose cargo feature is not built, it also +/// says what it needs. `None` when no builtin has the name. +pub fn doc_text(name: &str) -> Option { + use crate::builtins::registry::docs; + let registry = crate::builtins::registry::registry(); + let with_summary = |line: String, summary: Option| match summary { + Some(summary) => format!("{line}\n{summary}"), + None => line, + }; + if let Some(module) = registry.module(name) { + let mut text = docs::module_lines(module).join("\n"); + if let Some(feature) = module.feature.filter(|_| !module.enabled) { + let needs = crate::module::needs_feature(&format!("`{name}`"), feature); + text.push_str(&format!("\n{needs}")); + } + return Some(text); + } + let row = match name.split_once('.') { + Some((module, function)) => (registry.module(module)) + .and_then(|m| m.rows.iter().find(|row| row.name == function)) + .and_then(|row| Some((signature_block(module, function)?, row))), + None => (registry.prelude.iter()) + .find(|row| row.name == name) + .map(|row| (row.signature.trim_start_matches("fn ").to_string(), row)), + }; + if let Some((signature, row)) = row { + let mut text = format!("{signature}\n{}", row.summary); + if !row.enabled { + let module = registry.module(row.module); + let feature = match module.is_some_and(|m| !m.enabled) { + true => module.and_then(|m| m.feature), + false => row.feature, + }; + if let Some(feature) = feature { + let needs = crate::module::needs_feature(&format!("`{name}`"), feature); + text.push_str(&format!("\n{needs}")); + } + } + return Some(text); + } + if let Some(line) = docs::type_line(name) { + return Some(with_summary(line, docs::type_summary(name))); + } + if let Some(line) = docs::trait_line(name) { + let summary = match name.contains('.') { + true => docs::section_summary(name), + false => docs::prelude_trait_summary(name), + }; + return Some(with_summary(line, summary)); + } + if let Some((line, enum_name)) = docs::variant_enum(name) { + let variant = name.rsplit('.').next().unwrap_or(name); + let summary = (docs::section_summary(name)) + .or_else(|| docs::variant_meaning(&enum_name, variant)) + .or_else(|| docs::type_summary(&enum_name)); + return Some(with_summary(line, summary)); + } + let builtin = (crate::types::builtins::BUILTIN_TYPES.iter()) + .find(|t| t.name == name && t.name != "Unit" && t.name.chars().all(char::is_alphabetic))?; + let params: Vec = (b'a'..) + .take(builtin.arity? as usize) + .map(|c| char::from(c).to_string()) + .collect(); + let line = match params.is_empty() { + true => format!("type {name} -- builtin"), + false => format!("type {name}({}) -- builtin", params.join(", ")), + }; + let summary = docs::module_docs() + .get(name.to_lowercase().as_str()) + .cloned(); + Some(with_summary(line, summary)) +} + /// A REPL session: one compilation session, to which each input is /// added as a cell of its own (``), and the VM that runs the /// cells. A cell sees what the cells before it that ran define; a cell @@ -377,6 +597,30 @@ impl Repl { evaluation } + /// What `:type input` shows: `input` checked as the next entry, and + /// the type of its value if it has no error. The entry is not run, + /// and no later entry sees it. `Err` when it is declarations, which + /// have no value. + pub fn type_of(&mut self, input: &str) -> Result { + let file = self.session.add_cell(input.to_string()); + let analysis = self.session.analyze(file); + let diagnostics = analysis.diagnostics.clone(); + if analysis.has_errors() { + return Ok(Typed { + diagnostics, + ty: None, + }); + } + let scheme = self + .session + .cell_value_scheme(file) + .ok_or(NotAnExpression)?; + Ok(Typed { + diagnostics, + ty: Some(written_scheme(&scheme)), + }) + } + /// The names `` offers now: those of [`builtin_names`], and /// every name the next input sees of the inputs that ran (see /// [`scope_completion_names`]). An input that did not run to its @@ -478,7 +722,7 @@ fn report_task_failures(repl: &Repl) { /// keywords and the prelude's names. A builtin module's members are /// offered once it is imported (see [`scope_completion_names`]). pub fn builtin_names() -> Vec { - let mut names: Vec = vec![":quit", ":q", ":help", ":h"] + let mut names: Vec = vec![":quit", ":q", ":help", ":h", ":type", ":doc"] .into_iter() .map(String::from) .collect(); @@ -566,9 +810,11 @@ pub fn scope_completion_names<'a>( fn print_help() { println!("Commands:"); - println!(" :help, :h Show this help"); - println!(" :quit, :q Exit the REPL"); - println!(" Autocomplete builtins and user-defined names"); + println!(" :help, :h Show this help"); + println!(" :quit, :q Exit the REPL"); + println!(" :type Show the type of an expression without running it"); + println!(" :doc Show a builtin's signature and summary (list.map, Option, string)"); + println!(" Autocomplete builtins and user-defined names"); println!(); println!("Enter expressions to evaluate, or declarations (fn, type, trait, import)."); println!( @@ -796,6 +1042,19 @@ mod tests { .collect() } + /// `:type` checks its input as the next entry, but does not run it, + /// and no later entry sees what it declares. + #[test] + fn a_typed_entry_is_not_run_and_binds_nothing() { + let mut repl = repl(); + value(&mut repl, "let n = 1"); + let typed = repl.type_of("n + 1").expect("an expression"); + assert_eq!(typed.ty.as_deref(), Some("Int")); + assert!(repl.type_of("fn f() { 1 }").is_err()); + assert_eq!(errors(&mut repl, "f()"), ["undefined variable 'f'"]); + assert_eq!(value(&mut repl, "n"), "1"); + } + #[test] fn eval_simple_values() { let mut repl = repl(); diff --git a/src/session/mod.rs b/src/session/mod.rs index b9e857347..bab19b096 100644 --- a/src/session/mod.rs +++ b/src/session/mod.rs @@ -410,6 +410,24 @@ impl Session { self.analyses.get(&id) } + /// The type of the value of the REPL cell `file`, once + /// [`Session::analyze`] has checked it: what the function that holds + /// its statements returns, general in what the statements leave + /// open, with what its scheme asks of those variables. `None` for a + /// cell of declarations. + pub fn cell_value_scheme(&self, file: FileId) -> Option { + let id = self.module_of(file); + let wrapper = intern(&self.cells.info.get(&id)?.wrapper()); + let names::Binding::Def(def) = self.analyses.get(&id)?.scope.values.get(&wrapper)? else { + return None; + }; + let scheme = self.tables.scheme_of(*def)?; + let Type::Fun(_, ret) = scheme.ty else { + return None; + }; + Some(crate::types::Scheme { ty: *ret, ..scheme }) + } + /// The analysis of the entry file `entry`: its module graph is /// completed, and each module that is not checked yet is checked, /// in the order of the graph. Asked again with nothing changed, it is diff --git a/tests/cli/repl_keyword_parity_with_lexer_tests.rs b/tests/cli/repl_keyword_parity_with_lexer_tests.rs index aa708bf82..fe879c819 100644 --- a/tests/cli/repl_keyword_parity_with_lexer_tests.rs +++ b/tests/cli/repl_keyword_parity_with_lexer_tests.rs @@ -34,7 +34,7 @@ fn repl_builtin_names_is_superset_of_lexer_keywords() { fn repl_includes_short_commands() { let names: std::collections::HashSet = silt::repl::builtin_names().into_iter().collect(); - for short in &[":quit", ":q", ":help", ":h"] { + for short in &[":quit", ":q", ":help", ":h", ":type", ":doc"] { assert!(names.contains(*short)); } } diff --git a/tests/golden/cli/repl/repl__a_line_that_ends_in_an_operator_goes_on.stdout b/tests/golden/cli/repl/repl__a_line_that_ends_in_an_operator_goes_on.stdout index 5ae8fab4b..3316588f7 100644 --- a/tests/golden/cli/repl/repl__a_line_that_ends_in_an_operator_goes_on.stdout +++ b/tests/golden/cli/repl/repl__a_line_that_ends_in_an_operator_goes_on.stdout @@ -6,9 +6,11 @@ x true [1, 2, 3] Commands: - :help, :h Show this help - :quit, :q Exit the REPL - Autocomplete builtins and user-defined names + :help, :h Show this help + :quit, :q Exit the REPL + :type Show the type of an expression without running it + :doc Show a builtin's signature and summary (list.map, Option, string) + Autocomplete builtins and user-defined names Enter expressions to evaluate, or declarations (fn, type, trait, import). Multi-line input: an open brace, paren, bracket, string or block comment, or a line that ends in an operator (+, |>, =, -> ...), continues on the next line. diff --git a/tests/golden/cli/repl/repl__help_command.stdout b/tests/golden/cli/repl/repl__help_command.stdout index 4f28e5f74..0695460f4 100644 --- a/tests/golden/cli/repl/repl__help_command.stdout +++ b/tests/golden/cli/repl/repl__help_command.stdout @@ -1,8 +1,10 @@ Silt REPL (type :quit to exit, :help for commands) Commands: - :help, :h Show this help - :quit, :q Exit the REPL - Autocomplete builtins and user-defined names + :help, :h Show this help + :quit, :q Exit the REPL + :type Show the type of an expression without running it + :doc Show a builtin's signature and summary (list.map, Option, string) + Autocomplete builtins and user-defined names Enter expressions to evaluate, or declarations (fn, type, trait, import). Multi-line input: an open brace, paren, bracket, string or block comment, or a line that ends in an operator (+, |>, =, -> ...), continues on the next line. diff --git a/tests/golden/cli/repl/repl__help_short_form.stdout b/tests/golden/cli/repl/repl__help_short_form.stdout index 4f28e5f74..0695460f4 100644 --- a/tests/golden/cli/repl/repl__help_short_form.stdout +++ b/tests/golden/cli/repl/repl__help_short_form.stdout @@ -1,8 +1,10 @@ Silt REPL (type :quit to exit, :help for commands) Commands: - :help, :h Show this help - :quit, :q Exit the REPL - Autocomplete builtins and user-defined names + :help, :h Show this help + :quit, :q Exit the REPL + :type Show the type of an expression without running it + :doc Show a builtin's signature and summary (list.map, Option, string) + Autocomplete builtins and user-defined names Enter expressions to evaluate, or declarations (fn, type, trait, import). Multi-line input: an open brace, paren, bracket, string or block comment, or a line that ends in an operator (+, |>, =, -> ...), continues on the next line. diff --git a/tests/golden/cli/repl/repl_doc_command__a_builtin_s_signature_and_summary.silt b/tests/golden/cli/repl/repl_doc_command__a_builtin_s_signature_and_summary.silt new file mode 100644 index 000000000..499b4275c --- /dev/null +++ b/tests/golden/cli/repl/repl_doc_command__a_builtin_s_signature_and_summary.silt @@ -0,0 +1,2 @@ +-- cmd: repl +-- stdin: :doc list.map\n:doc println\n:doc math.pi\n:doc uuid\n:quit\n diff --git a/tests/golden/cli/repl/repl_doc_command__a_builtin_s_signature_and_summary.stderr b/tests/golden/cli/repl/repl_doc_command__a_builtin_s_signature_and_summary.stderr new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/cli/repl/repl_doc_command__a_builtin_s_signature_and_summary.stdout b/tests/golden/cli/repl/repl_doc_command__a_builtin_s_signature_and_summary.stdout new file mode 100644 index 000000000..fd068a2e7 --- /dev/null +++ b/tests/golden/cli/repl/repl_doc_command__a_builtin_s_signature_and_summary.stdout @@ -0,0 +1,13 @@ +Silt REPL (type :quit to exit, :help for commands) +list.map(xs: List(a), f: Fn(a) -> b) -> List(b) +Transform each element +println(value: a) -> () where a: Display +Print a value with trailing newline +math.pi: Float +Pi (3.14159...) +type UuidError { Invalid(String), Other(String) } +uuid.is_valid(s: String) -> Bool +uuid.nil() -> String +uuid.parse(s: String) -> Result(String, UuidError) +uuid.v4() -> String +uuid.v7() -> String diff --git a/tests/golden/cli/repl/repl_doc_command__a_function_of_a_feature_not_built.silt b/tests/golden/cli/repl/repl_doc_command__a_function_of_a_feature_not_built.silt new file mode 100644 index 000000000..ccc6e76d0 --- /dev/null +++ b/tests/golden/cli/repl/repl_doc_command__a_function_of_a_feature_not_built.silt @@ -0,0 +1,3 @@ +-- cmd: repl +-- without-feature: postgres +-- stdin: :doc postgres.connect\n:quit\n diff --git a/tests/golden/cli/repl/repl_doc_command__a_function_of_a_feature_not_built.stderr b/tests/golden/cli/repl/repl_doc_command__a_function_of_a_feature_not_built.stderr new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/cli/repl/repl_doc_command__a_function_of_a_feature_not_built.stdout b/tests/golden/cli/repl/repl_doc_command__a_function_of_a_feature_not_built.stdout new file mode 100644 index 000000000..c9eee963f --- /dev/null +++ b/tests/golden/cli/repl/repl_doc_command__a_function_of_a_feature_not_built.stdout @@ -0,0 +1,4 @@ +Silt REPL (type :quit to exit, :help for commands) +postgres.connect(url: String) -> Result(PgPool, PostgresError) +Open a connection pool from a `postgresql://` URL (uses r2d2 defaults) +`postgres.connect` is not part of this build of silt: it needs the cargo feature `postgres` diff --git a/tests/golden/cli/repl/repl_doc_command__a_module_lists_its_types_and_traits.silt b/tests/golden/cli/repl/repl_doc_command__a_module_lists_its_types_and_traits.silt new file mode 100644 index 000000000..df338927b --- /dev/null +++ b/tests/golden/cli/repl/repl_doc_command__a_module_lists_its_types_and_traits.silt @@ -0,0 +1,2 @@ +-- cmd: repl +-- stdin: :doc json\n:quit\n diff --git a/tests/golden/cli/repl/repl_doc_command__a_module_lists_its_types_and_traits.stderr b/tests/golden/cli/repl/repl_doc_command__a_module_lists_its_types_and_traits.stderr new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/cli/repl/repl_doc_command__a_module_lists_its_types_and_traits.stdout b/tests/golden/cli/repl/repl_doc_command__a_module_lists_its_types_and_traits.stdout new file mode 100644 index 000000000..5a1e7d69d --- /dev/null +++ b/tests/golden/cli/repl/repl_doc_command__a_module_lists_its_types_and_traits.stdout @@ -0,0 +1,12 @@ +Silt REPL (type :quit to exit, :help for commands) +type JsonError { Syntax(String, Int), TypeMismatch(String, String), MissingField(String), Other(String) } +type Value { Null, Bool(Bool), Int(Int), Float(Float), String(String), Array(List(Value)), Object(Map(String, Value)) } +trait Encode { fn encode(self) -> Value } +trait Decode { fn decode(value: Value) -> Result(Self, JsonError) } +json.decode(value: Value, type a) -> Result(a, JsonError) where a: Decode +json.encode(value: a) -> Value where a: Encode +json.parse(s: String, type a) -> Result(a, JsonError) where a: Decode +json.parse_list(s: String, type a) -> Result(List(a), JsonError) where a: Decode +json.parse_map(s: String, type a) -> Result(Map(String, a), JsonError) where a: Decode +json.pretty(value: a) -> String where a: Encode +json.stringify(value: a) -> String where a: Encode diff --git a/tests/golden/cli/repl/repl_doc_command__a_type_a_trait_or_a_variant.silt b/tests/golden/cli/repl/repl_doc_command__a_type_a_trait_or_a_variant.silt new file mode 100644 index 000000000..81062ab1d --- /dev/null +++ b/tests/golden/cli/repl/repl_doc_command__a_type_a_trait_or_a_variant.silt @@ -0,0 +1,5 @@ +-- cmd: repl +-- A type and a trait show their declarations and what their docs say +-- first; a variant shows its enum; a type of the language its module's +-- first sentence. +-- stdin: :doc Option\n:doc Result\n:doc List\n:doc Map\n:doc Int\n:doc Bool\n:doc Bytes\n:doc Equal\n:doc Display\n:doc Compare\n:doc Hash\n:doc Error\n:doc Number\n:doc Some\n:doc None\n:doc Ok\n:doc Err\n:doc json.Value\n:doc json.Encode\n:doc json.Decode\n:doc channel.Recv\n:doc channel.Send\n:doc channel.Sent\n:doc channel.Received\n:doc channel.Closed\n:doc channel.Empty\n:doc channel.Message\n:doc list.Stop\n:doc list.Continue\n:doc io.IoError\n:doc io.NotFound\n:doc task.Handle\n:doc time.Weekday.Monday\n:quit\n diff --git a/tests/golden/cli/repl/repl_doc_command__a_type_a_trait_or_a_variant.stderr b/tests/golden/cli/repl/repl_doc_command__a_type_a_trait_or_a_variant.stderr new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/cli/repl/repl_doc_command__a_type_a_trait_or_a_variant.stdout b/tests/golden/cli/repl/repl_doc_command__a_type_a_trait_or_a_variant.stdout new file mode 100644 index 000000000..b560a73f6 --- /dev/null +++ b/tests/golden/cli/repl/repl_doc_command__a_type_a_trait_or_a_variant.stdout @@ -0,0 +1,60 @@ +Silt REPL (type :quit to exit, :help for commands) +type Option(a) { Some(a), None } +type Result(a, e) { Ok(a), Err(e) } +type List(a) -- builtin +Functions for working with ordered, immutable lists (`List(a)`). +type Map(a, b) -- builtin +Functions for working with immutable, ordered maps (`Map(k, v)`). +type Int -- builtin +Functions for parsing, converting, and comparing integers. +type Bool -- builtin +type Bytes -- opaque +trait Equal { fn equal(self, other: Self) -> Bool } +Whether two values are equal: `==` and `!=` need it. +trait Display { fn display(self) -> String } +How a value is shown: `println`, `print`, interpolation and `string.from` show it so. +trait Compare: Equal { fn compare(self, other: Self) -> Int } +The order of values: `<`, `>`, `<=` and `>=` need it. +trait Hash { fn hash(self) -> Int } +A value as a map's key or a set's element. +trait Error: Display { fn message(self) -> String } +An error a program reports: `message` says what went wrong. +trait Number {} +The types arithmetic is on, `Int` and `Float`: `+`, `-`, `*`, `/`, `%` and unary `-` need it. +type Option(a) { Some(a), None } +Constructs a present variant of `Option`. +type Option(a) { Some(a), None } +The absent variant of `Option`. +type Result(a, e) { Ok(a), Err(e) } +Constructs a success variant of `Result`. +type Result(a, e) { Ok(a), Err(e) } +Constructs an error variant of `Result`. +type Value { Null, Bool(Bool), Int(Int), Float(Float), String(String), Array(List(Value)), Object(Map(String, Value)) } +A JSON document as it is, for input whose shape is not known in advance: any document reads into it. +trait Encode { fn encode(self) -> Value } +What `json.stringify` and `json.pretty` need of the value they write. +trait Decode { fn decode(value: Value) -> Result(Self, JsonError) } +What `json.parse`, `json.parse_list`, `json.parse_map` and `json.decode` need of the type they decode into. +type ChannelOp(a) { Recv(Channel(a)), Send(Channel(a), a) } +Builds a receive arm for `channel.select`. +type ChannelOp(a) { Recv(Channel(a)), Send(Channel(a), a) } +Builds a send arm for `channel.select`. +type Selected(a) { Received(Channel(a), Option(a)), Sent(Channel(a)) } +What `channel.select` gives when an arm built with `channel.Send(ch, value)` completes: the value was handed off. +type Selected(a) { Received(Channel(a), Option(a)), Sent(Channel(a)) } +What `channel.select` gives when an arm built with `channel.Recv(ch)` completes: `channel.Received(ch, Some(value))` for a value, `channel.Received(ch, None)` when `ch` is closed and empty. +type ChannelResult(a) { Message(a), Empty, Closed } +Indicates the channel has been closed and is empty. +type ChannelResult(a) { Message(a), Empty, Closed } +Indicates the channel buffer is currently empty but not closed. +type ChannelResult(a) { Message(a), Empty, Closed } +Wraps a value received from a channel. +type Step(a) { Stop(a), Continue(a) } +Signals early termination from `list.fold_until`. +type Step(a) { Stop(a), Continue(a) } +Signals continuation in `list.fold_until`. +type IoError { NotFound(String), PermissionDenied(String), AlreadyExists(String), InvalidInput(String), Interrupted, UnexpectedEof, WriteZero, Other(String) } +type IoError { NotFound(String), PermissionDenied(String), AlreadyExists(String), InvalidInput(String), Interrupted, UnexpectedEof, WriteZero, Other(String) } +file or directory missing +type Handle(a) -- opaque +type Weekday { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } diff --git a/tests/golden/cli/repl/repl_doc_command__errors.silt b/tests/golden/cli/repl/repl_doc_command__errors.silt new file mode 100644 index 000000000..78fe567bf --- /dev/null +++ b/tests/golden/cli/repl/repl_doc_command__errors.silt @@ -0,0 +1,2 @@ +-- cmd: repl +-- stdin: :doc\n:doc nope\n:doc list.nope\n:doc json.Nope\n:doc Unit\n:quit\n diff --git a/tests/golden/cli/repl/repl_doc_command__errors.stderr b/tests/golden/cli/repl/repl_doc_command__errors.stderr new file mode 100644 index 000000000..6f527b47c --- /dev/null +++ b/tests/golden/cli/repl/repl_doc_command__errors.stderr @@ -0,0 +1,5 @@ +:doc needs a name, as in :doc list.map +no builtin named 'nope' +no builtin named 'list.nope' +no builtin named 'json.Nope' +no builtin named 'Unit' diff --git a/tests/golden/cli/repl/repl_doc_command__errors.stdout b/tests/golden/cli/repl/repl_doc_command__errors.stdout new file mode 100644 index 000000000..d17688b81 --- /dev/null +++ b/tests/golden/cli/repl/repl_doc_command__errors.stdout @@ -0,0 +1 @@ +Silt REPL (type :quit to exit, :help for commands) diff --git a/tests/golden/cli/repl/repl_type_command__an_expression_over_lines.silt b/tests/golden/cli/repl/repl_type_command__an_expression_over_lines.silt new file mode 100644 index 000000000..d0c2056fe --- /dev/null +++ b/tests/golden/cli/repl/repl_type_command__an_expression_over_lines.silt @@ -0,0 +1,2 @@ +-- cmd: repl +-- stdin: :type [1,\n2]\n:type 1 +\n2\n:type "a\nb"\n:quit\n diff --git a/tests/golden/cli/repl/repl_type_command__an_expression_over_lines.stderr b/tests/golden/cli/repl/repl_type_command__an_expression_over_lines.stderr new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/cli/repl/repl_type_command__an_expression_over_lines.stdout b/tests/golden/cli/repl/repl_type_command__an_expression_over_lines.stdout new file mode 100644 index 000000000..fe78bd62e --- /dev/null +++ b/tests/golden/cli/repl/repl_type_command__an_expression_over_lines.stdout @@ -0,0 +1,4 @@ +Silt REPL (type :quit to exit, :help for commands) +List(Int) +Int +String diff --git a/tests/golden/cli/repl/repl_type_command__errors.silt b/tests/golden/cli/repl/repl_type_command__errors.silt new file mode 100644 index 000000000..a7dc6a301 --- /dev/null +++ b/tests/golden/cli/repl/repl_type_command__errors.silt @@ -0,0 +1,2 @@ +-- cmd: repl +-- stdin: :type\n:type fn f() { 1 }\n:type nope\n:type list.map\n:type "a" + 1\n:typo\n1 + 1\n:quit\n diff --git a/tests/golden/cli/repl/repl_type_command__errors.stderr b/tests/golden/cli/repl/repl_type_command__errors.stderr new file mode 100644 index 000000000..f49a7a124 --- /dev/null +++ b/tests/golden/cli/repl/repl_type_command__errors.stderr @@ -0,0 +1,19 @@ +:type needs an expression, as in :type [1, 2] +:type takes an expression, not a declaration +error[type]: undefined variable 'nope' + --> :1:1 + | + 1 | nope + | ^^^^ undefined variable 'nope' +error[type]: module 'list' is not imported + --> :1:1 + | + 1 | list.map + | ^^^^^^^^ module 'list' is not imported + = help: enter `import list` first +error[type]: operator '+' requires Int or Float, got 'String'; build strings with interpolation, e.g. "{a}{b}" + --> :1:1 + | + 1 | "a" + 1 + | ^^^ operator '+' requires Int or Float, got 'String'; build strings with interpolation, e.g. "{a}{b}" +unknown REPL command ':typo'; type :help for the list diff --git a/tests/golden/cli/repl/repl_type_command__errors.stdout b/tests/golden/cli/repl/repl_type_command__errors.stdout new file mode 100644 index 000000000..24959c70b --- /dev/null +++ b/tests/golden/cli/repl/repl_type_command__errors.stdout @@ -0,0 +1,2 @@ +Silt REPL (type :quit to exit, :help for commands) +2 diff --git a/tests/golden/cli/repl/repl_type_command__the_expression_is_not_run.silt b/tests/golden/cli/repl/repl_type_command__the_expression_is_not_run.silt new file mode 100644 index 000000000..513969682 --- /dev/null +++ b/tests/golden/cli/repl/repl_type_command__the_expression_is_not_run.silt @@ -0,0 +1,2 @@ +-- cmd: repl +-- stdin: :type println("not printed")\nlet n = 1\n:type n + 1\nn\n:quit\n diff --git a/tests/golden/cli/repl/repl_type_command__the_expression_is_not_run.stderr b/tests/golden/cli/repl/repl_type_command__the_expression_is_not_run.stderr new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/cli/repl/repl_type_command__the_expression_is_not_run.stdout b/tests/golden/cli/repl/repl_type_command__the_expression_is_not_run.stdout new file mode 100644 index 000000000..a00b56159 --- /dev/null +++ b/tests/golden/cli/repl/repl_type_command__the_expression_is_not_run.stdout @@ -0,0 +1,4 @@ +Silt REPL (type :quit to exit, :help for commands) +() +Int +1 diff --git a/tests/golden/cli/repl/repl_type_command__the_type_of_an_expression.silt b/tests/golden/cli/repl/repl_type_command__the_type_of_an_expression.silt new file mode 100644 index 000000000..4b9ff9ddc --- /dev/null +++ b/tests/golden/cli/repl/repl_type_command__the_type_of_an_expression.silt @@ -0,0 +1,2 @@ +-- cmd: repl +-- stdin: :type 1 + 2\nimport list\nimport test\n:type test.assert_eq\n:type list.map\n:type list.sort\n:type list.group_by\nfn id(x) { x }\n:type id\nfn same(a, b) { a == b }\n:type same\n:type same(1, 2)\n:type [None]\n:type { x -> x.name }\n:quit\n diff --git a/tests/golden/cli/repl/repl_type_command__the_type_of_an_expression.stderr b/tests/golden/cli/repl/repl_type_command__the_type_of_an_expression.stderr new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/cli/repl/repl_type_command__the_type_of_an_expression.stdout b/tests/golden/cli/repl/repl_type_command__the_type_of_an_expression.stdout new file mode 100644 index 000000000..58da2a63a --- /dev/null +++ b/tests/golden/cli/repl/repl_type_command__the_type_of_an_expression.stdout @@ -0,0 +1,11 @@ +Silt REPL (type :quit to exit, :help for commands) +Int +Fn(a, a) -> () where a: Equal + Display +Fn(List(a), Fn(a) -> b) -> List(b) +Fn(List(a)) -> List(a) where a: Compare +Fn(List(a), Fn(a) -> b) -> Map(b, List(a)) where b: Hash +Fn(a) -> a +Fn(a, a) -> Bool where a: Equal +Bool +List(Option(a)) +Fn({name: a, ...b}) -> a