Skip to main content

decl_lang/
repl.rs

1//! The REPL (docs/tooling/02_repl.md) — a port of the reference
2//! implementation's repl.ts: an interactive session over a universe —
3//! expressions evaluated partially, session outputs and declarations,
4//! documents bound and edited with exact undo, and the command-line verbs
5//! root for root. Everything it prints goes to standard output; a scripted
6//! session (`--script`) prints the transcript the terminal would show, so
7//! the three implementations can be diffed.
8use crate::session::{
9    fmt_diag, parse_decl, parse_expr, pretty_json, BindSource, EditKind, Mode, Op, RenderOverrides,
10    Rendered, Session, SessionError,
11};
12use regex::Regex;
13use std::io::{BufRead, IsTerminal, Read, Write};
14
15/// the `:` commands — `name args`, what it does, its group (docs/tooling/02_repl.md
16/// §2.4); the help text and completion read this table
17pub const COMMANDS: &[(&str, &str, &str)] = &[
18    // the universe
19    (
20        ":load file.decl",
21        "open the universe from an entry module (a new session)",
22        "universe",
23    ),
24    (
25        ":reload",
26        "re-read every module of the universe from disk",
27        "universe",
28    ),
29    (
30        ":roots",
31        "the roots of the universe and of the session",
32        "universe",
33    ),
34    // documents
35    (
36        ":bind name=doc.json",
37        "bind a JSON file to an input",
38        "documents",
39    ),
40    (
41        ":bind name { … }",
42        "bind an inline JSON document",
43        "documents",
44    ),
45    (
46        ":bind name = expr",
47        "bind the value of an expression as the document",
48        "documents",
49    ),
50    (":unbind name", "drop the binding", "documents"),
51    (
52        ":create path = expr",
53        "add a member, entry, or element at a path of a document",
54        "documents",
55    ),
56    (
57        ":update path = expr",
58        "replace the value at a path of a document",
59        "documents",
60    ),
61    (
62        ":remove path",
63        "remove the value at a path of a document",
64        "documents",
65    ),
66    (
67        ":diff name",
68        "the document against what it started from",
69        "documents",
70    ),
71    (
72        ":save name=file",
73        "write the document of a root to a file",
74        "documents",
75    ),
76    // session declarations
77    (":drop name", "remove a session declaration", "declarations"),
78    (
79        ":write file.decl",
80        "write the scratch module to a file",
81        "declarations",
82    ),
83    (
84        ":session",
85        "the session's declarations and documents",
86        "declarations",
87    ),
88    (
89        ":reset",
90        "drop every binding, edit, and declaration",
91        "declarations",
92    ),
93    // evaluation and validation
94    (":check", "static diagnostics of every module", "evaluation"),
95    (
96        ":evaluate [--format f] [--indent n] [--template p] [root…]",
97        "full evaluation: the documents of the roots, in their declared forms",
98        "evaluation",
99    ),
100    (
101        ":validate [root…]",
102        "full validation: every diagnostic, then a verdict per root",
103        "evaluation",
104    ),
105    (
106        ":fmt",
107        "the scratch module, canonically formatted",
108        "evaluation",
109    ),
110    // inspection
111    (
112        ":type expr",
113        "the static type of an expression",
114        "inspection",
115    ),
116    (
117        ":doc name",
118        "a declaration and its documentation",
119        "inspection",
120    ),
121    (":path expr", "the canonical path of a place", "inspection"),
122    (
123        ":trace path",
124        "the derivation of a place, or its root cause",
125        "inspection",
126    ),
127    (
128        ":complete text",
129        "the completions offered at the end of the text",
130        "inspection",
131    ),
132    // history
133    (":undo [n]", "step the log back", "history"),
134    (":redo [n]", "step forward again", "history"),
135    (
136        ":history [file]",
137        "the log, or write it as a session file",
138        "history",
139    ),
140    // the session
141    (":time", "wall time of the last evaluation", "session"),
142    (":set pretty|compact", "value printing", "session"),
143    (":help [command]", "these commands", "session"),
144    (":quit", "end the session", "session"),
145];
146
147fn command_names() -> Vec<&'static str> {
148    let mut out: Vec<&'static str> = vec![];
149    for c in COMMANDS {
150        let n = c.0.split(' ').next().unwrap_or("");
151        if !out.contains(&n) {
152            out.push(n);
153        }
154    }
155    out
156}
157
158const KEYWORDS: &[&str] = &[
159    "if", "then", "else", "for", "in", "match", "with", "matches", "true", "false", "null",
160    "export",
161];
162
163fn is_decl_head(t: &str) -> bool {
164    Regex::new(
165        r"^\s*(?:export\s+)?(type|const|func|output|input|diagnostic|dimension|unit|import)\b",
166    )
167    .unwrap()
168    .is_match(t)
169}
170fn is_ident(s: &str) -> bool {
171    Regex::new(r"^[A-Za-z_][A-Za-z0-9_]*$").unwrap().is_match(s)
172}
173
174/// `name = expr` / `name: T = expr` — a session output (the reference's OUTPUT_HEAD)
175fn output_head(t: &str) -> Option<(String, Option<String>, String)> {
176    let re = Regex::new(r"^\s*([A-Za-z_][A-Za-z0-9_]*)\s*").unwrap();
177    let m = re.captures(t)?;
178    let name = m.get(1).unwrap().as_str().to_string();
179    let mut rest = &t[m.get(0).unwrap().end()..];
180    let mut ty: Option<String> = None;
181    if let Some(r) = rest.strip_prefix(':') {
182        let r = r.trim_start();
183        let eq = r.find('=')?;
184        let type_part = &r[..eq];
185        if type_part.trim_end().is_empty() {
186            return None;
187        }
188        ty = Some(type_part.trim().to_string());
189        rest = &r[eq..];
190    }
191    let rest = rest.strip_prefix('=')?;
192    if rest.starts_with('=') {
193        return None;
194    }
195    let expr = rest.trim_start();
196    if expr.is_empty() {
197        return None;
198    }
199    Some((name, ty, expr.trim().to_string()))
200}
201
202/// does the input so far leave an expression open (§2.9)?
203pub fn needs_more(text: &str) -> bool {
204    let cs: Vec<char> = text.chars().collect();
205    let mut depth = 0i32;
206    let mut in_str: Option<char> = None;
207    let mut i = 0;
208    while i < cs.len() {
209        let c = cs[i];
210        if let Some(q) = in_str {
211            if c == '\\' {
212                i += 1;
213            } else if c == q {
214                in_str = None;
215            }
216            i += 1;
217            continue;
218        }
219        if c == '"' || c == '`' {
220            in_str = Some(c);
221        } else if c == '/' && cs.get(i + 1) == Some(&'/') {
222            match cs[i..].iter().position(|&x| x == '\n') {
223                Some(nl) => i += nl,
224                None => break,
225            }
226        } else if "{[(".contains(c) {
227            depth += 1;
228        } else if "}])".contains(c) {
229            depth -= 1;
230        }
231        i += 1;
232    }
233    if depth > 0 || in_str == Some('`') {
234        return true;
235    }
236    if text.trim_start().starts_with(':') {
237        return false; // a command: only an open bracket continues it
238    }
239    let no_comment = Regex::new(r"//[^\n]*$")
240        .unwrap()
241        .replace(text, "")
242        .to_string();
243    let tail = no_comment.trim_end();
244    Regex::new(r"(?:[+\-*/%<>=!&|?:,]|\bthen|\belse|\bin|\bwith|=>)$")
245        .unwrap()
246        .is_match(tail)
247}
248
249/// the read-eval-print loop over a session: lines in, answers out
250pub struct Repl {
251    /// the session the lines act on
252    pub session: Session,
253    /// `--compact`: documents printed in the wire form, one line each
254    pub compact: bool,
255    /// how many inputs were refused (`error:` lines): the exit status
256    pub errors: usize,
257    /// `:quit` was given, or the input ended
258    pub quit_requested: bool,
259    out: Box<dyn Fn(&str)>,
260    buffer: Vec<String>,
261}
262
263impl Repl {
264    /// A REPL printing through `out`, over the universe of `entry` (none: a scratch session).
265    pub fn new(out: Box<dyn Fn(&str)>, entry: Option<&str>) -> Repl {
266        Repl {
267            session: Session::new(entry),
268            compact: false,
269            errors: 0,
270            quit_requested: false,
271            out,
272            buffer: vec![],
273        }
274    }
275
276    /// feed one line; returns true when the input is complete and was handled
277    pub fn line(&mut self, text: &str) -> bool {
278        self.buffer.push(text.to_string());
279        let whole = self.buffer.join("\n");
280        if needs_more(&whole) {
281            return false;
282        }
283        self.buffer.clear();
284        self.input(&whole);
285        true
286    }
287    /// drop the input being continued (Ctrl-C at a continuation prompt)
288    pub fn discard(&mut self) {
289        self.buffer.clear();
290    }
291    /// Whether the lines so far continue an input: an open brace, bracket, or template.
292    pub fn pending(&self) -> bool {
293        !self.buffer.is_empty()
294    }
295
296    fn out(&self, line: &str) {
297        (self.out)(line)
298    }
299    fn error(&mut self, msg: &str) {
300        self.errors += 1;
301        self.out(&format!("error: {msg}"));
302    }
303    fn diag(&self, d: &crate::semantics::Diag, in_file: Option<&str>) {
304        self.out(&fmt_diag(d, in_file));
305    }
306    fn value(&self, json: &str) {
307        if self.compact {
308            self.out(json);
309        } else {
310            self.out(&pretty_json(json));
311        }
312    }
313
314    /// One line of input: completes or continues a pending input, then evaluates it.
315    pub fn input(&mut self, text: &str) {
316        let t = text.trim();
317        if t.is_empty() || (t.starts_with("//") && !t.starts_with("///")) {
318            return;
319        }
320        let r = if t.starts_with(':') {
321            self.command(t)
322        } else if is_decl_head(t) {
323            self.add_declaration(t)
324        } else if let Some((name, ty, expr)) =
325            output_head(t).filter(|(n, _, _)| !KEYWORDS.contains(&n.as_str()))
326        {
327            self.session_output(&name, ty, &expr)
328        } else {
329            self.expression(t)
330        };
331        if let Err(e) = r {
332            self.error(&e.0);
333        }
334    }
335
336    fn expression(&mut self, text: &str) -> Result<(), SessionError> {
337        parse_expr(text)?;
338        let r = self.session.evaluate_expr(text)?;
339        for d in &r.diags {
340            self.diag(d, None);
341        }
342        match (&r.error, &r.value) {
343            (Some((code, message)), _) => {
344                if !message.is_empty() {
345                    self.out(&format!(
346                        "error{}: {message}",
347                        code.as_ref().map(|c| format!(" [{c}]")).unwrap_or_default()
348                    ));
349                }
350                self.out("(invalid)");
351            }
352            (None, Some(v)) => self.value(v),
353            (None, None) => self.out("(invalid)"),
354        }
355        self.out("(partial)");
356        Ok(())
357    }
358    fn add_declaration(&mut self, text: &str) -> Result<(), SessionError> {
359        let (_, name) = parse_decl(text)?;
360        self.session.apply(Op::Declare {
361            name,
362            text: text.trim().to_string(),
363        })
364    }
365    fn session_output(
366        &mut self,
367        name: &str,
368        ty: Option<String>,
369        expr: &str,
370    ) -> Result<(), SessionError> {
371        parse_expr(expr)?;
372        if let Some(t) = &ty {
373            parse_decl(&format!("output {name}: {t} = 0"))?;
374        }
375        self.session.apply(Op::Output {
376            name: name.to_string(),
377            ty,
378            expr: expr.to_string(),
379        })
380    }
381
382    fn command(&mut self, t: &str) -> Result<(), SessionError> {
383        let sp = t.find(char::is_whitespace);
384        let cmd = match sp {
385            Some(i) => &t[..i],
386            None => t,
387        };
388        let rest = match sp {
389            Some(i) => t[i + 1..].trim(),
390            None => "",
391        }
392        .to_string();
393        let cmd = cmd.to_string();
394        let no_args = |rest: &str| -> Result<(), SessionError> {
395            if !rest.is_empty() {
396                Err(SessionError(format!("{cmd} takes no argument")))
397            } else {
398                Ok(())
399            }
400        };
401        let one_name = |rest: &str| -> Result<String, SessionError> {
402            if !is_ident(rest) {
403                Err(SessionError(format!("{cmd} expects a name")))
404            } else {
405                Ok(rest.to_string())
406            }
407        };
408        let entry_abs = self.session.entry_abs().display().to_string();
409        let in_file = |file: &str| -> Option<String> {
410            if file == entry_abs {
411                None
412            } else {
413                Some(file.to_string())
414            }
415        };
416        match cmd.as_str() {
417            ":load" => {
418                if rest.is_empty() {
419                    return Err(SessionError(":load expects a file".into()));
420                }
421                self.session = Session::new(Some(&rest));
422                Ok(())
423            }
424            ":reload" => {
425                no_args(&rest)?;
426                let op = self.session.reload_op();
427                self.session.apply(op)
428            }
429            ":roots" => {
430                no_args(&rest)?;
431                let rs = self.session.roots();
432                if rs.is_empty() {
433                    self.out("(no roots)");
434                    return Ok(());
435                }
436                for r in rs {
437                    let status = if r.session {
438                        "session".to_string()
439                    } else if r.kind == "output" {
440                        if r.binding == "detached" {
441                            "detached".into()
442                        } else if r.exported {
443                            "exported".into()
444                        } else {
445                            "local".into()
446                        }
447                    } else {
448                        r.binding.clone()
449                    };
450                    let line = format!(
451                        "{:<7} {:<16} {:<12} {:<16} {}{}",
452                        r.kind,
453                        r.name,
454                        status,
455                        r.module,
456                        r.detail,
457                        if r.edited { " (edited)" } else { "" }
458                    );
459                    self.out(line.trim_end());
460                }
461                Ok(())
462            }
463            ":bind" => {
464                let eq_re = Regex::new(r"^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*([\s\S]+)$").unwrap();
465                if let Some(m) = eq_re.captures(&rest) {
466                    let name = m.get(1).unwrap().as_str().to_string();
467                    let val = m.get(2).unwrap().as_str();
468                    let after_name = &rest[name.len()..];
469                    let starts_bracket = val.trim().starts_with('[') || val.trim().starts_with('{');
470                    if !starts_bracket && !after_name.starts_with(char::is_whitespace) {
471                        // name=file (no spaces around =)
472                        let file = val.trim().to_string();
473                        let text = std::fs::read_to_string(&file)
474                            .map_err(|_| SessionError(format!("cannot read {file}")))?;
475                        return self.session.apply(Op::Bind {
476                            name,
477                            src: BindSource::File { file, text },
478                        });
479                    }
480                    return self.session.apply(Op::Bind {
481                        name,
482                        src: BindSource::Expr {
483                            text: val.trim().to_string(),
484                        },
485                    });
486                }
487                let inline_re = Regex::new(r"^([A-Za-z_][A-Za-z0-9_]*)\s+([\[{][\s\S]*)$").unwrap();
488                if let Some(m) = inline_re.captures(&rest) {
489                    let name = m.get(1).unwrap().as_str().to_string();
490                    let text = m.get(2).unwrap().as_str().to_string();
491                    return self.session.apply(Op::Bind {
492                        name,
493                        src: BindSource::Inline { text },
494                    });
495                }
496                Err(SessionError(
497                    ":bind expects name=doc.json, name { … }, or name = expr".into(),
498                ))
499            }
500            ":unbind" => {
501                let name = one_name(&rest)?;
502                self.session.apply(Op::Unbind { name })
503            }
504            ":create" | ":update" => {
505                let re = Regex::new(r"^(\S+)\s*=\s*([\s\S]+)$").unwrap();
506                let Some(m) = re.captures(&rest) else {
507                    return Err(SessionError(format!("{cmd} expects path = expr")));
508                };
509                let kind = if cmd == ":create" {
510                    EditKind::Create
511                } else {
512                    EditKind::Update
513                };
514                self.session.apply(Op::Edit {
515                    kind,
516                    path: m.get(1).unwrap().as_str().to_string(),
517                    expr: Some(m.get(2).unwrap().as_str().trim().to_string()),
518                })
519            }
520            ":remove" => {
521                if rest.is_empty() || rest.contains(char::is_whitespace) {
522                    return Err(SessionError(":remove expects a path".into()));
523                }
524                self.session.apply(Op::Edit {
525                    kind: EditKind::Remove,
526                    path: rest.clone(),
527                    expr: None,
528                })
529            }
530            ":diff" => {
531                let name = one_name(&rest)?;
532                for l in self.session.diff(&name)? {
533                    self.out(&l);
534                }
535                Ok(())
536            }
537            ":save" => {
538                let re = Regex::new(r"^([A-Za-z_][A-Za-z0-9_]*)=(\S+)$").unwrap();
539                let Some(m) = re.captures(&rest) else {
540                    return Err(SessionError(":save expects name=file".into()));
541                };
542                self.session
543                    .save(m.get(1).unwrap().as_str(), m.get(2).unwrap().as_str())
544            }
545            ":drop" => {
546                let name = one_name(&rest)?;
547                self.session.apply(Op::Drop { name })
548            }
549            ":write" => {
550                if rest.is_empty() {
551                    return Err(SessionError(":write expects a file".into()));
552                }
553                self.session.write(&rest)
554            }
555            ":session" => {
556                no_args(&rest)?;
557                let ls = self.session.session_lines();
558                if ls.is_empty() {
559                    self.out("(empty session)");
560                }
561                for l in ls {
562                    self.out(&l);
563                }
564                Ok(())
565            }
566            ":reset" => {
567                no_args(&rest)?;
568                self.session.apply(Op::Reset)
569            }
570            ":check" => {
571                no_args(&rest)?;
572                let cs = self.session.check();
573                for (file, d) in &cs {
574                    self.diag(d, in_file(file).as_deref());
575                }
576                if cs.is_empty() {
577                    self.out("ok");
578                }
579                Ok(())
580            }
581            ":evaluate" => {
582                // the overrides of a declared form come before the roots (05_render.md §8)
583                let words: Vec<String> = if rest.is_empty() {
584                    vec![]
585                } else {
586                    Regex::new(r"[\s,]+")
587                        .unwrap()
588                        .split(&rest)
589                        .filter(|s| !s.is_empty())
590                        .map(|s| s.to_string())
591                        .collect()
592                };
593                let mut over = RenderOverrides::default();
594                let mut names: Vec<String> = vec![];
595                let mut i = 0;
596                while i < words.len() {
597                    let w = words[i].as_str();
598                    if w == "--format" || w == "--indent" || w == "--template" {
599                        i += 1;
600                        let Some(v) = words.get(i) else {
601                            return Err(SessionError(format!("{w} expects a value")));
602                        };
603                        if w == "--format" {
604                            if v != "json" && v != "yaml" {
605                                return Err(SessionError(format!(
606                                    "--format expects json or yaml, got {v}"
607                                )));
608                            }
609                            over.yaml = Some(v == "yaml");
610                        } else if w == "--indent" {
611                            let digits = v.len() <= 2
612                                && v.bytes().all(|b| b.is_ascii_digit())
613                                && !(v.len() == 2 && v.starts_with('0'));
614                            let ok = digits && v.parse::<usize>().is_ok_and(|n| n <= 16);
615                            if !ok {
616                                return Err(SessionError(format!(
617                                    "--indent expects an integer in 0..16, got {v}"
618                                )));
619                            }
620                            over.indent = Some(v.parse().unwrap());
621                        } else {
622                            over.template = Some(v.clone());
623                        }
624                    } else if w.starts_with("--") {
625                        return Err(SessionError(format!("unknown option {w}")));
626                    } else {
627                        names.push(w.to_string());
628                    }
629                    i += 1;
630                }
631                let (run, docs, exported) = self.session.evaluate(&names)?;
632                for d in &run.load_diags {
633                    self.diag(d, None);
634                }
635                for (file, d) in &run.checks {
636                    self.diag(d, in_file(file).as_deref());
637                }
638                for d in &run.session_checks {
639                    self.diag(d, None);
640                }
641                for d in &run.diags {
642                    self.diag(d, None);
643                }
644                if run.entry.is_none() {
645                    return Ok(());
646                }
647                if run.eng.is_none() {
648                    self.out("(not evaluated)");
649                    return Ok(());
650                }
651                if exported {
652                    if docs.iter().any(|(_, j)| j.is_none()) {
653                        self.out("(invalid)");
654                        return Ok(());
655                    }
656                    let text = format!(
657                        "{{{}}}",
658                        docs.iter()
659                            .map(|(n, j)| format!(
660                                "{}:{}",
661                                crate::semantics::json_str(n),
662                                j.clone().unwrap_or_default()
663                            ))
664                            .collect::<Vec<_>>()
665                            .join(",")
666                    );
667                    self.value(&text);
668                    return Ok(());
669                }
670                let many = docs.len() > 1;
671                for (name, json) in &docs {
672                    if many {
673                        self.out(&format!("{name}:"));
674                    }
675                    let Some(j) = json else {
676                        self.out("(invalid)");
677                        continue;
678                    };
679                    // the root's declared form, with the overrides (05_render.md §8)
680                    match self.session.render(&run, name, &over) {
681                        None => self.value(j),
682                        Some(Rendered::Error { diag, file }) => {
683                            self.diag(&diag, file.as_deref());
684                            self.out("(invalid)");
685                        }
686                        Some(Rendered::Files(files)) => {
687                            for (p, t) in files {
688                                self.out(&format!("# {p}"));
689                                self.out(t.strip_suffix('\n').unwrap_or(&t));
690                            }
691                        }
692                        Some(Rendered::Text { text, .. }) => {
693                            self.out(text.strip_suffix('\n').unwrap_or(&text));
694                        }
695                    }
696                }
697                Ok(())
698            }
699            ":validate" => {
700                let names: Vec<String> = if rest.is_empty() {
701                    vec![]
702                } else {
703                    Regex::new(r"[\s,]+")
704                        .unwrap()
705                        .split(&rest)
706                        .filter(|s| !s.is_empty())
707                        .map(|s| s.to_string())
708                        .collect()
709                };
710                let (run, verdicts, diags) = self.session.validate(&names)?;
711                for d in &run.load_diags {
712                    self.diag(d, None);
713                }
714                for (file, d) in &run.checks {
715                    self.diag(d, in_file(file).as_deref());
716                }
717                for d in &run.session_checks {
718                    self.diag(d, None);
719                }
720                if run.eng.is_none() {
721                    self.out("(not evaluated)");
722                    return Ok(());
723                }
724                for d in &diags {
725                    self.diag(d, None);
726                }
727                if verdicts.is_empty() {
728                    self.out("(no roots)");
729                }
730                for (name, errors, warnings) in &verdicts {
731                    let n = |k: usize, w: &str| format!("{k} {w}{}", if k == 1 { "" } else { "s" });
732                    if *errors == 0 && *warnings == 0 {
733                        self.out(&format!("{name}: ok"));
734                    } else {
735                        let parts: Vec<String> = [
736                            if *errors > 0 {
737                                n(*errors, "error")
738                            } else {
739                                String::new()
740                            },
741                            if *warnings > 0 {
742                                n(*warnings, "warning")
743                            } else {
744                                String::new()
745                            },
746                        ]
747                        .into_iter()
748                        .filter(|s| !s.is_empty())
749                        .collect();
750                        self.out(&format!("{name}: {}", parts.join(", ")));
751                    }
752                }
753                Ok(())
754            }
755            ":fmt" => {
756                no_args(&rest)?;
757                let t = self.session.fmt()?;
758                if t.is_empty() {
759                    self.out("(empty session)");
760                } else {
761                    self.out(t.strip_suffix('\n').unwrap_or(&t));
762                }
763                Ok(())
764            }
765            ":type" => {
766                if rest.is_empty() {
767                    return Err(SessionError(":type expects an expression".into()));
768                }
769                let (ty, maybe_absent, diags) = self.session.type_of(&rest)?;
770                for d in &diags {
771                    self.diag(d, None);
772                }
773                self.out(&format!(
774                    "{ty}{}",
775                    if maybe_absent { "  (maybe absent)" } else { "" }
776                ));
777                Ok(())
778            }
779            ":doc" => {
780                if rest.is_empty() {
781                    return Err(SessionError(":doc expects a name".into()));
782                }
783                for l in self.session.doc_of(&rest)? {
784                    self.out(&l);
785                }
786                Ok(())
787            }
788            ":path" => {
789                if rest.is_empty() {
790                    return Err(SessionError(":path expects an expression".into()));
791                }
792                let p = self.session.path_of(&rest)?;
793                self.out(&p);
794                Ok(())
795            }
796            ":trace" => {
797                if rest.is_empty() || rest.contains(char::is_whitespace) {
798                    return Err(SessionError(":trace expects a path".into()));
799                }
800                for l in self.session.trace(&rest)? {
801                    self.out(&l);
802                }
803                Ok(())
804            }
805            ":complete" => {
806                let names = command_names();
807                let cs = self.session.complete(&rest, &names);
808                if cs.is_empty() {
809                    self.out("(no completions)");
810                }
811                for c in cs {
812                    self.out(&c);
813                }
814                Ok(())
815            }
816            ":undo" | ":redo" => {
817                let n = if rest.is_empty() {
818                    Some(1)
819                } else {
820                    js_parse_int(&rest)
821                };
822                let Some(n) = n.filter(|n| *n >= 1) else {
823                    return Err(SessionError(format!("{cmd} expects a count")));
824                };
825                let k = if cmd == ":undo" {
826                    self.session.undo(n as usize)
827                } else {
828                    self.session.redo(n as usize)
829                };
830                if k == 0 {
831                    self.out(if cmd == ":undo" {
832                        "nothing to undo"
833                    } else {
834                        "nothing to redo"
835                    });
836                }
837                Ok(())
838            }
839            ":history" => {
840                if !rest.is_empty() {
841                    let text = format!("{}\n", self.session.script_lines().join("\n"));
842                    return std::fs::write(&rest, text)
843                        .map_err(|_| SessionError(format!("cannot write {rest}")));
844                }
845                for l in self.session.history_lines() {
846                    self.out(&l);
847                }
848                Ok(())
849            }
850            ":time" => {
851                no_args(&rest)?;
852                match self.session.last_timing.get() {
853                    None => self.out("nothing evaluated yet"),
854                    Some(t) => {
855                        let step = match (t.recomputed, t.slots) {
856                            (Some(n), Some(m)) => format!(", recomputed {n} of {m} slots"),
857                            _ => String::new(),
858                        };
859                        self.out(&format!("total {:.1} ms (load {:.1} ms, check {:.1} ms, bind {:.1} ms, evaluate {:.1} ms){step}", t.total, t.load, t.check, t.bind, t.evaluate))
860                    }
861                }
862                Ok(())
863            }
864            ":set" => {
865                match rest.as_str() {
866                    "pretty" => self.compact = false,
867                    "compact" => self.compact = true,
868                    _ => return Err(SessionError(":set expects pretty or compact".into())),
869                }
870                Ok(())
871            }
872            ":help" => {
873                let want = if rest.is_empty() {
874                    None
875                } else {
876                    Some(if rest.starts_with(':') {
877                        rest.clone()
878                    } else {
879                        format!(":{rest}")
880                    })
881                };
882                let rows: Vec<&(&str, &str, &str)> = COMMANDS
883                    .iter()
884                    .filter(|c| {
885                        want.as_ref()
886                            .map(|w| c.0.split(' ').next() == Some(w.as_str()))
887                            .unwrap_or(true)
888                    })
889                    .collect();
890                if rows.is_empty() {
891                    return Err(SessionError(format!("unknown command {rest}")));
892                }
893                let mut cat = "";
894                for (form, what, c) in rows {
895                    if want.is_none() && *c != cat {
896                        cat = c;
897                        self.out(&format!("{cat}:"));
898                    }
899                    self.out(&format!("  {:<24} {what}", form));
900                }
901                Ok(())
902            }
903            ":quit" => {
904                no_args(&rest)?;
905                self.quit_requested = true;
906                Ok(())
907            }
908            _ => Err(SessionError(format!("unknown command {cmd}"))),
909        }
910    }
911}
912
913/// JavaScript's parseInt(text, 10): leading digits, or NaN (None)
914fn js_parse_int(s: &str) -> Option<i64> {
915    let t = s.trim_start();
916    let (neg, digits) = match t.strip_prefix('-') {
917        Some(r) => (true, r),
918        None => (false, t.strip_prefix('+').unwrap_or(t)),
919    };
920    let n: String = digits.chars().take_while(|c| c.is_ascii_digit()).collect();
921    if n.is_empty() {
922        return None;
923    }
924    let v: i64 = n.parse().ok()?;
925    Some(if neg { -v } else { v })
926}
927
928// ---------------- the command ----------------
929/// The `decl repl` command line: the arguments, then the scripted or the
930/// interactive session. Returns the exit status.
931pub fn run_repl(args: Vec<String>) -> i32 {
932    let mut entry: Option<String> = None;
933    let mut script: Option<String> = None;
934    let mut compact = false;
935    let mut inputs: Vec<String> = vec![];
936    let mut i = 0;
937    while i < args.len() {
938        let a = &args[i];
939        if a == "--script" {
940            i += 1;
941            script = args.get(i).cloned();
942        } else if a == "--input" {
943            i += 1;
944            if let Some(s) = args.get(i) {
945                inputs.push(s.clone());
946            }
947        } else if a == "--compact" {
948            compact = true;
949        } else if a.starts_with("--") {
950            eprintln!("unknown option {a}");
951            return 2;
952        } else if entry.is_none() {
953            entry = Some(a.clone());
954        } else {
955            eprintln!("decl repl takes one entry file");
956            return 2;
957        }
958        i += 1;
959    }
960    if script.is_none() && entry.is_none() && !inputs.is_empty() {
961        eprintln!("--input needs an entry file");
962        return 2;
963    }
964    for spec in &inputs {
965        if !spec.contains('=') {
966            eprintln!("--input expects name=doc.json, got {spec}");
967            return 2;
968        }
969    }
970
971    // without a terminal there is no line editor: standard input is the script (§9)
972    if script.is_none() && !std::io::stdin().is_terminal() {
973        script = Some("-".into());
974    }
975
976    let out: Box<dyn Fn(&str)> = Box::new(|l: &str| {
977        let stdout = std::io::stdout();
978        let mut h = stdout.lock();
979        let _ = writeln!(h, "{l}");
980    });
981    let mut repl = Repl::new(out, entry.as_deref());
982    repl.compact = compact;
983    for spec in &inputs {
984        repl.input(&format!(":bind {spec}"));
985    }
986
987    if let Some(script) = script {
988        let text = if script == "-" {
989            let mut s = String::new();
990            std::io::stdin().read_to_string(&mut s).map(|_| s).ok()
991        } else {
992            std::fs::read_to_string(&script).ok()
993        };
994        let Some(text) = text else {
995            eprintln!("cannot read {script}");
996            return 2;
997        };
998        let text = text.strip_suffix('\n').unwrap_or(&text).to_string();
999        for l in text.split('\n') {
1000            let prompt = if repl.pending() { ". " } else { "> " };
1001            println!("{prompt}{l}");
1002            repl.line(l);
1003            if repl.quit_requested {
1004                break;
1005            }
1006        }
1007        if repl.pending() {
1008            repl.line("");
1009        }
1010        return if repl.errors > 0 { 1 } else { 0 };
1011    }
1012
1013    // interactive: the line editor, with history (kept across sessions in
1014    // ~/.decl_history) and completion on Tab (docs/tooling/02_repl.md §2, §7)
1015    let repl = std::rc::Rc::new(std::cell::RefCell::new(repl));
1016    // completion lists the candidates (the shell's way), not cycling through them
1017    let config = rustyline::Config::builder()
1018        .completion_type(rustyline::CompletionType::List)
1019        .build();
1020    let mut rl: rustyline::Editor<DeclHelper, rustyline::history::DefaultHistory> =
1021        match rustyline::Editor::with_config(config) {
1022            Ok(e) => e,
1023            Err(_) => return run_plain(repl),
1024        };
1025    rl.set_helper(Some(DeclHelper { repl: repl.clone() }));
1026    let history =
1027        std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join(".decl_history"));
1028    if let Some(h) = &history {
1029        let _ = rl.load_history(h);
1030    }
1031    loop {
1032        let prompt = if repl.borrow().pending() { ". " } else { "> " };
1033        match rl.readline(prompt) {
1034            Ok(l) => {
1035                if !l.trim().is_empty() {
1036                    let _ = rl.add_history_entry(l.as_str());
1037                }
1038                repl.borrow_mut().line(&l);
1039                if repl.borrow().quit_requested {
1040                    break;
1041                }
1042            }
1043            Err(rustyline::error::ReadlineError::Interrupted) => {
1044                repl.borrow_mut().discard();
1045                continue;
1046            }
1047            Err(_) => break,
1048        }
1049    }
1050    if let Some(h) = &history {
1051        let _ = rl.save_history(h);
1052    }
1053    let _ = Mode::Full;
1054    0
1055}
1056
1057// without a terminal the editor cannot start: a plain line loop
1058fn run_plain(repl: std::rc::Rc<std::cell::RefCell<Repl>>) -> i32 {
1059    let stdin = std::io::stdin();
1060    let mut lines = stdin.lock().lines();
1061    loop {
1062        print!("{}", if repl.borrow().pending() { ". " } else { "> " });
1063        let _ = std::io::stdout().flush();
1064        let Some(Ok(l)) = lines.next() else { break };
1065        repl.borrow_mut().line(&l);
1066        if repl.borrow().quit_requested {
1067            break;
1068        }
1069    }
1070    0
1071}
1072
1073/// the line editor's helper: completion from the session (the tail of the
1074/// trailing token completed, as the reference's completer does)
1075struct DeclHelper {
1076    repl: std::rc::Rc<std::cell::RefCell<Repl>>,
1077}
1078impl rustyline::completion::Completer for DeclHelper {
1079    type Candidate = rustyline::completion::Pair;
1080    fn complete(
1081        &self,
1082        line: &str,
1083        pos: usize,
1084        _ctx: &rustyline::Context<'_>,
1085    ) -> rustyline::Result<(usize, Vec<Self::Candidate>)> {
1086        let head = &line[..pos];
1087        let candidates: Vec<String> = self
1088            .repl
1089            .borrow_mut()
1090            .session
1091            .complete(head, &command_names())
1092            .into_iter()
1093            .map(|c| c.split("  ").next().unwrap_or("").to_string())
1094            .collect();
1095        let tok_start = head
1096            .rfind(|c: char| !(c.is_alphanumeric() || "_$:.[]\"".contains(c)))
1097            .map(|i| i + 1)
1098            .unwrap_or(0);
1099        let tok = &head[tok_start..];
1100        let tail_start = tok
1101            .rfind('.')
1102            .map(|i| tok_start + i + 1)
1103            .unwrap_or(tok_start);
1104        let tail = &head[tail_start..];
1105        let pairs = candidates
1106            .into_iter()
1107            .filter(|c| c.starts_with(tail))
1108            .map(|c| rustyline::completion::Pair {
1109                display: c.clone(),
1110                replacement: c,
1111            })
1112            .collect();
1113        Ok((tail_start, pairs))
1114    }
1115}
1116impl rustyline::hint::Hinter for DeclHelper {
1117    type Hint = String;
1118}
1119impl rustyline::highlight::Highlighter for DeclHelper {}
1120impl rustyline::validate::Validator for DeclHelper {}
1121impl rustyline::Helper for DeclHelper {}