git clone https://garage44.eu/jeroen/frits.gitcartopolis-agent · 2026-11-26T12:24:42Z
feat(frits): formatter, language server and the scripting guide
Part C, the tools around the language, all without outside crates.
- `frits fmt` works on the source text rather than the syntax tree, so
comments, blank lines and how a number was written survive. Brackets
opened on one line indent what follows by one level: counted per
bracket, `Prim.set_geo({` pushed the record's fields two levels in.
A CamelCase name before `<` opens type arguments; an ALL_CAPS constant
(`LIMIT < 3`) does not. The two ported scripts were already in its
layout; a test keeps them so.
- `frits lsp` speaks LSP on stdio (a small JSON reader and writer in
`json.rs`): diagnostics per line as you type, completion after
`Prim.` with signatures and the declaration's comments, hover,
formatting. It checks against the platform declaration it is given.
- `frits guide` writes the scripting guide as Markdown from a platform
declaration, the comment above each function as its explanation, plus
a page on the language whose examples a test compiles. Meant for
Cartopolis's MCP `scripting_guide`, so the guide cannot drift from
what scripts can call.crates/bench/src/main.rs | 14 ++
crates/frits/src/fmt.rs | 307 +++++++++++++++++++++++++++++++++
crates/frits/src/guide.rs | 254 ++++++++++++++++++++++++++++
crates/frits/src/json.rs | 251 +++++++++++++++++++++++++++
crates/frits/src/lib.rs | 4 +
crates/frits/src/lsp.rs | 419 ++++++++++++++++++++++++++++++++++++++++++++++
crates/frits/src/main.rs | 73 +++++++-
docs/design.md | 22 ++-
8 files changed, 1340 insertions(+), 4 deletions(-)
diff --git a/crates/bench/src/main.rs b/crates/bench/src/main.rs
index 7e638fc..cc0001d 100644
--- a/crates/bench/src/main.rs
+++ b/crates/bench/src/main.rs
@@ -512,6 +512,20 @@ mod tests {
);
}
+ #[test]
+ fn the_ported_scripts_are_formatted() {
+ for src in [
+ include_str!("../scripts/firebird.frits"),
+ include_str!("../scripts/football.frits"),
+ ] {
+ assert_eq!(
+ frits::fmt::format(src),
+ src,
+ "run `frits fmt crates/bench/scripts/*.frits`"
+ );
+ }
+ }
+
/// The `frits` examples in the documentation compile against this platform.
#[test]
fn the_documented_examples_compile() {
diff --git a/crates/frits/src/fmt.rs b/crates/frits/src/fmt.rs
new file mode 100644
index 0000000..c1d62e3
--- /dev/null
+++ b/crates/frits/src/fmt.rs
@@ -0,0 +1,307 @@
+//! `frits fmt`: one layout for every script.
+//!
+//! Works on the source text, not the syntax tree, so comments, blank lines
+//! (at most one in a row) and how a number was written all survive. What it
+//! settles: four spaces per level of `{`, `(` and `[`; one space around binary
+//! operators, after `,` and `:`, and inside `{ … }` on one line; none inside
+//! `(…)`, `[…]` and type arguments (`List<Int>`); no trailing spaces; one newline
+//! at the end. A file it cannot read (a string never closed) comes back as it
+//! was.
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+enum Kind {
+ Word,
+ Number,
+ Str,
+ Sym,
+ Comment,
+}
+
+#[derive(Debug)]
+struct Token<'a> {
+ kind: Kind,
+ text: &'a str,
+ /// Newlines between the previous token and this one.
+ breaks: usize,
+}
+
+const SYMS: [&str; 33] = [
+ "..", "=>", "->", "==", "!=", "<=", ">=", "&&", "||", "+=", "-=", "*=", "/=", "(", ")", "{", "}", "[",
+ "]", ",", ".", ":", "=", "<", ">", "+", "-", "*", "/", "%", "!", "_", "?",
+];
+
+fn tokens(src: &str) -> Option<Vec<Token<'_>>> {
+ let b = src.as_bytes();
+ let mut out = Vec::new();
+ let mut i = 0;
+ let mut breaks = 0;
+ while i < b.len() {
+ let c = b[i];
+ if c == b'\n' {
+ breaks += 1;
+ i += 1;
+ continue;
+ }
+ if c.is_ascii_whitespace() {
+ i += 1;
+ continue;
+ }
+ let s = i;
+ let kind = if c == b'/' && b.get(i + 1) == Some(&b'/') {
+ while i < b.len() && b[i] != b'\n' {
+ i += 1;
+ }
+ Kind::Comment
+ } else if c == b'"' {
+ i = string_end(b, i)?;
+ Kind::Str
+ } else if c.is_ascii_alphabetic()
+ || (c == b'_' && b.get(i + 1).is_some_and(|n| n.is_ascii_alphanumeric()))
+ {
+ while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_') {
+ i += 1;
+ }
+ Kind::Word
+ } else if c.is_ascii_digit() {
+ while i < b.len()
+ && (b[i].is_ascii_alphanumeric()
+ || b[i] == b'_'
+ || (b[i] == b'.' && b.get(i + 1).is_some_and(|n| n.is_ascii_digit()))
+ || ((b[i] == b'+' || b[i] == b'-') && matches!(b[i - 1], b'e' | b'E')))
+ {
+ i += 1;
+ }
+ Kind::Number
+ } else {
+ let rest = &src[i..];
+ let sym = SYMS.iter().find(|s| rest.starts_with(**s))?;
+ i += sym.len();
+ Kind::Sym
+ };
+ out.push(Token {
+ kind,
+ text: &src[s..i],
+ breaks,
+ });
+ breaks = 0;
+ }
+ Some(out)
+}
+
+/// Where the string starting at `i` ends (after its closing quote), holes and
+/// strings inside holes included.
+fn string_end(b: &[u8], mut i: usize) -> Option<usize> {
+ i += 1;
+ while i < b.len() {
+ match b[i] {
+ b'\\' => i += 2,
+ b'"' => return Some(i + 1),
+ b'{' => {
+ let mut depth = 1;
+ i += 1;
+ while i < b.len() && depth > 0 {
+ match b[i] {
+ b'{' => depth += 1,
+ b'}' => depth -= 1,
+ b'"' => {
+ i = string_end(b, i)? - 1;
+ }
+ _ => {}
+ }
+ i += 1;
+ }
+ }
+ _ => i += 1,
+ }
+ }
+ None
+}
+
+const KEYWORDS: [&str; 14] = [
+ "if", "else", "while", "for", "in", "match", "return", "let", "var", "on", "script", "keep", "import",
+ "test",
+];
+
+fn is_binary(t: &str) -> bool {
+ matches!(
+ t,
+ "=" | "=="
+ | "!="
+ | "<="
+ | ">="
+ | "&&"
+ | "||"
+ | "+="
+ | "-="
+ | "*="
+ | "/="
+ | "+"
+ | "-"
+ | "*"
+ | "/"
+ | "%"
+ | "=>"
+ | "->"
+ | "<"
+ | ">"
+ )
+}
+
+pub fn format(src: &str) -> String {
+ let Some(toks) = tokens(src) else {
+ return src.to_string();
+ };
+ let mut out = String::new();
+ // Open brackets, with the line each opened on; `<` marks type arguments.
+ // Brackets opened on one line indent the lines after it by one level, not
+ // one each: `f({` then the record's fields at one level in.
+ let mut opened: Vec<usize> = Vec::new();
+ let mut stack: Vec<&str> = Vec::new();
+ let mut line = 0;
+ // Whether the token before ended a value, so a `-` after it is binary.
+ let mut after_value = false;
+ // Whether the token before was a unary `-` or `!`.
+ let mut prev_unary = false;
+ let mut prev_generic_close = false;
+ for (n, t) in toks.iter().enumerate() {
+ let sym = |s: &str| t.kind == Kind::Sym && t.text == s;
+ let generic_close = sym(">") && stack.last() == Some(&"<");
+ let unary = (sym("-") && !after_value) || sym("!");
+ let generic_open = sym("<") && n > 0 && opens_generic(&toks, n);
+ line += t.breaks;
+ if n > 0 && t.breaks > 0 {
+ out.push('\n');
+ if t.breaks > 1 {
+ out.push('\n');
+ }
+ // Closers leading this line close their brackets before it is indented.
+ let leading = toks[n..]
+ .iter()
+ .enumerate()
+ .take_while(|(k, x)| {
+ (*k == 0 || x.breaks == 0) && x.kind == Kind::Sym && matches!(x.text, "}" | ")" | "]")
+ })
+ .count();
+ let open: Vec<usize> = stack
+ .iter()
+ .zip(&opened)
+ .filter(|(s, _)| **s != "<")
+ .map(|(_, l)| *l)
+ .collect();
+ let mut lines = open[..open.len().saturating_sub(leading)].to_vec();
+ lines.dedup();
+ out.push_str(&" ".repeat(lines.len()));
+ } else if n > 0
+ && !generic_open
+ && !(prev_generic_close && (sym("(") || sym(">")))
+ && space_between(&toks[n - 1], t, &stack, prev_unary)
+ {
+ out.push(' ');
+ }
+ out.push_str(t.text);
+ if t.kind == Kind::Sym {
+ match t.text {
+ "{" | "(" | "[" => {
+ stack.push(t.text);
+ opened.push(line);
+ }
+ "}" | ")" | "]" => {
+ while stack.last() == Some(&"<") {
+ stack.pop();
+ opened.pop();
+ }
+ stack.pop();
+ opened.pop();
+ }
+ "<" if generic_open => {
+ stack.push("<");
+ opened.push(line);
+ }
+ ">" if generic_close => {
+ stack.pop();
+ opened.pop();
+ }
+ _ => {}
+ }
+ }
+ if t.kind != Kind::Comment {
+ after_value = match t.kind {
+ Kind::Word => !KEYWORDS.contains(&t.text),
+ Kind::Number | Kind::Str => true,
+ _ => matches!(t.text, ")" | "]" | "}" | "?" | "_") || generic_close,
+ };
+ prev_unary = unary;
+ prev_generic_close = generic_close;
+ }
+ }
+ let mut out: String = out.lines().map(|l| l.trim_end()).collect::<Vec<_>>().join("\n");
+ out.push('\n');
+ out
+}
+
+/// Does the `<` at `n` open type arguments? After a type name written in
+/// CamelCase (`List<`, `Tree<`, not the constant `LIMIT <`), or after `fn name`.
+fn opens_generic(toks: &[Token], n: usize) -> bool {
+ let p = &toks[n - 1];
+ if p.kind != Kind::Word {
+ return false;
+ }
+ let camel = p.text.starts_with(|c: char| c.is_ascii_uppercase())
+ && p.text.chars().any(|c| c.is_ascii_lowercase());
+ camel || (n >= 2 && toks[n - 2].kind == Kind::Word && toks[n - 2].text == "fn")
+}
+
+fn space_between(p: &Token, t: &Token, stack: &[&str], prev_unary: bool) -> bool {
+ if t.kind == Kind::Comment {
+ return true;
+ }
+ let psym = |s: &str| p.kind == Kind::Sym && p.text == s;
+ let tsym = |s: &str| t.kind == Kind::Sym && t.text == s;
+ if prev_unary {
+ return false;
+ }
+ if tsym(",") || tsym(")") || tsym("]") || tsym("?") || tsym(".") || tsym(":") {
+ return false;
+ }
+ if psym("(") || psym("[") || psym(".") || psym("..") {
+ return false;
+ }
+ if tsym("..") {
+ // `0..10` and `xs..`; but `{ ..base }` and `in ..` keep theirs.
+ return !matches!(p.kind, Kind::Number | Kind::Word) || KEYWORDS.contains(&p.text);
+ }
+ if psym("{") && tsym("}") {
+ return false;
+ }
+ if psym("{") || tsym("}") || psym(",") || psym(":") || tsym("{") {
+ return true;
+ }
+ if stack.last() == Some(&"<") || (tsym(">") && stack.last() == Some(&"<")) {
+ return false;
+ }
+ if psym("<") && stack.last() == Some(&"<") {
+ return false;
+ }
+ if tsym("(") || tsym("[") {
+ // A call or an index sticks to what it calls; a keyword keeps its space.
+ return match p.kind {
+ Kind::Word => KEYWORDS.contains(&p.text),
+ Kind::Sym => is_binary(p.text) || psym("{"),
+ _ => false,
+ };
+ }
+ true
+}
+
+#[cfg(test)]
+mod tests {
+ use super::format;
+
+ #[test]
+ fn layout() {
+ let src = "script / Prim,Chat\n\n\n// hi\nfn f(a:Int,b : List<Int>)->Int{\nlet x=a+ -b[0] // why\nif x>0{return x}\n x*2\n}\nfn g<T>(x:T)->Option<T>{Some(x)}\non go(){let r={x:1,y:2}\nlet n=0..10\nlet s=\"{r.x+1} {f(1, [2])}\"\n}\n\n";
+ let want = "script / Prim, Chat\n\n// hi\nfn f(a: Int, b: List<Int>) -> Int {\n let x = a + -b[0] // why\n if x > 0 { return x }\n x * 2\n}\nfn g<T>(x: T) -> Option<T> { Some(x) }\non go() { let r = { x: 1, y: 2 }\n let n = 0..10\n let s = \"{r.x+1} {f(1, [2])}\"\n}\n";
+ assert_eq!(format(src), want);
+ assert_eq!(format(want), want);
+ }
+}
diff --git a/crates/frits/src/guide.rs b/crates/frits/src/guide.rs
new file mode 100644
index 0000000..b1150ec
--- /dev/null
+++ b/crates/frits/src/guide.rs
@@ -0,0 +1,254 @@
+//! The scripting guide for one platform, as Markdown, written from its
+//! declaration: what each effect and module offers, with the comment above each
+//! function as its explanation, the events, the types, and the language itself.
+//! A host serves it to people and to agents (Cartopolis's `scripting_guide`), so
+//! the guide cannot drift from what scripts can actually call.
+
+use std::collections::HashMap;
+
+use crate::types::{HostFnSig, PlatformDecl, Show};
+
+/// The comment lines written directly above each declaration, by
+/// `Namespace.name` (or `event name`, or `type Name`).
+pub fn doc_comments_of(src: &str) -> HashMap<String, String> {
+ let mut docs = HashMap::new();
+ let mut pending: Vec<String> = Vec::new();
+ let mut namespace: Option<String> = None;
+ for line in src.lines() {
+ let t = line.trim();
+ if let Some(c) = t.strip_prefix("//") {
+ pending.push(c.trim().to_string());
+ continue;
+ }
+ let word = |prefix: &str| {
+ t.strip_prefix(prefix).map(|r| {
+ r.trim_start()
+ .split(|c: char| !(c.is_alphanumeric() || c == '_'))
+ .next()
+ .unwrap_or("")
+ .to_string()
+ })
+ };
+ let key = if let Some(n) = word("effect ").or_else(|| word("module ")) {
+ namespace = Some(n.clone());
+ Some(n)
+ } else if t == "}" {
+ namespace = None;
+ None
+ } else if let Some(n) = word("fn ").or_else(|| word("let ")) {
+ namespace.as_ref().map(|ns| format!("{ns}.{n}"))
+ } else if let Some(n) = word("event ") {
+ Some(format!("event {n}"))
+ } else {
+ word("type ")
+ .or_else(|| word("opaque "))
+ .map(|n| format!("type {n}"))
+ };
+ if let Some(k) = key
+ && !pending.is_empty()
+ {
+ docs.insert(k, pending.join(" "));
+ }
+ pending.clear();
+ }
+ docs
+}
+
+pub fn signature(f: &HostFnSig) -> String {
+ let params: Vec<String> = f.params.iter().map(|t| Show(t, &[]).to_string()).collect();
+ let ret = if f.ret == crate::types::Type::Unit {
+ String::new()
+ } else {
+ format!(" -> {}", Show(&f.ret, &[]))
+ };
+ format!("{}.{}({}){ret}", f.namespace, f.name, params.join(", "))
+}
+
+/// The guide for the platform declared by `decl_src` (the prelude included).
+pub fn guide(title: &str, decl_src: &str) -> Result<String, crate::Error> {
+ let decl = PlatformDecl::parse(decl_src)?;
+ let mut docs = doc_comments_of(crate::prelude::DECL);
+ docs.extend(doc_comments_of(decl_src));
+ let doc = |k: &str| docs.get(k).map(|d| format!(" — {d}")).unwrap_or_default();
+ let mut out = format!("# Scripting {title} in Frits\n\n");
+ out.push_str(LANGUAGE);
+
+ out.push_str("\n## What a script can do here\n\n");
+ out.push_str(
+ "A script names the effects it uses on its first line, `script / Prim, Chat`, and a function names \
+ the ones it uses after its parameters, `fn fly() / Prim`. A **module** needs no effect.\n",
+ );
+ for ns in decl
+ .effects
+ .iter()
+ .map(|n| (n, "effect"))
+ .chain(decl.modules.iter().map(|n| (n, "module")))
+ {
+ let (name, kind) = ns;
+ out.push_str(&format!("\n### {name} ({kind}){}\n\n", doc(name)));
+ let fns: Vec<_> = decl.fns.iter().filter(|f| &f.namespace == name).collect();
+ let consts: Vec<_> = decl.consts.iter().filter(|c| &c.namespace == name).collect();
+ if fns.is_empty() && consts.is_empty() {
+ out.push_str("(Nothing to call: the effect itself is the permission.)\n");
+ }
+ for f in fns {
+ out.push_str(&format!(
+ "- `{}`{}\n",
+ signature(f),
+ doc(&format!("{}.{}", f.namespace, f.name))
+ ));
+ }
+ for c in consts {
+ out.push_str(&format!(
+ "- `{}.{}: {}`{}\n",
+ c.namespace,
+ c.name,
+ Show(&c.ty, &[]),
+ doc(&format!("{}.{}", c.namespace, c.name))
+ ));
+ }
+ }
+
+ out.push_str("\n## Events\n\nA handler is `on name(…) { … }` and has the script's effects.\n\n");
+ for (name, params) in &decl.events {
+ let ps: Vec<String> = params.iter().map(|t| Show(t, &[]).to_string()).collect();
+ out.push_str(&format!(
+ "- `on {name}({})`{}\n",
+ ps.join(", "),
+ doc(&format!("event {name}"))
+ ));
+ }
+ out.push_str(
+ "- `on receive(m: T)` — a message from another script; it gives this script an address, `me()`.\n",
+ );
+
+ let mut types: Vec<_> = decl.env.aliases.iter().collect();
+ types.sort_by(|a, b| a.0.cmp(b.0));
+ if !types.is_empty() {
+ out.push_str("\n## Types\n\n");
+ for (name, t) in types {
+ let shown = Show(t, &[]).to_string();
+ if shown == *name {
+ out.push_str(&format!(
+ "- `{name}`: made only by the host{}\n",
+ doc(&format!("type {name}"))
+ ));
+ } else {
+ out.push_str(&format!("- `{name} = {shown}`{}\n", doc(&format!("type {name}"))));
+ }
+ }
+ }
+ Ok(out)
+}
+
+/// The language, briefly; every example compiles (a test checks).
+const LANGUAGE: &str = r#"Frits is typed: a mistake is reported, with its line, before the script runs.
+Every script runs on its own, with its own memory and a slice of time per tick;
+a long loop is paused and resumed, never a reason to stop the world.
+
+```frits
+script / Random
+
+// Values: Int, Float, Bool, Str, lists, maps, records, tuples, enums.
+let SPOTS = [3, 1, 4]
+let NAMES: Map<Str, Int> = ["ada": 1, "bo": 2]
+var best = { name: "nobody", score: 0 } // a record; `var` can change
+
+enum Mood { Calm, Angry(Int) } // an enum, its variants may carry values
+var mood = Calm
+
+fn describe(m: Mood) -> Str { // parameters and results are typed
+ match m { // `match` must cover every case
+ Calm => "calm",
+ Angry(n) if n > 5 => "furious",
+ Angry(_) => "cross",
+ }
+}
+
+fn roll() -> Int / Random { // what a function does, after `/`
+ Random.int(1, 6)
+}
+
+fn parse(text: Str) -> Result<Int, Str> { // errors are values
+ match text.parse_int() {
+ Some(n) => Ok(n),
+ None => Err("not a number: {text}"),
+ }
+}
+
+fn total(a: Str, b: Str) -> Result<Int, Str> {
+ let x = parse(a)? // `?` passes an Err on
+ Ok(x + parse(b)?)
+}
+
+fn demo() / Random {
+ var xs = SPOTS.map(fn(x) { x * 2 }) // functions are values
+ xs.push(roll())
+ best.score = xs.filter(fn(x) { x > 2 }).count(fn(x) { true })
+ let (lo, hi) = (xs.sort()[0], len(xs)) // tuples
+ let v: Vec3 = { x: 1, y: 0, z: 0 }
+ let w = v * 2.0 + { x: 0, y: 1, z: 0 } // Vec3 arithmetic
+ log("{describe(mood)} {lo} {hi} {w.length():.2}")
+ if let Some(n) = NAMES.get("bo") { assert(n == 2, "bo is two") }
+ mood = Angry(6)
+}
+
+test "a calm mood reads calm" {
+ assert(describe(Calm) == "calm")
+}
+```
+
+- Statements end at the end of a line; an operator that continues one goes at
+ its end, and `} else {` stays on one line.
+- `let` cannot change, `var` can. `keep var score = 0` also survives a restart.
+- `if let Some(x) = … { }`, `for x in xs { }`, `for i in 0..10 { }`,
+ `while cond { }`, `break`, `continue`, `return`.
+- Strings: `"{name} is {d:.1} m away"`, `.split(",")`, `.trim()`, `.upper()`,
+ `.contains(…)`, `.replace(a, b)`, `.parse_int()`.
+- Lists: `.push(x)`, `.get(i)`, `xs[i]`, `.map`, `.filter`, `.find`, `.any`,
+ `.all`, `.count`, `.sort()`, `.join(", ")`, `xs + ys`; maps: `.get`, `.set`,
+ `.has`, `.remove`, `.keys()`.
+- `log("…")`, `warn("…")`, `assert(cond, "why")`; `test "…" { }` blocks run
+ with `frits test`.
+- Scripts talk with `send(addr, message)` (effect `Mail`) to a script's
+ `on receive(m: T)`; its address is `me()`.
+- No `null` (use `Option`), no exceptions (use `Result`), no classes.
+"#;
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_guide_lists_the_platform_and_its_examples_compile() {
+ let decl = "
+// The prim the script is in.
+effect Prim {
+ // Where it is, in metres.
+ fn pos() -> Vec3
+ fn set_pos(p: Vec3)
+}
+// Someone touched it.
+event touch(name: Str)
+opaque Door
+";
+ let g = guide("prims", decl).unwrap();
+ assert!(
+ g.contains("### Prim (effect) — The prim the script is in."),
+ "{g}"
+ );
+ assert!(
+ g.contains("- `Prim.pos() -> { x: Float, y: Float, z: Float }` — Where it is, in metres."),
+ "{g}"
+ );
+ assert!(g.contains("- `on touch(Str)` — Someone touched it."), "{g}");
+ assert!(g.contains("- `Door`: made only by the host"), "{g}");
+ let p = crate::Platform::<()>::new(decl).unwrap();
+ for block in g.split("```frits\n").skip(1) {
+ let src = block.split("```").next().unwrap();
+ if let Err(e) = p.compile(src) {
+ panic!("{e:?}\n{src}");
+ }
+ }
+ }
+}
diff --git a/crates/frits/src/json.rs b/crates/frits/src/json.rs
new file mode 100644
index 0000000..1ae804e
--- /dev/null
+++ b/crates/frits/src/json.rs
@@ -0,0 +1,251 @@
+//! Just enough JSON for the language server: read a message, write one.
+
+use std::fmt::Write;
+
+#[derive(Clone, Debug, PartialEq)]
+pub enum Json {
+ Null,
+ Bool(bool),
+ Num(f64),
+ Str(String),
+ Arr(Vec<Json>),
+ Obj(Vec<(String, Json)>),
+}
+
+impl Json {
+ pub fn get(&self, key: &str) -> &Json {
+ match self {
+ Json::Obj(kv) => kv
+ .iter()
+ .find(|(k, _)| k == key)
+ .map(|(_, v)| v)
+ .unwrap_or(&Json::Null),
+ _ => &Json::Null,
+ }
+ }
+
+ pub fn at(&self, path: &[&str]) -> &Json {
+ path.iter().fold(self, |j, k| j.get(k))
+ }
+
+ pub fn str(&self) -> Option<&str> {
+ if let Json::Str(s) = self { Some(s) } else { None }
+ }
+
+ pub fn num(&self) -> Option<f64> {
+ if let Json::Num(n) = self { Some(*n) } else { None }
+ }
+
+ pub fn obj(pairs: Vec<(&str, Json)>) -> Json {
+ Json::Obj(pairs.into_iter().map(|(k, v)| (k.to_string(), v)).collect())
+ }
+
+ pub fn s(text: impl Into<String>) -> Json {
+ Json::Str(text.into())
+ }
+}
+
+impl std::fmt::Display for Json {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Json::Null => f.write_str("null"),
+ Json::Bool(b) => write!(f, "{b}"),
+ Json::Num(n) if n.fract() == 0.0 && n.abs() < 1e15 => write!(f, "{}", *n as i64),
+ Json::Num(n) => write!(f, "{n}"),
+ Json::Str(s) => {
+ f.write_char('"')?;
+ for c in s.chars() {
+ match c {
+ '"' => f.write_str("\\\"")?,
+ '\\' => f.write_str("\\\\")?,
+ '\n' => f.write_str("\\n")?,
+ '\r' => f.write_str("\\r")?,
+ '\t' => f.write_str("\\t")?,
+ c if (c as u32) < 0x20 => write!(f, "\\u{:04x}", c as u32)?,
+ c => f.write_char(c)?,
+ }
+ }
+ f.write_char('"')
+ }
+ Json::Arr(items) => {
+ f.write_char('[')?;
+ for (i, v) in items.iter().enumerate() {
+ if i > 0 {
+ f.write_char(',')?;
+ }
+ write!(f, "{v}")?;
+ }
+ f.write_char(']')
+ }
+ Json::Obj(kv) => {
+ f.write_char('{')?;
+ for (i, (k, v)) in kv.iter().enumerate() {
+ if i > 0 {
+ f.write_char(',')?;
+ }
+ write!(f, "{}:{v}", Json::Str(k.clone()))?;
+ }
+ f.write_char('}')
+ }
+ }
+ }
+}
+
+pub fn parse(text: &str) -> Option<Json> {
+ let mut p = P {
+ b: text.as_bytes(),
+ i: 0,
+ };
+ let v = p.value()?;
+ p.ws();
+ (p.i == p.b.len()).then_some(v)
+}
+
+struct P<'a> {
+ b: &'a [u8],
+ i: usize,
+}
+
+impl P<'_> {
+ fn ws(&mut self) {
+ while self.i < self.b.len() && self.b[self.i].is_ascii_whitespace() {
+ self.i += 1;
+ }
+ }
+
+ fn eat(&mut self, c: u8) -> bool {
+ self.ws();
+ if self.b.get(self.i) == Some(&c) {
+ self.i += 1;
+ true
+ } else {
+ false
+ }
+ }
+
+ fn lit(&mut self, word: &str, v: Json) -> Option<Json> {
+ if self.b[self.i..].starts_with(word.as_bytes()) {
+ self.i += word.len();
+ Some(v)
+ } else {
+ None
+ }
+ }
+
+ fn value(&mut self) -> Option<Json> {
+ self.ws();
+ match *self.b.get(self.i)? {
+ b'n' => self.lit("null", Json::Null),
+ b't' => self.lit("true", Json::Bool(true)),
+ b'f' => self.lit("false", Json::Bool(false)),
+ b'"' => self.string().map(Json::Str),
+ b'[' => {
+ self.i += 1;
+ let mut items = Vec::new();
+ if self.eat(b']') {
+ return Some(Json::Arr(items));
+ }
+ loop {
+ items.push(self.value()?);
+ if self.eat(b']') {
+ return Some(Json::Arr(items));
+ }
+ if !self.eat(b',') {
+ return None;
+ }
+ }
+ }
+ b'{' => {
+ self.i += 1;
+ let mut kv = Vec::new();
+ if self.eat(b'}') {
+ return Some(Json::Obj(kv));
+ }
+ loop {
+ self.ws();
+ let k = self.string()?;
+ if !self.eat(b':') {
+ return None;
+ }
+ kv.push((k, self.value()?));
+ if self.eat(b'}') {
+ return Some(Json::Obj(kv));
+ }
+ if !self.eat(b',') {
+ return None;
+ }
+ }
+ }
+ _ => {
+ let s = self.i;
+ while self.i < self.b.len()
+ && matches!(self.b[self.i], b'-' | b'+' | b'.' | b'e' | b'E' | b'0'..=b'9')
+ {
+ self.i += 1;
+ }
+ std::str::from_utf8(&self.b[s..self.i])
+ .ok()?
+ .parse()
+ .ok()
+ .map(Json::Num)
+ }
+ }
+ }
+
+ fn string(&mut self) -> Option<String> {
+ if self.b.get(self.i) != Some(&b'"') {
+ return None;
+ }
+ self.i += 1;
+ let mut out = Vec::new();
+ loop {
+ let c = *self.b.get(self.i)?;
+ self.i += 1;
+ match c {
+ b'"' => return String::from_utf8(out).ok(),
+ b'\\' => {
+ let e = *self.b.get(self.i)?;
+ self.i += 1;
+ match e {
+ b'n' => out.push(b'\n'),
+ b't' => out.push(b'\t'),
+ b'r' => out.push(b'\r'),
+ b'b' => out.push(8),
+ b'f' => out.push(12),
+ b'u' => {
+ let hex = std::str::from_utf8(self.b.get(self.i..self.i + 4)?).ok()?;
+ self.i += 4;
+ let mut code = u32::from_str_radix(hex, 16).ok()?;
+ // A surrogate pair.
+ if (0xD800..0xDC00).contains(&code)
+ && self.b.get(self.i..self.i + 2) == Some(b"\\u")
+ {
+ let lo = std::str::from_utf8(self.b.get(self.i + 2..self.i + 6)?).ok()?;
+ let lo = u32::from_str_radix(lo, 16).ok()?;
+ self.i += 6;
+ code = 0x10000 + ((code - 0xD800) << 10) + (lo - 0xDC00);
+ }
+ let ch = char::from_u32(code).unwrap_or('\u{FFFD}');
+ out.extend_from_slice(ch.to_string().as_bytes());
+ }
+ other => out.push(other),
+ }
+ }
+ c => out.push(c),
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn round_trip() {
+ let src = r#"{"a":[1,2.5,true,null],"b":"x\"y\né😀","c":{}}"#;
+ let v = parse(src).unwrap();
+ assert_eq!(v.at(&["b"]).str(), Some("x\"y\né😀"));
+ assert_eq!(parse(&v.to_string()).unwrap(), v);
+ }
+}
diff --git a/crates/frits/src/lib.rs b/crates/frits/src/lib.rs
index 1a8b57c..dab61a5 100644
--- a/crates/frits/src/lib.rs
+++ b/crates/frits/src/lib.rs
@@ -9,8 +9,12 @@
pub mod ast;
pub mod bytecode;
pub mod compile;
+pub mod fmt;
+pub mod guide;
pub mod imports;
+pub mod json;
pub mod lexer;
+pub mod lsp;
pub mod parser;
pub mod platform;
pub mod prelude;
diff --git a/crates/frits/src/lsp.rs b/crates/frits/src/lsp.rs
new file mode 100644
index 0000000..ccff904
--- /dev/null
+++ b/crates/frits/src/lsp.rs
@@ -0,0 +1,419 @@
+//! `frits lsp`: a language server over stdin and stdout, for any editor that
+//! speaks LSP. It checks a script against one platform's declaration as it is
+//! typed, completes `Prim.` with what the platform offers, shows a function's
+//! signature and explanation on hover, and formats.
+//!
+//! Errors carry a line, not a column, so a diagnostic covers its whole line.
+
+use std::collections::HashMap;
+use std::io::{BufRead, Read, Write};
+
+use crate::Platform;
+use crate::json::{self, Json};
+use crate::types::PlatformDecl;
+
+pub struct Server {
+ platform: Platform<()>,
+ decl_src: String,
+ docs: HashMap<String, String>,
+ files: HashMap<String, String>,
+}
+
+const KEYWORDS: [&str; 22] = [
+ "fn", "let", "var", "if", "else", "while", "for", "in", "match", "return", "break", "continue", "enum",
+ "type", "script", "on", "true", "false", "keep", "import", "test", "receive",
+];
+
+impl Server {
+ pub fn new(decl_src: &str) -> Result<Server, crate::Error> {
+ let platform = Platform::new(decl_src)?;
+ let mut docs = HashMap::new();
+ for (k, v) in crate::guide::doc_comments_of(crate::prelude::DECL)
+ .into_iter()
+ .chain(crate::guide::doc_comments_of(decl_src))
+ {
+ docs.insert(k, v);
+ }
+ Ok(Server {
+ platform,
+ decl_src: decl_src.to_string(),
+ docs,
+ files: HashMap::new(),
+ })
+ }
+
+ fn decl(&self) -> &PlatformDecl {
+ &self.platform.decl
+ }
+
+ /// Answer one message; returns what to send back (replies and
+ /// notifications), and whether to stop.
+ pub fn handle(&mut self, msg: &Json) -> (Vec<Json>, bool) {
+ let method = msg.get("method").str().unwrap_or("");
+ let id = msg.get("id").clone();
+ let params = msg.get("params");
+ let reply = |result: Json| {
+ Json::obj(vec![
+ ("jsonrpc", Json::s("2.0")),
+ ("id", id.clone()),
+ ("result", result),
+ ])
+ };
+ match method {
+ "initialize" => {
+ let caps = Json::obj(vec![
+ ("textDocumentSync", Json::Num(1.0)),
+ ("hoverProvider", Json::Bool(true)),
+ ("documentFormattingProvider", Json::Bool(true)),
+ (
+ "completionProvider",
+ Json::obj(vec![("triggerCharacters", Json::Arr(vec![Json::s(".")]))]),
+ ),
+ ]);
+ let info = Json::obj(vec![
+ ("name", Json::s("frits")),
+ ("version", Json::s(env!("CARGO_PKG_VERSION"))),
+ ]);
+ (
+ vec![reply(Json::obj(vec![
+ ("capabilities", caps),
+ ("serverInfo", info),
+ ]))],
+ false,
+ )
+ }
+ "shutdown" => (vec![reply(Json::Null)], false),
+ "exit" => (Vec::new(), true),
+ "textDocument/didOpen" => {
+ let doc = params.get("textDocument");
+ let uri = doc.get("uri").str().unwrap_or("").to_string();
+ let text = doc.get("text").str().unwrap_or("").to_string();
+ self.files.insert(uri.clone(), text);
+ (vec![self.diagnostics(&uri)], false)
+ }
+ "textDocument/didChange" => {
+ let uri = params
+ .at(&["textDocument", "uri"])
+ .str()
+ .unwrap_or("")
+ .to_string();
+ if let Json::Arr(changes) = params.get("contentChanges")
+ && let Some(text) = changes.last().and_then(|c| c.get("text").str())
+ {
+ self.files.insert(uri.clone(), text.to_string());
+ }
+ (vec![self.diagnostics(&uri)], false)
+ }
+ "textDocument/didClose" => {
+ let uri = params.at(&["textDocument", "uri"]).str().unwrap_or("");
+ self.files.remove(uri);
+ (Vec::new(), false)
+ }
+ "textDocument/completion" => (vec![reply(self.completion(params))], false),
+ "textDocument/hover" => (vec![reply(self.hover(params))], false),
+ "textDocument/formatting" => {
+ let uri = params.at(&["textDocument", "uri"]).str().unwrap_or("");
+ let text = self.files.get(uri).cloned().unwrap_or_default();
+ let formatted = crate::fmt::format(&text);
+ let lines = text.lines().count() as f64 + 1.0;
+ let edit = Json::obj(vec![
+ ("range", range(0.0, 0.0, lines, 0.0)),
+ ("newText", Json::s(formatted)),
+ ]);
+ (vec![reply(Json::Arr(vec![edit]))], false)
+ }
+ _ if id != Json::Null => {
+ // A request we do not know: answer it, so the editor does not wait.
+ (vec![reply(Json::Null)], false)
+ }
+ _ => (Vec::new(), false),
+ }
+ }
+
+ fn diagnostics(&self, uri: &str) -> Json {
+ let text = self.files.get(uri).map(|s| s.as_str()).unwrap_or("");
+ let errors = match self.platform.compile(text) {
+ Ok(_) => Vec::new(),
+ Err(es) => es,
+ };
+ let diags: Vec<Json> = errors
+ .iter()
+ .map(|e| {
+ let line = e.line.saturating_sub(1) as f64;
+ Json::obj(vec![
+ ("range", range(line, 0.0, line, 1000.0)),
+ ("severity", Json::Num(1.0)),
+ ("source", Json::s("frits")),
+ ("message", Json::s(e.msg.clone())),
+ ])
+ })
+ .collect();
+ Json::obj(vec![
+ ("jsonrpc", Json::s("2.0")),
+ ("method", Json::s("textDocument/publishDiagnostics")),
+ (
+ "params",
+ Json::obj(vec![("uri", Json::s(uri)), ("diagnostics", Json::Arr(diags))]),
+ ),
+ ])
+ }
+
+ /// The text of the line at the request's position, up to the cursor.
+ fn before_cursor(&self, params: &Json) -> String {
+ let uri = params.at(&["textDocument", "uri"]).str().unwrap_or("");
+ let line = params.at(&["position", "line"]).num().unwrap_or(0.0) as usize;
+ let ch = params.at(&["position", "character"]).num().unwrap_or(0.0) as usize;
+ let text = self.files.get(uri).map(|s| s.as_str()).unwrap_or("");
+ let l = text.lines().nth(line).unwrap_or("");
+ // LSP counts UTF-16 units; scripts are mostly ASCII, and this is a guess.
+ l.chars().take(ch).collect()
+ }
+
+ fn completion(&self, params: &Json) -> Json {
+ let before = self.before_cursor(params);
+ let word: String = before
+ .chars()
+ .rev()
+ .take_while(|c| c.is_alphanumeric() || *c == '_' || *c == '.')
+ .collect();
+ let word: String = word.chars().rev().collect();
+ let mut items = Vec::new();
+ let item = |label: String, kind: f64, detail: String, doc: Option<&String>| {
+ let mut kv = vec![
+ ("label", Json::s(label)),
+ ("kind", Json::Num(kind)),
+ ("detail", Json::s(detail)),
+ ];
+ if let Some(d) = doc {
+ kv.push(("documentation", Json::s(d.clone())));
+ }
+ Json::obj(kv)
+ };
+ if let Some((ns, _)) = word.split_once('.') {
+ for f in self.decl().fns.iter().filter(|f| f.namespace == ns) {
+ let key = format!("{}.{}", f.namespace, f.name);
+ items.push(item(
+ f.name.clone(),
+ 3.0,
+ crate::guide::signature(f),
+ self.docs.get(&key),
+ ));
+ }
+ for c in self.decl().consts.iter().filter(|c| c.namespace == ns) {
+ let key = format!("{}.{}", c.namespace, c.name);
+ let ty = crate::types::Show(&c.ty, &[]).to_string();
+ items.push(item(c.name.clone(), 21.0, ty, self.docs.get(&key)));
+ }
+ } else {
+ for k in KEYWORDS {
+ items.push(item(k.to_string(), 14.0, "keyword".into(), None));
+ }
+ let decl = self.decl();
+ for ns in decl.effects.iter().chain(&decl.modules) {
+ items.push(item(
+ ns.clone(),
+ 9.0,
+ "effect or module".into(),
+ self.docs.get(ns),
+ ));
+ }
+ for (e, ps) in &decl.events {
+ let ps: Vec<String> = ps
+ .iter()
+ .map(|t| crate::types::Show(t, &[]).to_string())
+ .collect();
+ items.push(item(e.clone(), 23.0, format!("on {e}({})", ps.join(", ")), None));
+ }
+ for f in [
+ "len", "float", "int", "log", "warn", "assert", "abs", "min", "max", "me", "send", "panic",
+ ] {
+ items.push(item(f.to_string(), 3.0, "built in".into(), None));
+ }
+ }
+ Json::Arr(items)
+ }
+
+ fn hover(&self, params: &Json) -> Json {
+ let uri = params.at(&["textDocument", "uri"]).str().unwrap_or("");
+ let line = params.at(&["position", "line"]).num().unwrap_or(0.0) as usize;
+ let ch = params.at(&["position", "character"]).num().unwrap_or(0.0) as usize;
+ let text = self.files.get(uri).map(|s| s.as_str()).unwrap_or("");
+ let chars: Vec<char> = text.lines().nth(line).unwrap_or("").chars().collect();
+ let is_word = |c: &char| c.is_alphanumeric() || *c == '_' || *c == '.';
+ let mut s = ch.min(chars.len());
+ while s > 0 && is_word(&chars[s - 1]) {
+ s -= 1;
+ }
+ let mut e = ch.min(chars.len());
+ while e < chars.len() && is_word(&chars[e]) {
+ e += 1;
+ }
+ let word: String = chars[s..e].iter().collect();
+ let found = self
+ .decl()
+ .fns
+ .iter()
+ .find(|f| format!("{}.{}", f.namespace, f.name) == word);
+ let Some(f) = found else {
+ return match self.docs.get(&word) {
+ Some(d) => Json::obj(vec![("contents", markdown(&format!("**{word}** — {d}")))]),
+ None => Json::Null,
+ };
+ };
+ let mut md = format!("```frits\n{}\n```", crate::guide::signature(f));
+ if let Some(eff) = &f.effect {
+ md.push_str(&format!("\n\nNeeds the effect `{eff}`."));
+ }
+ if let Some(d) = self.docs.get(&word) {
+ md.push_str(&format!("\n\n{d}"));
+ }
+ Json::obj(vec![("contents", markdown(&md))])
+ }
+
+ pub fn decl_source(&self) -> &str {
+ &self.decl_src
+ }
+}
+
+fn markdown(text: &str) -> Json {
+ Json::obj(vec![("kind", Json::s("markdown")), ("value", Json::s(text))])
+}
+
+fn range(l0: f64, c0: f64, l1: f64, c1: f64) -> Json {
+ let pos = |l: f64, c: f64| Json::obj(vec![("line", Json::Num(l)), ("character", Json::Num(c))]);
+ Json::obj(vec![("start", pos(l0, c0)), ("end", pos(l1, c1))])
+}
+
+/// Serve on stdin and stdout until the editor says `exit`.
+pub fn serve(decl_src: &str) -> std::io::Result<()> {
+ let mut server = Server::new(decl_src).map_err(|e| std::io::Error::other(e.to_string()))?;
+ let stdin = std::io::stdin();
+ let mut input = stdin.lock();
+ let mut out = std::io::stdout().lock();
+ loop {
+ let mut len = None;
+ loop {
+ let mut header = String::new();
+ if input.read_line(&mut header)? == 0 {
+ return Ok(());
+ }
+ let h = header.trim();
+ if h.is_empty() {
+ break;
+ }
+ if let Some(v) = h.strip_prefix("Content-Length:") {
+ len = v.trim().parse::<usize>().ok();
+ }
+ }
+ let Some(len) = len else { continue };
+ let mut body = vec![0; len];
+ input.read_exact(&mut body)?;
+ let Some(msg) = std::str::from_utf8(&body).ok().and_then(json::parse) else {
+ continue;
+ };
+ let (replies, stop) = server.handle(&msg);
+ for r in replies {
+ let text = r.to_string();
+ write!(out, "Content-Length: {}\r\n\r\n{text}", text.len())?;
+ }
+ out.flush()?;
+ if stop {
+ return Ok(());
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn req(id: f64, method: &str, params: Json) -> Json {
+ Json::obj(vec![
+ ("jsonrpc", Json::s("2.0")),
+ ("id", Json::Num(id)),
+ ("method", Json::s(method)),
+ ("params", params),
+ ])
+ }
+
+ fn note(method: &str, params: Json) -> Json {
+ Json::obj(vec![
+ ("jsonrpc", Json::s("2.0")),
+ ("method", Json::s(method)),
+ ("params", params),
+ ])
+ }
+
+ #[test]
+ fn checks_completes_hovers_and_formats() {
+ let decl =
+ "effect Prim {\n // Move it, in metres.\n fn set_pos(p: Vec3)\n}\nevent touch(name: Str)\n";
+ let mut s = Server::new(decl).unwrap();
+ let (r, _) = s.handle(&req(1.0, "initialize", Json::obj(vec![])));
+ assert_eq!(
+ r[0].at(&["result", "capabilities", "hoverProvider"]),
+ &Json::Bool(true)
+ );
+ let doc = |text: &str| {
+ Json::obj(vec![(
+ "textDocument",
+ Json::obj(vec![("uri", Json::s("file:///a.frits")), ("text", Json::s(text))]),
+ )])
+ };
+ let (r, _) = s.handle(¬e(
+ "textDocument/didOpen",
+ doc("script / Prim\non touch(name: Str) {\n let x: Int = \"no\"\n}\n"),
+ ));
+ let diags = r[0].at(&["params", "diagnostics"]);
+ let Json::Arr(d) = diags else { panic!("{diags}") };
+ assert_eq!(d.len(), 1);
+ assert_eq!(d[0].at(&["range", "start", "line"]).num(), Some(2.0));
+ assert!(
+ d[0].get("message")
+ .str()
+ .unwrap()
+ .contains("expected Int, found Str")
+ );
+
+ let at = |line: f64, ch: f64| {
+ Json::obj(vec![
+ (
+ "textDocument",
+ Json::obj(vec![("uri", Json::s("file:///a.frits"))]),
+ ),
+ (
+ "position",
+ Json::obj(vec![("line", Json::Num(line)), ("character", Json::Num(ch))]),
+ ),
+ ])
+ };
+ s.handle(¬e("textDocument/didChange", Json::obj(vec![
+ ("textDocument", Json::obj(vec![("uri", Json::s("file:///a.frits"))])),
+ ("contentChanges", Json::Arr(vec![Json::obj(vec![("text", Json::s("script / Prim\non touch(name: Str) {\n Prim.\n Prim.set_pos({x:1,y:2,z:3})\n}\n"))])])),
+ ])));
+ let (r, _) = s.handle(&req(2.0, "textDocument/completion", at(2.0, 7.0)));
+ let Json::Arr(items) = r[0].get("result") else {
+ panic!()
+ };
+ assert_eq!(items[0].get("label").str(), Some("set_pos"));
+ assert_eq!(items[0].get("documentation").str(), Some("Move it, in metres."));
+ let (r, _) = s.handle(&req(3.0, "textDocument/hover", at(3.0, 8.0)));
+ let hover = r[0].at(&["result", "contents", "value"]).str().unwrap();
+ assert!(
+ hover.contains("Prim.set_pos(") && hover.contains("Move it, in metres."),
+ "{hover}"
+ );
+ let (r, _) = s.handle(&req(4.0, "textDocument/formatting", at(0.0, 0.0)));
+ let text = r[0].get("result");
+ let Json::Arr(edits) = text else { panic!() };
+ assert!(
+ edits[0]
+ .get("newText")
+ .str()
+ .unwrap()
+ .contains(" Prim.set_pos({ x: 1, y: 2, z: 3 })")
+ );
+ let (_, stop) = s.handle(¬e("exit", Json::Null));
+ assert!(stop);
+ }
+}
diff --git a/crates/frits/src/main.rs b/crates/frits/src/main.rs
index 0d9a9fe..a39e023 100644
--- a/crates/frits/src/main.rs
+++ b/crates/frits/src/main.rs
@@ -1,5 +1,10 @@
-//! `frits run <file>` runs a script on the console platform; `frits test
-//! <file>` runs its `test` blocks.
+//! The `frits` command:
+//!
+//! - `frits run <file>` runs a script on the console platform (`on main()`);
+//! - `frits test <file>` runs its `test` blocks;
+//! - `frits fmt [--check] <file>…` formats scripts in place;
+//! - `frits lsp [--platform <decl.frits>]` serves an editor;
+//! - `frits guide [--platform <decl.frits>] [--title <t>]` writes the scripting guide.
use frits::{Cx, Level, Platform, Runtime, Status, Value};
@@ -19,10 +24,72 @@ fn console() -> Platform<()> {
p
}
+/// The value after `--name`, if given.
+fn flag(args: &[String], name: &str) -> Option<String> {
+ args.iter()
+ .position(|a| a == name)
+ .and_then(|i| args.get(i + 1))
+ .cloned()
+}
+
+fn platform_source(args: &[String]) -> String {
+ match flag(args, "--platform") {
+ Some(path) => std::fs::read_to_string(&path).unwrap_or_else(|e| {
+ eprintln!("{path}: {e}");
+ std::process::exit(2);
+ }),
+ None => CONSOLE.to_string(),
+ }
+}
+
fn main() {
let args: Vec<String> = std::env::args().collect();
+ match args.get(1).map(|s| s.as_str()) {
+ Some("lsp") => {
+ if let Err(e) = frits::lsp::serve(&platform_source(&args)) {
+ eprintln!("frits lsp: {e}");
+ std::process::exit(1);
+ }
+ return;
+ }
+ Some("guide") => {
+ let title = flag(&args, "--title").unwrap_or_else(|| "scripts".into());
+ match frits::guide::guide(&title, &platform_source(&args)) {
+ Ok(g) => print!("{g}"),
+ Err(e) => {
+ eprintln!("the platform declaration: {e}");
+ std::process::exit(1);
+ }
+ }
+ return;
+ }
+ Some("fmt") => {
+ let check = args.iter().any(|a| a == "--check");
+ let mut differ = 0;
+ for path in args[2..].iter().filter(|a| !a.starts_with("--")) {
+ let src = std::fs::read_to_string(path).unwrap_or_else(|e| {
+ eprintln!("{path}: {e}");
+ std::process::exit(2);
+ });
+ let out = frits::fmt::format(&src);
+ if out != src {
+ differ += 1;
+ if check {
+ println!("{path}: not formatted");
+ } else if let Err(e) = std::fs::write(path, out) {
+ eprintln!("{path}: {e}");
+ std::process::exit(2);
+ }
+ }
+ }
+ std::process::exit(i32::from(check && differ > 0));
+ }
+ _ => {}
+ }
let (Some(cmd @ ("run" | "test")), Some(path)) = (args.get(1).map(|s| s.as_str()), args.get(2)) else {
- eprintln!("usage: frits run <file.frits>\n frits test <file.frits>");
+ eprintln!(
+ "usage: frits run <file.frits>\n frits test <file.frits>\n frits fmt [--check] <file.frits>…\n frits lsp [--platform <decl.frits>]\n frits guide [--platform <decl.frits>] [--title <title>]"
+ );
std::process::exit(2);
};
let src = std::fs::read_to_string(path).unwrap_or_else(|e| {
diff --git a/docs/design.md b/docs/design.md
index c6b7e12..73baa40 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -120,6 +120,25 @@ on timer() {
(a value the script holds and passes back, never builds or looks into). This
is the capability: a script that was never given a `Door` cannot open one.
+## Tools
+
+- `frits fmt [--check] <file>…` gives every script one layout. It works on the
+ text, so comments and how numbers are written survive; brackets opened on
+ one line indent what follows by one level.
+- `frits lsp [--platform <decl.frits>]` is a language server for any editor:
+ errors as you type (a whole line, since errors carry lines, not columns),
+ completion after `Prim.` with each function's signature and explanation,
+ hover, and formatting. It checks against the platform declaration it is
+ given, so a Cartopolis prim script is checked against the simulator's.
+- `frits guide [--platform <decl.frits>] [--title <t>]` writes the scripting
+ guide as Markdown from the declaration: every effect, module, function,
+ event and type, with the comment above each in the declaration as its
+ explanation, and a page on the language whose examples a test compiles. A
+ host serves it (Cartopolis's MCP `scripting_guide`), so it cannot drift from
+ what scripts can call.
+- `frits test <file>` runs a script's `test` blocks; `frits run <file>` runs it
+ on the console platform.
+
## The platform
A host describes what it offers in Frits, and binds Rust functions to it:
@@ -206,7 +225,8 @@ In the order they are likely to matter:
- Untrusted-origin labels (text from another person cannot steer what an
agent or script does): not designed yet, a question for the owner.
- `spawn` from inside a script, and supervisors; the host starts processes.
-- A language server, formatter and debugger.
+- A debugger (breakpoints, stepping): the VM's state is plain data, so it is
+ within reach, but nothing is built.
- `view` markup on the component library; AOT for Pinnacle apps; wasm.
Known gaps in what is built: