Skip to main content

quilt/
notebook.rs

1//! Notebooks: an HTML page whose quoted cells run on machines.
2//!
3//! A notebook is an `.html.quilt` file — ordinary HTML with cells spliced in
4//! as quotes of other languages:
5//!
6//! ```html
7//! <div class="row">
8//!   py↖
9//!     total = 6 * 7
10//!     print(html↖<b id="answer">↙↑(total)↘</b>↗.coparse())
11//!   ↗
12//!   sql↖SELECT ↙#answer↘ * 2;↗
13//! </div>
14//! ```
15//!
16//! HTML is the ground language, so the page is the program and the cells are
17//! its quotes; the file's *expansion* (`langs::html::meta`) holds the cells
18//! verbatim, which is what `quilt check` validates. *Running* it is this
19//! module's job, and it is machines all the way down:
20//!
21//! * **The page is the HTML machine.** Each cell is planted as a placeholder
22//!   element, the page becomes an [`HtmlMachine`], and every result is fed
23//!   back to it as a definition. A cell whose output carries an `id` the page
24//!   already has *redefines* that element wherever the author put it — a
25//!   Python cell that prints `<p id="summary">…</p>` edits the summary at the
26//!   top of the page. Ids are the page's definitions, and cells are how they
27//!   are made.
28//! * **Each cell runs on its language's park machine** (`Multi::machine`):
29//!   the persistent python kernel, a live `sqlite3`, a long-lived shell —
30//!   so definitions persist from cell to cell, the way they persist across
31//!   lines of `quilt repl`. A cell is re-parsed as a *program* of its own
32//!   language and expanded by that language's meta before it is fed, so a
33//!   Python cell quotes HTML with `html↖…↗` and lifts into it with `↑`
34//!   exactly as a `.html.py.quilt` file would.
35//! * **An unquote that reaches the page reads the page.** `↙#total↘` inside a
36//!   cell is a document reference: the text of the element with that id,
37//!   spliced into the cell as a string literal of the cell's language. That
38//!   is how machines that share nothing exchange values — SQL answers into
39//!   `<b id="total">`, Python reads `↙#total↘` — through the document, the
40//!   one thing every cell can see. An unquote whose body is not a selector
41//!   splices its own text, which is what the identity host would have done.
42//! * **Cells create cells.** Output is parsed as Quilt-in-HTML, not just as
43//!   HTML, so a quote in a cell's output is a new cell: it is planted, run
44//!   next (before the cells that follow in the page), and rendered in place.
45//!   Quilt's own staging depth makes this natural — a Python cell writes
46//!   `html↖<li>bash↖…↗</li>↗`, and the nested quote survives expansion with
47//!   its glyphs because it belongs to the next stage. A value baked into a
48//!   generated cell crosses two quote levels, so it is written `↙↙↑(n)↘↘`,
49//!   and the generation counter stops a cell that keeps creating cells at
50//!   [`MAX_GENERATION`].
51//!
52//! Output that contains a tag (or a glyph) is markup and joins the page as
53//! elements; plain text is shown verbatim. A cell that fails — a rejected
54//! feed, a parse error, a missing reference — renders its error and the
55//! notebook goes on, as a REPL would. Nothing is retried and nothing is
56//! cached: the notebook is a run, and its rendering is the record of it.
57
58use std::collections::{BTreeMap, VecDeque};
59use std::fmt::Write as _;
60
61use miette::bail;
62
63use crate::glyphs::GLYPHS;
64use crate::lang::{flat_nodes, InnerKind, Language as _};
65use crate::lift::escape_html;
66use crate::machine::html::{element_id, selector, top_level, Defined};
67use crate::machine::{Answer, HtmlMachine, Machine as _};
68use crate::multi::{Languages, MetaLanguages, Multi};
69use crate::prelude::*;
70use crate::qterm::QTerm;
71
72/**************************************************************/
73
74/// How many generations of cell-created cells a notebook will run before a
75/// cell is refused: a cell whose output creates a cell whose output creates
76/// a cell … is a loop with no other bound.
77pub const MAX_GENERATION: usize = 8;
78
79/// The id of the stylesheet the notebook adds when the page defines none —
80/// define an element with this id yourself to take over the cell chrome.
81pub const STYLE_ID: &str = "quilt-cells";
82
83/// The literals that spell "no value" — what a query answers when it was
84/// really an effect (`print(…)` in Python, a `console.log` in TypeScript).
85/// Not shown as a value: a cell that printed has shown what it did.
86pub const NO_VALUE: &[&str] = &["None", "undefined"];
87
88/// The cell chrome: enough to read a notebook cold, and no page layout —
89/// arranging cells is the page's business.
90pub const DEFAULT_STYLE: &str = r"
91.quilt-cell { --quilt-accent: #8250df; --quilt-line: #d0d7de; --quilt-ink: #1f2328; --quilt-paper: #fff; --quilt-mute: #57606a;
92  border: 1px solid var(--quilt-line); border-left: 4px solid var(--quilt-accent); border-radius: 6px;
93  margin: 1rem 0; padding: 0; background: var(--quilt-paper); color: var(--quilt-ink); font-size: .95rem; overflow: hidden; }
94.quilt-cell > .quilt-lang { font: 600 .7rem/1 ui-monospace, SFMono-Regular, Menlo, monospace; text-transform: uppercase;
95  letter-spacing: .08em; color: var(--quilt-accent); padding: .45rem .75rem 0; }
96.quilt-cell > .quilt-src { margin: 0; padding: .45rem .75rem .6rem; overflow-x: auto; font: .85rem/1.45 ui-monospace, SFMono-Regular, Menlo, monospace; }
97.quilt-cell > .quilt-out { display: block; border-top: 1px dashed var(--quilt-line); padding: .5rem .75rem; }
98.quilt-cell .quilt-stdout, .quilt-cell .quilt-value { margin: 0; font: .85rem/1.45 ui-monospace, SFMono-Regular, Menlo, monospace; white-space: pre-wrap; }
99.quilt-cell .quilt-value { color: #0550ae; }
100.quilt-cell > .quilt-stderr, .quilt-cell > .quilt-error { margin: 0; border-top: 1px dashed var(--quilt-line); padding: .5rem .75rem;
101  font: .8rem/1.4 ui-monospace, SFMono-Regular, Menlo, monospace; white-space: pre-wrap; }
102.quilt-cell > .quilt-stderr { color: #7d4e00; background: #fff8c5; }
103.quilt-cell > .quilt-error { color: #a40e26; background: #ffebe9; }
104.quilt-cell.quilt-failed { --quilt-accent: #cf222e; }
105.quilt-cell.quilt-generated { border-left-style: dashed; }
106.quilt-cell.quilt-pending { --quilt-accent: #8c959f; }
107.quilt-cell .quilt-glyph { color: #bc4c00; font-weight: 700; }
108.quilt-cell.quilt-py, .quilt-cell.quilt-python { --quilt-accent: #3572a5; }
109.quilt-cell.quilt-sql, .quilt-cell.quilt-mysql { --quilt-accent: #e38c00; }
110.quilt-cell.quilt-bash, .quilt-cell.quilt-zsh { --quilt-accent: #4e9a06; }
111.quilt-cell.quilt-ts, .quilt-cell.quilt-typescript { --quilt-accent: #3178c6; }
112.quilt-cell.quilt-html { --quilt-accent: #e34c26; }
113@media (prefers-color-scheme: dark) {
114  .quilt-cell { --quilt-line: #3d444d; --quilt-ink: #e6edf3; --quilt-paper: #161b22; --quilt-mute: #9198a1; }
115  .quilt-cell .quilt-value { color: #79c0ff; }
116  .quilt-cell > .quilt-stderr { color: #e3b341; background: #2b2411; }
117  .quilt-cell > .quilt-error { color: #ff7b72; background: #2d1214; }
118}
119";
120
121/**************************************************************/
122
123/// One cell, as it ran.
124#[derive(Debug, Clone)]
125pub struct Cell {
126    /// The cell's number: its element in the page is `quilt-cell-<id>`.
127    pub id: usize,
128    /// The language the cell was quoted in, as written (`py`, `sql`, …).
129    pub lang: Box<str>,
130    /// 0 for a cell the author wrote; `n + 1` for one created by the output
131    /// of a generation-`n` cell.
132    pub generation: usize,
133    /// The cell's source as shown: dedented, references unresolved.
134    pub src: String,
135    /// Whether the cell has run. A cell in a file has run by the time the
136    /// page is rendered; one added in a live session waits to be told to.
137    pub ran: bool,
138    /// The answered literal, for a cell that was a query.
139    pub value: Option<Box<str>>,
140    pub stdout: Box<str>,
141    pub stderr: Box<str>,
142    /// Why the cell did not run to an answer, when it did not.
143    pub error: Option<String>,
144    /// Ids of elements elsewhere in the page this cell's output redefined.
145    pub edits: Vec<String>,
146    /// Ids of the cells this cell's output created.
147    pub spawned: Vec<usize>,
148}
149
150impl Cell {
151    /// A cell that has a place and a source and has not run.
152    #[must_use]
153    pub fn pending(id: usize, lang: &str, src: &str, generation: usize) -> Cell {
154        Cell {
155            id,
156            lang: lang.into(),
157            generation,
158            src: src.to_string(),
159            ran: false,
160            value: None,
161            stdout: Box::default(),
162            stderr: Box::default(),
163            error: None,
164            edits: Vec::new(),
165            spawned: Vec::new(),
166        }
167    }
168
169    #[must_use]
170    pub fn failed(&self) -> bool {
171        self.error.is_some()
172    }
173
174    /// The id of this cell's `<figure>` in the page.
175    #[must_use]
176    pub fn element_id(&self) -> String {
177        cell_element_id(self.id)
178    }
179}
180
181/// The prefix that makes an element a cell's figure. An id is the page's
182/// namespace, so the cells' corner of it is spelled once, here.
183const CELL_ID_PREFIX: &str = "quilt-cell-";
184
185/// The id of cell `id`'s element in the page.
186#[must_use]
187pub fn cell_element_id(id: usize) -> String {
188    format!("{CELL_ID_PREFIX}{id}")
189}
190
191/// The cell an element id belongs to, if it is a cell's figure.
192#[must_use]
193pub fn cell_id(element_id: &str) -> Option<usize> {
194    element_id.strip_prefix(CELL_ID_PREFIX)?.parse().ok()
195}
196
197/// The first quote in a term, pre-order — how a cell's source becomes a
198/// cell's body.
199fn first_quote(term: &Arc<QTerm>) -> Option<Arc<QTerm>> {
200    match &**term {
201        QTerm::Quote { term, .. } => Some(term.clone()),
202        QTerm::Tuple { terms, .. } => terms.iter().find_map(first_quote),
203        QTerm::Unquote { .. } => None,
204    }
205}
206
207/// A cell that has been given a place in the page and not yet run.
208struct Planted {
209    id: usize,
210    lang: Box<str>,
211    body: Arc<QTerm>,
212    generation: usize,
213}
214
215/// A cell as the session holds it *between* runs: its place in the page and
216/// the source an editor shows. [`Cell`] is the record of a run; this is the
217/// record of a cell, and a live session edits and re-runs it from here.
218#[derive(Debug, Clone)]
219pub struct CellDef {
220    pub id: usize,
221    /// The language the cell is quoted in, as written (`py`, `sql`, …).
222    pub lang: Box<str>,
223    /// The cell's source, references unresolved — what the editor holds.
224    pub src: String,
225    /// 0 for a cell the author wrote; `n + 1` for one a generation-`n`
226    /// cell's output created.
227    pub generation: usize,
228}
229
230/// A cell as its machine will see it: what the expander made of it.
231#[derive(Debug, Clone)]
232pub struct Program {
233    /// Which message sort the machine is being sent.
234    pub kind: InnerKind,
235    /// The cell's source with its page references (`↙#id↘`) resolved — what
236    /// the expander was given.
237    pub resolved: String,
238    /// The expanded program: the text of [`term`](Self::term), and what a
239    /// reader means by "the program this cell becomes".
240    pub program: String,
241    /// The term that is fed. Machines traffic in terms; the two strings
242    /// above are this one, read.
243    pub term: Arc<QTerm>,
244}
245
246/// What the page just did, for a viewer to patch rather than reload.
247///
248/// A live notebook's page lives in two places — the [`HtmlMachine`] the
249/// cells feed and the DOM someone is looking at — and the second is a view
250/// of the first (see `crate::serve`). These are the edits that keep it one
251/// page: everything a session does to the document, in the order it did it.
252#[derive(Debug, Clone, PartialEq, Eq)]
253pub enum Change {
254    /// The element with this id is now this markup.
255    Define { id: String, html: String },
256    /// This markup is now the next sibling of the element with this id.
257    Insert { after: String, html: String },
258    /// This markup was appended to the page.
259    Append { html: String },
260    /// The element with this id is gone.
261    Remove { id: String },
262}
263
264/// A notebook run: the page with its cells rendered, and the cells.
265#[derive(Debug, Clone)]
266pub struct Rendered {
267    pub html: String,
268    pub cells: Vec<Cell>,
269}
270
271impl Rendered {
272    /// The cells that did not run to an answer.
273    #[must_use]
274    pub fn failures(&self) -> Vec<&Cell> {
275        self.cells.iter().filter(|c| c.failed()).collect()
276    }
277}
278
279/// Run a notebook: the page in `src`, its cells on `multi`'s park machines.
280pub fn run<LS: Languages, MS: MetaLanguages>(
281    multi: &mut Multi<LS, MS>,
282    src: &str,
283) -> Result<Rendered> {
284    let mut notebook = Notebook::open(multi, src)?;
285    notebook.run_pending();
286    Ok(notebook.finish())
287}
288
289/**************************************************************/
290
291/// A notebook session: a page held as an [`HtmlMachine`], the cells found in
292/// it, and the `Multi` whose park machines run them. [`run`] is the
293/// one-shot form; the session form is what `quilt repl html` drives a line
294/// at a time.
295pub struct Notebook<'m, LS: Languages, MS: MetaLanguages> {
296    multi: &'m mut Multi<LS, MS>,
297    page: HtmlMachine,
298    cells: Vec<Cell>,
299    /// Every cell the page holds, by id: what a live session edits and
300    /// re-runs. Planted cells enter here before they run.
301    defs: BTreeMap<usize, CellDef>,
302    queue: VecDeque<Planted>,
303    /// Cells planted while a fragment was being read; moved to the queue
304    /// once the fragment is placed.
305    spawned: Vec<Planted>,
306    /// What the page has done since a viewer last asked; see [`Change`].
307    changes: Vec<Change>,
308    next_id: usize,
309}
310
311impl<'m, LS: Languages, MS: MetaLanguages> Notebook<'m, LS, MS> {
312    /// An empty page.
313    pub fn new(multi: &'m mut Multi<LS, MS>) -> Self {
314        Notebook {
315            multi,
316            page: HtmlMachine::default(),
317            cells: Vec::new(),
318            defs: BTreeMap::new(),
319            queue: VecDeque::new(),
320            spawned: Vec::new(),
321            changes: Vec::new(),
322            next_id: 1,
323        }
324    }
325
326    /// Open a notebook: parse the page, plant its cells, and hold it as the
327    /// HTML machine. Nothing runs until [`run_pending`](Self::run_pending).
328    pub fn open(multi: &'m mut Multi<LS, MS>, src: &str) -> Result<Self> {
329        let mut nb = Self::new(multi);
330        let doc = nb.multi.parse_chain(&["html"], src)?;
331        let planted = nb.plant(&doc, 0);
332        nb.page = HtmlMachine::new(&planted);
333        nb.queue.extend(nb.spawned.drain(..));
334        nb.ensure_style();
335        Ok(nb)
336    }
337
338    /// Feed a fragment of Quilt-in-HTML to the page — the REPL's turn. Plain
339    /// markup defines (by id) or appends; quotes are cells, run before this
340    /// returns. Answers the ids of the cells that ran.
341    pub fn feed_source(&mut self, src: &str) -> Result<Vec<usize>> {
342        let frag = self.multi.parse_chain(&["html"], src)?;
343        let planted = self.plant(&frag, 0);
344        for node in top_level(&planted) {
345            self.define(&node);
346        }
347        self.queue.extend(self.spawned.drain(..));
348        let first = self.cells.len();
349        self.run_pending();
350        Ok(self.cells[first..].iter().map(|c| c.id).collect())
351    }
352
353    /// Run every planted cell, in page order — and every cell those create.
354    pub fn run_pending(&mut self) {
355        while let Some(planted) = self.queue.pop_front() {
356            self.run_planted(&planted);
357        }
358    }
359
360    /// The page as it stands.
361    #[must_use]
362    pub fn page(&self) -> &HtmlMachine {
363        &self.page
364    }
365
366    /// The cells run so far, in the order they ran.
367    #[must_use]
368    pub fn cells(&self) -> &[Cell] {
369        &self.cells
370    }
371
372    /// The page, serialized.
373    #[must_use]
374    pub fn render(&self) -> String {
375        self.page.document().coparse()
376    }
377
378    /// The run, as a page and its cells.
379    #[must_use]
380    pub fn finish(self) -> Rendered {
381        Rendered {
382            html: self.render(),
383            cells: self.cells,
384        }
385    }
386
387    /* ── the live session ─────────────────────────────────────────────── */
388
389    /// Every cell the page holds, in *page* order — which is the order an
390    /// editor lists them in, and not the order they ran in ([`cells`] is
391    /// that). A cell created by a cell's output sits where its creator's
392    /// output put it, so page order is the only order a reader sees.
393    ///
394    /// [`cells`]: Self::cells
395    #[must_use]
396    pub fn cell_defs(&self) -> Vec<&CellDef> {
397        let mut placed: Vec<&CellDef> = self
398            .page
399            .ids()
400            .iter()
401            .filter_map(|id| cell_id(id))
402            .filter_map(|id| self.defs.get(&id))
403            .collect();
404        // A cell whose figure is not (yet) in the page still belongs to the
405        // session; keep it, after the placed ones.
406        let loose: Vec<&CellDef> = self
407            .defs
408            .values()
409            .filter(|d| !placed.iter().any(|p| p.id == d.id))
410            .collect();
411        placed.extend(loose);
412        placed
413    }
414
415    /// One cell's source and place, if the page has it.
416    #[must_use]
417    pub fn cell_def(&self, id: usize) -> Option<&CellDef> {
418        self.defs.get(&id)
419    }
420
421    /// One cell's last run, if it has run.
422    #[must_use]
423    pub fn cell(&self, id: usize) -> Option<&Cell> {
424        self.cells.iter().find(|c| c.id == id)
425    }
426
427    /// The cell's `<figure>` as the page now holds it — what a viewer shows
428    /// in its place.
429    #[must_use]
430    pub fn cell_figure(&self, id: usize) -> Option<String> {
431        self.page.find(&cell_element_id(id)).map(|el| el.coparse())
432    }
433
434    /// Everything the page has done since this was last called, and clear
435    /// the journal. A viewer patches these in and is looking at the page
436    /// the cells are feeding.
437    pub fn take_changes(&mut self) -> Vec<Change> {
438        std::mem::take(&mut self.changes)
439    }
440
441    /// Add a cell to the page: after the element `after` names, else at the
442    /// end. Answers the new cell's id. Nothing runs — [`run_cell`] does.
443    ///
444    /// The source is not parsed here: a half-written cell is still a cell,
445    /// and the place to hear about a syntax error is the cell's own output,
446    /// where [`run_cell`] puts it.
447    ///
448    /// [`run_cell`]: Self::run_cell
449    pub fn add_cell(&mut self, lang: &str, src: &str, after: Option<&str>) -> Result<usize> {
450        let id = self.next_id;
451        self.next_id += 1;
452        let cell = Cell::pending(id, lang, src, 0);
453        let figure = self.figure_term(&cell, "")?;
454        match after {
455            Some(anchor) if self.page.insert_after(anchor, &figure) => {
456                let html = self.cell_figure(id).unwrap_or_else(|| figure.coparse());
457                self.changes.push(Change::Insert {
458                    after: anchor.to_string(),
459                    html,
460                });
461            }
462            _ => {
463                self.define(&figure);
464            }
465        }
466        self.defs.insert(
467            id,
468            CellDef {
469                id,
470                lang: lang.into(),
471                src: src.to_string(),
472                generation: 0,
473            },
474        );
475        Ok(id)
476    }
477
478    /// Edit a cell: a new source, and optionally a new language. The cell
479    /// goes back to pending — its old output belonged to its old source —
480    /// and nothing runs.
481    pub fn set_cell(&mut self, id: usize, lang: Option<&str>, src: &str) -> Result<()> {
482        let def = self
483            .defs
484            .get_mut(&id)
485            .ok_or_else(|| miette!("this page has no cell {id}"))?;
486        if let Some(lang) = lang {
487            def.lang = lang.into();
488        }
489        def.src = src.to_string();
490        let (lang, generation) = (def.lang.clone(), def.generation);
491        self.cells.retain(|c| c.id != id);
492        let cell = Cell::pending(id, &lang, src, generation);
493        let figure = self.figure_term(&cell, "")?;
494        self.define(&figure);
495        Ok(())
496    }
497
498    /// Remove a cell: its figure leaves the page and its source leaves the
499    /// session. Its machine keeps whatever the cell defined — a session is
500    /// a run, and a run cannot be unrun.
501    pub fn remove_cell(&mut self, id: usize) -> Result<()> {
502        if self.defs.remove(&id).is_none() {
503            bail!("this page has no cell {id}");
504        }
505        self.cells.retain(|c| c.id != id);
506        let element = cell_element_id(id);
507        if self.page.remove(&element) {
508            self.changes.push(Change::Remove { id: element });
509        }
510        Ok(())
511    }
512
513    /// Run a cell that the page holds, and every cell its output creates.
514    ///
515    /// A cell that cannot be read at all — an unbalanced bracket, say —
516    /// fails the way a cell that throws fails: in its own output, with the
517    /// session going on. That is the REPL's contract, and an editor needs it
518    /// more than a file does.
519    pub fn run_cell(&mut self, id: usize) -> Result<()> {
520        match self.planted(id)? {
521            Ok(planted) => self.run_planted(&planted),
522            Err((planted, e)) => self.land(&planted, Err(e)),
523        }
524        self.run_pending();
525        Ok(())
526    }
527
528    /// What a cell becomes: its references resolved and its program
529    /// expanded, without running anything. This is "Expand" in an editor,
530    /// and the program a cell whose machine is elsewhere is sent.
531    pub fn expand_cell(&mut self, id: usize) -> Result<Program> {
532        let def = self.def(id)?;
533        let body = self.parse_cell_body(&def.lang, &def.src)?;
534        self.program(&def.lang, &body, def.generation)
535    }
536
537    /// [`expand_cell`](Self::expand_cell) for source that is not (yet) a
538    /// cell: what this text *would* become, page references and all. An
539    /// editor expands as it is typed; the page it reads is this one.
540    pub fn expand_source(&mut self, lang: &str, src: &str) -> Result<Program> {
541        let body = self.parse_cell_body(lang, src)?;
542        self.program(lang, &body, 0)
543    }
544
545    /// Define a fragment of finished HTML into the page, as an `html` cell's
546    /// output would be — the door for an edit made *in* a viewer's DOM,
547    /// which has to reach the page the other cells read. Answers the id it
548    /// defined, when the fragment carried one.
549    pub fn define_html(&mut self, html: &str) -> Result<Option<String>> {
550        let frag = self.parse_html(html)?;
551        let mut defined = None;
552        for node in top_level(&frag) {
553            self.define(&node);
554            defined = defined.or_else(|| element_id(&node));
555        }
556        Ok(defined)
557    }
558
559    /// Land an [`Answer`] produced elsewhere as cell `id`'s outcome — the
560    /// door for a machine that is not in this process. Everything after the
561    /// feed is the same: output read back into the page, cells created by
562    /// it run, the figure rendered.
563    pub fn land_cell(&mut self, id: usize, outcome: Result<Answer>) -> Result<()> {
564        let planted = match self.planted(id)? {
565            Ok(planted) | Err((planted, _)) => planted,
566        };
567        self.land(&planted, outcome);
568        self.run_pending();
569        Ok(())
570    }
571
572    /// Feed source straight to a language's machine — as a cell is fed, but
573    /// without being a cell: no place in the page, no figure, no output read
574    /// back. The session's own line to a machine, for what belongs to the
575    /// session rather than to the page: a live server feeds its Python
576    /// prelude and dispatches its `/app` requests this way.
577    pub fn feed_lang(&mut self, lang: &str, kind: InnerKind, src: &str) -> Result<Answer> {
578        self.multi.feed_on(lang, kind, src)
579    }
580
581    /// Park a machine as the default for `lang`, replacing any already
582    /// parked — the door for a machine the *session* configured rather than
583    /// the language's own spec. A live session parks a `sqlite3` on a file
584    /// its Python kernel can also open, which is what lets SQL cells and a
585    /// Python route see one database.
586    ///
587    /// Park before the first cell of that language runs: the park spawns on
588    /// first use, and a machine already spawned has state to lose.
589    pub fn park_machine(&mut self, lang: &str, machine: Box<dyn crate::machine::Machine>) {
590        let key = self.multi.langs.canonical(lang).to_string();
591        self.multi.machines.insert(&key, machine);
592    }
593
594    /// Whether a machine for `lang` has been spawned (or parked) already.
595    #[must_use]
596    pub fn has_machine(&self, lang: &str) -> bool {
597        self.multi
598            .machines
599            .contains(self.multi.langs.canonical(lang))
600    }
601
602    /// The page as a *page*: the cell chrome gone, everything the cells
603    /// built still in place. This is what the notebook made, as opposed to
604    /// the record of making it — `GET /site` in a live session.
605    #[must_use]
606    pub fn site_html(&self) -> String {
607        self.page
608            .document_without(&|id| cell_id(id).is_some() || id == STYLE_ID)
609            .coparse()
610    }
611
612    /// One cell, ready to run: its stored source parsed as the body of a
613    /// `lang↖…↗` quote, so an editor's text and a file's text take one path.
614    /// `Err` *inside* the `Ok` is a cell that cannot be read — still a cell,
615    /// with somewhere to render the error.
616    #[allow(clippy::type_complexity)]
617    fn planted(
618        &mut self,
619        id: usize,
620    ) -> Result<std::result::Result<Planted, (Planted, miette::Report)>> {
621        let def = self.def(id)?;
622        let CellDef {
623            lang,
624            src,
625            generation,
626            ..
627        } = def;
628        Ok(match self.parse_cell_body(&lang, &src) {
629            Ok(body) => Ok(Planted {
630                id,
631                lang,
632                body,
633                generation,
634            }),
635            Err(e) => Err((
636                Planted {
637                    id,
638                    lang,
639                    body: leaf("text", &src),
640                    generation,
641                },
642                e,
643            )),
644        })
645    }
646
647    fn def(&self, id: usize) -> Result<CellDef> {
648        self.defs
649            .get(&id)
650            .cloned()
651            .ok_or_else(|| miette!("this page has no cell {id}"))
652    }
653
654    /// Parse a cell's source as a cell: the body of a `lang↖…↗` quote in the
655    /// page, which is what the same text in the file would have been.
656    fn parse_cell_body(&mut self, lang: &str, src: &str) -> Result<Arc<QTerm>> {
657        let wrapped = format!("{lang}↖{src}↗");
658        let doc = self
659            .multi
660            .parse_chain(&["html"], &wrapped)
661            .map_err(|e| e.with_source_code(wrapped.clone()))?;
662        first_quote(&doc).ok_or_else(|| miette!("a cell of {lang} must be readable as `{lang}↖…↗`"))
663    }
664
665    /// Add the default cell chrome unless the page defines its own.
666    fn ensure_style(&mut self) {
667        if self.page.find(STYLE_ID).is_some() {
668            return;
669        }
670        let style = format!("<style id=\"{STYLE_ID}\">{DEFAULT_STYLE}</style>");
671        if let Ok(style) = self.parse_html(&style) {
672            self.define(&style);
673        }
674    }
675
676    /// Define a node into the page and journal what that did, so a viewer
677    /// can patch. Every page edit a notebook makes goes through here.
678    ///
679    /// The journalled markup is read back *out of the page* rather than
680    /// taken from the node, so what a viewer patches in is exactly what the
681    /// page now holds — layout baked, entities as stored.
682    fn define(&mut self, node: &Arc<QTerm>) -> Defined {
683        let defined = self.page.define(node);
684        let id = element_id(node);
685        let html = id
686            .as_deref()
687            .and_then(|id| self.page.find(id))
688            .map_or_else(|| node.coparse(), |el| el.coparse());
689        self.changes.push(match (id, defined) {
690            (Some(id), Defined::Replaced) => Change::Define { id, html },
691            _ => Change::Append { html },
692        });
693        defined
694    }
695
696    /// Parse a fragment of finished HTML (no Quilt in it) with the HTML
697    /// language.
698    fn parse_html(&mut self, src: &str) -> Result<Arc<QTerm>> {
699        self.multi
700            .get_lang_mut("html")?
701            .parse_as(None, &flat_nodes(src))
702    }
703
704    /// Rebuild a fragment with every quote replaced by a placeholder
705    /// element, recording each as a cell to run at `generation`.
706    fn plant(&mut self, term: &Arc<QTerm>, generation: usize) -> Arc<QTerm> {
707        match &**term {
708            QTerm::Quote {
709                lang, term: body, ..
710            } => {
711                let id = self.next_id;
712                self.next_id += 1;
713                self.defs.insert(
714                    id,
715                    CellDef {
716                        id,
717                        lang: lang.clone(),
718                        src: cell_source(lang, body),
719                        generation,
720                    },
721                );
722                self.spawned.push(Planted {
723                    id,
724                    lang: lang.clone(),
725                    body: body.clone(),
726                    generation,
727                });
728                self.placeholder(id, lang)
729            }
730            QTerm::Tuple { tag, terms, cmds } => {
731                let terms: Vec<_> = terms.iter().map(|t| self.plant(t, generation)).collect();
732                tuple(tag, &terms, cmds)
733            }
734            // An unquote at page level is a parse error before it gets here.
735            QTerm::Unquote { .. } => term.clone(),
736        }
737    }
738
739    /// The element that stands where a cell will render.
740    fn placeholder(&mut self, id: usize, lang: &str) -> Arc<QTerm> {
741        let html = format!(
742            "<figure class=\"quilt-cell quilt-pending\" id=\"{}\" data-lang=\"{lang}\"></figure>",
743            cell_element_id(id)
744        );
745        self.parse_html(&html).unwrap_or_else(|_| leaf("text", ""))
746    }
747
748    /// Run one planted cell and render it into its place.
749    fn run_planted(&mut self, planted: &Planted) {
750        let outcome = self.execute(&planted.lang, &planted.body, planted.generation);
751        self.land(planted, outcome);
752    }
753
754    /// Land a cell's outcome: read what it said back into the page, take the
755    /// cells its output created, and render its figure where it stands.
756    ///
757    /// Separate from [`run_planted`](Self::run_planted) because a cell's machine is
758    /// not always in this process — a TypeScript cell in a live session runs
759    /// in the viewer's browser (`crate::serve`), and its answer comes back
760    /// over the wire. Where the [`Answer`] was produced makes no difference
761    /// from here on: it is read exactly as a park machine's would be.
762    fn land(&mut self, planted: &Planted, outcome: Result<Answer>) {
763        let Planted {
764            id,
765            lang,
766            body,
767            generation,
768        } = planted;
769        let (id, generation) = (*id, *generation);
770        let mut cell = Cell {
771            id,
772            lang: lang.clone(),
773            generation,
774            src: cell_source(lang, body),
775            ran: true,
776            value: None,
777            stdout: Box::default(),
778            stderr: Box::default(),
779            error: None,
780            edits: Vec::new(),
781            spawned: Vec::new(),
782        };
783        // The nodes that stay in the cell's own output slot.
784        let mut slot: Vec<Arc<QTerm>> = Vec::new();
785        match outcome {
786            Ok(answer) => {
787                // A query's answer is its last stdout line: it is the value,
788                // and not output as well.
789                cell.stdout = match &answer.value {
790                    Some(value) => without_answer_line(&answer.stdout, value).into(),
791                    None => answer.stdout,
792                };
793                cell.stderr = answer.stderr;
794                cell.value = answer.value;
795                let stdout = cell.stdout.to_string();
796                let mut nodes = self.output_nodes(&stdout, "quilt-stdout", generation);
797                if let Some(value) = cell.value.clone() {
798                    if !NO_VALUE.contains(&value.trim()) {
799                        nodes.extend(self.output_nodes(&value, "quilt-value", generation));
800                    }
801                }
802                for node in nodes {
803                    // An element with an id the page has already defined is a
804                    // redefinition: it goes where that id is, not here.
805                    match element_id(&node) {
806                        Some(id) if self.page.find(&id).is_some() => {
807                            self.define(&node);
808                            cell.edits.push(id);
809                        }
810                        _ => slot.push(node),
811                    }
812                }
813            }
814            Err(e) => cell.error = Some(render_error(&e)),
815        }
816        // The cells this one created run next, before the rest of the page.
817        cell.spawned = self.spawned.iter().map(|p| p.id).collect();
818        let spawned: Vec<Planted> = self.spawned.drain(..).collect();
819        for planted in spawned.into_iter().rev() {
820            self.queue.push_front(planted);
821        }
822        self.place(&cell, &slot);
823        // A cell re-run in a live session replaces its record; in a one-shot
824        // run every id is new, so this is a push.
825        match self.cells.iter_mut().find(|c| c.id == id) {
826            Some(slot) => *slot = cell,
827            None => self.cells.push(cell),
828        }
829    }
830
831    /// Prepare and feed a cell: [`program`](Self::program), then
832    /// [`feed`](Self::feed).
833    fn execute(&mut self, lang: &str, body: &Arc<QTerm>, generation: usize) -> Result<Answer> {
834        let program = self.program(lang, body, generation)?;
835        self.feed(lang, &program)
836    }
837
838    /// Resolve the cell's page references, re-parse it as a program of its
839    /// own language and expand it with that language's meta — everything
840    /// that happens to a cell before its machine sees it. Split out because
841    /// a live session shows this ("Expand") and, for a cell whose machine is
842    /// the viewer's browser, sends it.
843    fn program(&mut self, lang: &str, body: &Arc<QTerm>, generation: usize) -> Result<Program> {
844        if generation > MAX_GENERATION {
845            bail!(
846                "cell generation {generation} is past the limit of {MAX_GENERATION}: cells kept \
847                 creating cells"
848            );
849        }
850        let resolved = self.resolve_refs(lang, body, 1)?;
851        let src = cell_source(lang, &resolved);
852        let with_src = |e: miette::Report| e.with_source_code(src.clone());
853        let term = self.multi.parse_chain(&[lang], &src).map_err(with_src)?;
854        // A language with no meta (SQL, WGSL) has nothing to expand: the
855        // parsed term is the program.
856        let term = if self.multi.get_meta(lang).is_ok() {
857            self.multi.expand_lang(lang, &term).map_err(with_src)?
858        } else {
859            term
860        };
861        let kind = self.multi.classify_for_feed(lang, &term)?;
862        Ok(Program {
863            kind,
864            resolved: src,
865            program: term.coparse(),
866            term,
867        })
868    }
869
870    /// Feed a cell's program to its machine: the language's park machine,
871    /// or — for an `html` cell — the page itself.
872    fn feed(&mut self, lang: &str, program: &Program) -> Result<Answer> {
873        if lang == "html" {
874            return self.feed_page(program.kind, &program.term);
875        }
876        self.multi.machine(lang)?.feed(program.kind, &program.term)
877    }
878
879    /// Feed the page, journalling what it defined. `HtmlMachine::feed` would
880    /// do the defining itself; the notebook does it so that every page edit
881    /// goes through [`define`](Self::define) and reaches a viewer. The one
882    /// distinction mirrored here is the machine's own: a query changes
883    /// nothing.
884    fn feed_page(&mut self, kind: InnerKind, term: &Arc<QTerm>) -> Result<Answer> {
885        let nodes = top_level(term);
886        let query =
887            kind == InnerKind::Expr || matches!(nodes.as_slice(), [one] if selector(one).is_some());
888        if query {
889            return self.page.feed(kind, term);
890        }
891        for node in &nodes {
892            self.define(node);
893        }
894        Ok(Answer::default())
895    }
896
897    /// Replace every unquote that reaches the page (`depth` quote levels up
898    /// from the cell body, which sits at depth 1) with what it reads: a
899    /// selector's element text as a string literal of the cell's language,
900    /// or any other body as its own text.
901    fn resolve_refs(&self, lang: &str, term: &Arc<QTerm>, depth: usize) -> Result<Arc<QTerm>> {
902        Ok(match &**term {
903            QTerm::Quote {
904                tag,
905                index,
906                lang: qlang,
907                term: inner,
908                cmds,
909                span,
910                repr,
911            } => arc(QTerm::Quote {
912                tag: tag.clone(),
913                index: *index,
914                lang: qlang.clone(),
915                term: self.resolve_refs(lang, inner, depth + usize::from(*index))?,
916                cmds: cmds.clone(),
917                span: span.clone(),
918                repr: *repr,
919            }),
920            QTerm::Unquote {
921                tag,
922                index,
923                lang: ulang,
924                term: inner,
925                cmds,
926                span,
927            } => {
928                if usize::from(*index) >= depth {
929                    let text = inner.coparse();
930                    let text = text.trim();
931                    let spliced = match text.strip_prefix('#') {
932                        Some(id) if !id.is_empty() && !id.contains(char::is_whitespace) => {
933                            let value = self.page.text(id).ok_or_else(|| {
934                                miette!(
935                                    "the page has no element with id {id:?} for `↙{text}↘` to read"
936                                )
937                            })?;
938                            string_literal(lang, &value)
939                        }
940                        _ => text.to_string(),
941                    };
942                    leaf("text", &spliced)
943                } else {
944                    arc(QTerm::Unquote {
945                        tag: tag.clone(),
946                        index: *index,
947                        lang: ulang.clone(),
948                        term: self.resolve_refs(lang, inner, depth - usize::from(*index))?,
949                        cmds: cmds.clone(),
950                        span: span.clone(),
951                    })
952                }
953            }
954            QTerm::Tuple { tag, terms, cmds } => {
955                let terms = terms
956                    .iter()
957                    .map(|t| self.resolve_refs(lang, t, depth))
958                    .collect::<Result<Vec<_>>>()?;
959                tuple(tag, &terms, cmds)
960            }
961        })
962    }
963
964    /// What a cell said, as page nodes: markup (anything with a tag or a
965    /// glyph) is parsed as Quilt-in-HTML, so its quotes become cells of the
966    /// next generation; plain text is shown as it was printed.
967    fn output_nodes(
968        &mut self,
969        text: &str,
970        plain_class: &str,
971        generation: usize,
972    ) -> Vec<Arc<QTerm>> {
973        let text = text.trim_end_matches(['\n', '\r']);
974        if text.trim().is_empty() {
975            return Vec::new();
976        }
977        let markup = text.contains('<') || text.chars().any(|c| GLYPHS.contains(&c));
978        if markup {
979            if let Ok(frag) = self.multi.parse_chain(&["html"], text) {
980                let planted = self.plant(&frag, generation + 1);
981                return top_level(&planted);
982            }
983        }
984        vec![self.pre(plain_class, text)]
985    }
986
987    /// Text as a `<pre>` of the given class.
988    fn pre(&mut self, class: &str, text: &str) -> Arc<QTerm> {
989        let escaped = escape_html(text);
990        self.parse_html(&format!("<pre class=\"{class}\">{escaped}</pre>"))
991            .unwrap_or_else(|_| leaf("text", &escaped))
992    }
993
994    /// Render the cell's figure and define it into the page, where its
995    /// placeholder stands.
996    fn place(&mut self, cell: &Cell, slot: &[Arc<QTerm>]) {
997        let slot_html = slot
998            .iter()
999            .map(|n| n.coparse())
1000            .collect::<Vec<_>>()
1001            .join("\n");
1002        if let Ok(figure) = self.figure_term(cell, &slot_html) {
1003            self.define(&figure);
1004        }
1005    }
1006
1007    /// The cell's `<figure>`, parsed. Falls back to showing the output as
1008    /// the text it was when it does not survive as markup inside a figure
1009    /// (an unbalanced tag, say).
1010    fn figure_term(&mut self, cell: &Cell, slot_html: &str) -> Result<Arc<QTerm>> {
1011        self.parse_html(&figure_html(cell, slot_html)).or_else(|_| {
1012            let escaped = format!(
1013                "<pre class=\"quilt-stdout\">{}</pre>",
1014                escape_html(slot_html)
1015            );
1016            self.parse_html(&figure_html(cell, &escaped))
1017        })
1018    }
1019}
1020
1021/**************************************************************/
1022
1023/// The cell's `<figure>`: language badge, source, output slot, and what
1024/// went wrong if something did.
1025fn figure_html(cell: &Cell, slot_html: &str) -> String {
1026    let mut classes = format!("quilt-cell quilt-{}", cell.lang);
1027    if cell.generation > 0 {
1028        classes.push_str(" quilt-generated");
1029    }
1030    if cell.failed() {
1031        classes.push_str(" quilt-failed");
1032    }
1033    if !cell.ran {
1034        classes.push_str(" quilt-pending");
1035    }
1036    let mut h = String::new();
1037    let _ = writeln!(
1038        h,
1039        "<figure class=\"{classes}\" id=\"{}\" data-lang=\"{}\" data-generation=\"{}\">",
1040        cell.element_id(),
1041        cell.lang,
1042        cell.generation
1043    );
1044    let _ = writeln!(
1045        h,
1046        "<figcaption class=\"quilt-lang\">{}</figcaption>",
1047        cell.lang
1048    );
1049    let _ = writeln!(
1050        h,
1051        "<pre class=\"quilt-src\"><code>{}</code></pre>",
1052        highlight(&cell.src)
1053    );
1054    if !slot_html.is_empty() {
1055        let _ = writeln!(h, "<output class=\"quilt-out\">\n{slot_html}\n</output>");
1056    }
1057    let stderr = cell.stderr.trim_end();
1058    if !stderr.trim().is_empty() {
1059        let _ = writeln!(
1060            h,
1061            "<pre class=\"quilt-stderr\">{}</pre>",
1062            escape_html(stderr)
1063        );
1064    }
1065    if let Some(error) = &cell.error {
1066        let _ = writeln!(
1067            h,
1068            "<pre class=\"quilt-error\">{}</pre>",
1069            escape_html(error.trim_end())
1070        );
1071    }
1072    h.push_str("</figure>");
1073    h
1074}
1075
1076/// Source, escaped, with the Quilt glyphs marked so a stylesheet can color
1077/// them.
1078fn highlight(src: &str) -> String {
1079    let mut out = String::with_capacity(src.len());
1080    for c in escape_html(src).chars() {
1081        if GLYPHS.contains(&c) {
1082            let _ = write!(out, "<span class=\"quilt-glyph\">{c}</span>");
1083        } else {
1084            out.push(c);
1085        }
1086    }
1087    out
1088}
1089
1090/// A string literal of `lang` denoting `s` — how a page reference crosses
1091/// into a cell. Spelled with the same escaping rules the `LiftTo` impls use
1092/// for each language; a language with no string syntax gets the text.
1093fn string_literal(lang: &str, s: &str) -> String {
1094    match lang {
1095        "python" | "py" | "typescript" | "ts" => {
1096            format!("\"{}\"", crate::lift::py_dquote_escape(s))
1097        }
1098        "bash" | "zsh" => format!("\"{}\"", crate::lift::sh_dquote_escape(s)),
1099        "sql" => format!("'{}'", crate::lift::sql_squote_escape(s)),
1100        "mysql" | "mariadb" => format!("'{}'", crate::lift::mysql_squote_escape(s)),
1101        "rust" | "rs" => format!("{s:?}"),
1102        _ => s.to_string(),
1103    }
1104}
1105
1106/// A cell body as Quilt source again: nested quotes keep their glyphs, a
1107/// deferred operator keeps its glyph, and a glyph that was *content* (the
1108/// author wrote `\↖`) is escaped again — so the cell re-parses as the
1109/// author wrote it. `coparse_quilt` makes that distinction only inside a
1110/// bracket, which is where the body came from; a throwaway quote around it
1111/// puts it back there.
1112fn cell_source(lang: &str, body: &Arc<QTerm>) -> String {
1113    let quoted = quote(
1114        "cell",
1115        1,
1116        lang,
1117        body.clone(),
1118        &[
1119            crate::term::cmd(crate::strcmd::write("↖")),
1120            crate::term::HOLE,
1121            crate::term::cmd(crate::strcmd::write("↗")),
1122        ],
1123    );
1124    let text = quoted.coparse_quilt();
1125    text.strip_prefix('↖')
1126        .and_then(|t| t.strip_suffix('↗'))
1127        .map_or(text.clone(), str::to_string)
1128}
1129
1130/// `stdout` without its answer line — the last non-empty line, when it is
1131/// `value` — so a query's answer is not shown as output and as value both.
1132fn without_answer_line(stdout: &str, value: &str) -> String {
1133    let trimmed = stdout.trim_end();
1134    match trimmed.rfind('\n') {
1135        Some(at) if trimmed[at + 1..].trim() == value => trimmed[..at].to_string(),
1136        None if trimmed.trim() == value => String::new(),
1137        _ => stdout.to_string(),
1138    }
1139}
1140
1141/// An error as it reads in a cell. One that points into the cell's source
1142/// (a parse error) is rendered with its snippet and caret; any other is its
1143/// messages, outermost first — a rejected feed's message already carries
1144/// the machine's traceback.
1145fn render_error(e: &miette::Report) -> String {
1146    let diagnostic: &dyn miette::Diagnostic = e.as_ref();
1147    if diagnostic.labels().is_some() && diagnostic.source_code().is_some() {
1148        let handler =
1149            miette::GraphicalReportHandler::new_themed(miette::GraphicalTheme::unicode_nocolor())
1150                .with_width(96);
1151        let mut out = String::new();
1152        if handler.render_report(&mut out, diagnostic).is_ok() {
1153            return out;
1154        }
1155    }
1156    e.chain()
1157        .map(ToString::to_string)
1158        .collect::<Vec<_>>()
1159        .join("\n")
1160}
1161
1162/**************************************************************/
1163
1164#[cfg(test)]
1165mod tests {
1166    use super::*;
1167
1168    #[test]
1169    fn string_literals_follow_each_language() {
1170        assert_eq!(string_literal("py", "a\"b"), "\"a\\\"b\"");
1171        assert_eq!(string_literal("bash", "$x"), "\"\\$x\"");
1172        assert_eq!(string_literal("sql", "it's"), "'it''s'");
1173        assert_eq!(string_literal("html", "<b>"), "<b>");
1174    }
1175
1176    #[test]
1177    fn the_answer_line_is_shown_once() {
1178        assert_eq!(without_answer_line("hi\n42\n", "42"), "hi");
1179        assert_eq!(without_answer_line("42", "42"), "");
1180        assert_eq!(without_answer_line("hi\n", "42"), "hi\n");
1181    }
1182
1183    #[test]
1184    fn highlight_marks_glyphs_and_escapes_markup() {
1185        assert_eq!(
1186            highlight("<b>↖x↗"),
1187            "&lt;b&gt;<span class=\"quilt-glyph\">↖</span>x<span class=\"quilt-glyph\">↗</span>"
1188        );
1189    }
1190}