Skip to main content

quilt/machine/
html.rs

1//! The HTML machine: a document as machine state.
2//!
3//! Every other provider in this crate wraps an interpreter, because "what a
4//! program *does*" for Python or SQL means running it. HTML does nothing when
5//! run — but a *document* is still a stateful thing that accepts fragments
6//! over time and remembers them, which is all [`Machine`] asks for. So the
7//! HTML machine is native and in-process: its state is one document term, and
8//! the three message sorts read as a DOM would read them.
9//!
10//! * A **definition** (`Item`, `Stmt`, `File` — HTML has no statements, so
11//!   the sorts collapse) is a fragment. Each top-level element that carries
12//!   an `id` the document already has *replaces* the element of that id, in
13//!   place; everything else is appended (into `<body>` when there is one).
14//!   Ids are the document's own namespace, so they are the machine's
15//!   definitions — the way `y = 40` is a Python machine's.
16//! * A **query** (`Expr`) is a selector `#id`, answered with the element's
17//!   own markup — the value's literal, as the denotation law wants. Any
18//!   other fragment fed as a query answers itself: a fragment of markup *is*
19//!   its own value.
20//! * The **typing judgment** answers an element's tag name: the type of an
21//!   HTML value is what kind of element it is.
22//!
23//! This is what `quilt notebook` runs on (see `crate::notebook`): the page
24//! is the HTML machine, each cell's output is fed to it, and a cell that
25//! prints `<p id="summary">…</p>` redefines the summary wherever the author
26//! put it. But the machine is independent of notebooks — `html⟨M⟩` in a
27//! Python or Rust program spawns one, `quilt repl html` talks to one, and
28//! the conformance battery holds it to the same three laws as the rest.
29
30use super::{Answer, Def, IntrospectMachine, Machine, Snapshot, SnapshotMachine};
31use crate::lang::InnerKind;
32use crate::prelude::*;
33use crate::qterm::QTerm;
34use crate::strcmd::StrCmd;
35use crate::term::CmdOrHole;
36use miette::{bail, IntoDiagnostic};
37
38/**************************************************************/
39
40/// A document, held as a term, driven as a machine. See the module docs.
41pub struct HtmlMachine {
42    /// Always a `document` tuple (possibly empty).
43    doc: Arc<QTerm>,
44}
45
46impl Default for HtmlMachine {
47    fn default() -> Self {
48        HtmlMachine {
49            doc: tuple("document", &[], &[]),
50        }
51    }
52}
53
54/// What [`HtmlMachine::define`] did with a fragment.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum Defined {
57    /// The fragment carried an id the document had: the old element is gone
58    /// and the fragment stands in its place.
59    Replaced,
60    /// No such id (or no id): the fragment was appended.
61    Appended,
62}
63
64impl HtmlMachine {
65    /// Adopt a parsed document. A whole `document` is taken as is (its layout
66    /// included); a single element or text node becomes a document of one.
67    #[must_use]
68    pub fn new(doc: &QTerm) -> Self {
69        let root = unwrap_root(doc);
70        let doc = match root {
71            QTerm::Tuple { tag, .. } if &**tag == "document" => arc(root.clone()),
72            _ => tuple("document", &[arc(root.clone())], &[CmdOrHole::Hole]),
73        };
74        HtmlMachine { doc }
75    }
76
77    /// The document as it stands.
78    #[must_use]
79    pub fn document(&self) -> &Arc<QTerm> {
80        &self.doc
81    }
82
83    /// The element with this id, if the document has one.
84    #[must_use]
85    pub fn find(&self, id: &str) -> Option<Arc<QTerm>> {
86        find_first(&self.doc, &|t| element_id(t).as_deref() == Some(id))
87    }
88
89    /// What the element with this id *says*: its text content, entities
90    /// decoded, markup dropped. `None` when there is no such element.
91    #[must_use]
92    pub fn text(&self, id: &str) -> Option<String> {
93        self.find(id).map(|el| text_content(&el))
94    }
95
96    /// Every id the document defines, in document order.
97    #[must_use]
98    pub fn ids(&self) -> Vec<String> {
99        let mut ids = Vec::new();
100        collect_ids(&self.doc, &mut ids);
101        ids
102    }
103
104    /// Define one node: replace the element that has its id, else append it.
105    ///
106    /// The node's layout is baked first ([`bake_layout`]), so it renders
107    /// exactly as fed wherever it lands: the indentation of its new
108    /// surroundings cannot leak into it, which inside a `<pre>` would be a
109    /// change of content, not of layout.
110    pub fn define(&mut self, node: &Arc<QTerm>) -> Defined {
111        let node = bake_layout(node);
112        if let Some(id) = element_id(&node) {
113            if let Some(doc) = map_first(
114                &self.doc,
115                &|t| element_id(t).as_deref() == Some(id.as_str()),
116                &|_| node.clone(),
117            ) {
118                self.doc = doc;
119                return Defined::Replaced;
120            }
121        }
122        self.append_baked(&node);
123        Defined::Appended
124    }
125
126    /// Append a node (layout baked, as for [`define`](Self::define)): into
127    /// `<body>` when the document has one, else at the end of the document.
128    pub fn append(&mut self, node: &Arc<QTerm>) {
129        self.append_baked(&bake_layout(node));
130    }
131
132    /// Insert a node directly after the element with `anchor_id`, as its
133    /// next sibling. `false` (and no change) when the document has no such
134    /// element — the caller's cue to [`append`](Self::append) instead.
135    ///
136    /// [`define`](Self::define) can only replace or append, which is all a
137    /// machine's definitions need; a *live* page also has to put a new cell
138    /// where the author is looking, and "after that element" is the only
139    /// position an editor can name with the ids it already has.
140    pub fn insert_after(&mut self, anchor_id: &str, node: &Arc<QTerm>) -> bool {
141        let node = bake_layout(node);
142        let found = map_parent(
143            &self.doc,
144            &|t| element_id(t).as_deref() == Some(anchor_id),
145            &|parent, index| insert_child_after(parent, index, &node),
146        );
147        match found {
148            Some(doc) => {
149                self.doc = doc;
150                true
151            }
152            None => false,
153        }
154    }
155
156    /// Remove the element with this id, leaving its place empty. `false`
157    /// when the document has no such element.
158    ///
159    /// The element becomes an empty text node rather than being spliced out:
160    /// a parent's layout commands interleave its children by position, so
161    /// blanking one keeps every other child rendering exactly where it was.
162    pub fn remove(&mut self, id: &str) -> bool {
163        let found = map_first(
164            &self.doc,
165            &|t| element_id(t).as_deref() == Some(id),
166            &|_| leaf("text", ""),
167        );
168        match found {
169            Some(doc) => {
170                self.doc = doc;
171                true
172            }
173            None => false,
174        }
175    }
176
177    /// The document with every element whose id satisfies `pred` blanked —
178    /// the page as a *page*, when the ids named are its cell chrome. See
179    /// [`remove`](Self::remove) for why blanking rather than splicing.
180    #[must_use]
181    pub fn document_without(&self, pred: &dyn Fn(&str) -> bool) -> Arc<QTerm> {
182        fn go(term: &Arc<QTerm>, pred: &dyn Fn(&str) -> bool) -> Arc<QTerm> {
183            if element_id(term).is_some_and(|id| pred(&id)) {
184                return leaf("text", "");
185            }
186            match &**term {
187                QTerm::Tuple { tag, terms, cmds } => {
188                    let terms: Vec<_> = terms.iter().map(|t| go(t, pred)).collect();
189                    tuple(tag, &terms, cmds)
190                }
191                _ => term.clone(),
192            }
193        }
194        go(&self.doc, pred)
195    }
196
197    fn append_baked(&mut self, node: &Arc<QTerm>) {
198        let into_body = map_first(
199            &self.doc,
200            &|t| tag_name(t).as_deref() == Some("body"),
201            &|body| append_child(body, node),
202        );
203        self.doc = into_body.unwrap_or_else(|| append_child(&self.doc, node));
204    }
205}
206
207impl Machine for HtmlMachine {
208    fn lang(&self) -> &'static str {
209        "html"
210    }
211
212    fn feed(&mut self, kind: InnerKind, term: &QTerm) -> Result<Answer> {
213        let nodes = top_level(term);
214        // A selector is a query whatever sort it was sent as: `#id` is not a
215        // fragment anyone could mean to define.
216        if let [one] = nodes.as_slice() {
217            if let Some(id) = selector(one) {
218                let el = self
219                    .find(id)
220                    .ok_or_else(|| miette!("the html machine has no element with id {id:?}"))?;
221                return Ok(Answer {
222                    value: Some(el.coparse().into()),
223                    ..Answer::default()
224                });
225            }
226        }
227        if kind == InnerKind::Expr {
228            // Denotation: a fragment queried answers itself.
229            return Ok(Answer {
230                value: Some(term.coparse().trim().into()),
231                ..Answer::default()
232            });
233        }
234        for node in &nodes {
235            self.define(node);
236        }
237        Ok(Answer::default())
238    }
239
240    /// The type of an HTML value is its element name: `#id` answers the tag
241    /// of the element it names, an element its own tag, text `text`.
242    fn type_of(&mut self, term: &QTerm) -> Result<Answer> {
243        let nodes = top_level(term);
244        let [one] = nodes.as_slice() else {
245            bail!(
246                "the html machine types one node at a time; got {} top-level nodes",
247                nodes.len()
248            );
249        };
250        let node = match selector(one) {
251            Some(id) => self
252                .find(id)
253                .ok_or_else(|| miette!("the html machine has no element with id {id:?}"))?,
254            None => one.clone(),
255        };
256        let ty = match tag_name(&node) {
257            Some(tag) => tag,
258            None => match &*node {
259                QTerm::Tuple { tag, .. } => tag.to_string(),
260                QTerm::Quote { .. } => "quote".to_string(),
261                QTerm::Unquote { .. } => "unquote".to_string(),
262            },
263        };
264        Ok(Answer {
265            value: Some(ty.into()),
266            ..Answer::default()
267        })
268    }
269}
270
271/// The whole document is the state, so a snapshot is the document.
272impl SnapshotMachine for HtmlMachine {
273    fn snapshot(&self) -> Result<Snapshot> {
274        Ok(Snapshot(
275            postcard::to_stdvec(&*self.doc).into_diagnostic()?.into(),
276        ))
277    }
278
279    fn restore(&mut self, snapshot: &Snapshot) -> Result<()> {
280        let doc: QTerm = postcard::from_bytes(&snapshot.0).into_diagnostic()?;
281        self.doc = arc(doc);
282        Ok(())
283    }
284}
285
286/// The definitions are the ids.
287impl IntrospectMachine for HtmlMachine {
288    fn defs(&self) -> Result<Vec<Def>> {
289        Ok(self
290            .ids()
291            .into_iter()
292            .map(|id| Def {
293                name: id.into(),
294                kind: InnerKind::Item,
295            })
296            .collect())
297    }
298}
299
300/**************************************************************/
301// Term helpers. Public because the notebook driver reads documents with the
302// same eyes the machine does — one notion of "the element with this id".
303
304/// See through the tagless root `parse_chain` wraps a parsed fragment in.
305fn unwrap_root(term: &QTerm) -> &QTerm {
306    match term {
307        QTerm::Tuple { tag, terms, .. } if tag.is_empty() && terms.len() == 1 => {
308            unwrap_root(&terms[0])
309        }
310        _ => term,
311    }
312}
313
314/// The top-level nodes of a fragment: a `document`'s children, else the
315/// fragment itself (a single element or text node).
316#[must_use]
317pub fn top_level(term: &QTerm) -> Vec<Arc<QTerm>> {
318    match unwrap_root(term) {
319        QTerm::Tuple { tag, terms, .. } if &**tag == "document" => terms.to_vec(),
320        other => vec![arc(other.clone())],
321    }
322}
323
324/// `#id`, when `node` is a text node holding exactly one selector.
325#[must_use]
326pub fn selector(node: &QTerm) -> Option<&str> {
327    let QTerm::Tuple { tag, terms, cmds } = node else {
328        return None;
329    };
330    if &**tag != "text" || !terms.is_empty() {
331        return None;
332    }
333    let [CmdOrHole::Cmd(StrCmd::Write(text))] = &**cmds else {
334        return None;
335    };
336    let text = text.trim();
337    let id = text.strip_prefix('#')?;
338    (!id.is_empty() && !id.contains(char::is_whitespace)).then_some(id)
339}
340
341fn children(term: &QTerm) -> &[Arc<QTerm>] {
342    match term {
343        QTerm::Tuple { terms, .. } => terms,
344        QTerm::Quote { .. } | QTerm::Unquote { .. } => &[],
345    }
346}
347
348fn tag_is(term: &QTerm, want: &str) -> bool {
349    matches!(term, QTerm::Tuple { tag, .. } if &**tag == want)
350}
351
352/// The text of a leaf (a tuple with no children and one `Write`).
353fn leaf_text(term: &QTerm) -> Option<&str> {
354    match term {
355        QTerm::Tuple { terms, cmds, .. } if terms.is_empty() => match &**cmds {
356            [CmdOrHole::Cmd(StrCmd::Write(s))] => Some(s),
357            _ => None,
358        },
359        _ => None,
360    }
361}
362
363/// The `start_tag` / `self_closing_tag` of an element. `<script>` and
364/// `<style>` are elements too, under their own node kinds.
365fn opening_tag(term: &QTerm) -> Option<&QTerm> {
366    if !(tag_is(term, "element") || tag_is(term, "script_element") || tag_is(term, "style_element"))
367    {
368        return None;
369    }
370    children(term)
371        .first()
372        .map(AsRef::as_ref)
373        .filter(|t| tag_is(t, "start_tag") || tag_is(t, "self_closing_tag"))
374}
375
376/// An element's tag name (`p` for `<p>…</p>`).
377#[must_use]
378pub fn tag_name(term: &QTerm) -> Option<String> {
379    let open = opening_tag(term)?;
380    children(open)
381        .iter()
382        .find(|t| tag_is(t, "tag_name"))
383        .and_then(|t| leaf_text(t))
384        .map(str::to_string)
385}
386
387/// An element's `id` attribute value, when it has one.
388#[must_use]
389pub fn element_id(term: &QTerm) -> Option<String> {
390    let open = opening_tag(term)?;
391    children(open)
392        .iter()
393        .filter(|t| tag_is(t, "attribute"))
394        .find_map(|attr| {
395            let parts = children(attr);
396            let name = parts.first().and_then(|n| leaf_text(n))?;
397            if name != "id" {
398                return None;
399            }
400            let value = parts.iter().skip(1).find_map(|p| {
401                if tag_is(p, "attribute_value") {
402                    leaf_text(p).map(str::to_string)
403                } else if tag_is(p, "quoted_attribute_value") {
404                    children(p)
405                        .iter()
406                        .find(|q| tag_is(q, "attribute_value"))
407                        .and_then(|q| leaf_text(q))
408                        .map(str::to_string)
409                } else {
410                    None
411                }
412            });
413            // `<p id>` (no value) defines the empty id, which nothing can
414            // reference; treat it as no id.
415            value.filter(|v| !v.is_empty())
416        })
417}
418
419/// The text content of a node: text and entities, markup dropped, script
420/// and style bodies skipped. The whitespace between nodes is layout the
421/// parser keeps as `Write`/`NewLine` commands on the parent rather than as
422/// text nodes, so the walk follows the commands, not just the children.
423#[must_use]
424pub fn text_content(term: &QTerm) -> String {
425    fn collect(term: &QTerm, out: &mut String) {
426        let QTerm::Tuple { tag, terms, cmds } = term else {
427            out.push_str(&term.coparse());
428            return;
429        };
430        match &**tag {
431            "entity" => out.push_str(&decode_entity(leaf_text(term).unwrap_or_default())),
432            "start_tag" | "end_tag" | "self_closing_tag" | "doctype" | "comment"
433            | "script_element" | "style_element" | "raw_text" => {}
434            _ => {
435                let mut children = terms.iter();
436                for cmd in cmds {
437                    match cmd {
438                        CmdOrHole::Hole => {
439                            if let Some(child) = children.next() {
440                                collect(child, out);
441                            }
442                        }
443                        CmdOrHole::Cmd(StrCmd::Write(s)) => out.push_str(s),
444                        CmdOrHole::Cmd(StrCmd::NewLine) => out.push('\n'),
445                        CmdOrHole::Cmd(StrCmd::Push(_) | StrCmd::Pop) => {}
446                    }
447                }
448            }
449        }
450    }
451    let mut out = String::new();
452    collect(term, &mut out);
453    out
454}
455
456/// Decode one HTML entity (`&amp;`, `&#39;`, `&#x27;`, …); unknown ones are
457/// kept as written.
458fn decode_entity(entity: &str) -> String {
459    let inner = entity
460        .strip_prefix('&')
461        .and_then(|s| s.strip_suffix(';'))
462        .unwrap_or(entity);
463    let decoded = match inner {
464        "amp" => Some('&'),
465        "lt" => Some('<'),
466        "gt" => Some('>'),
467        "quot" => Some('"'),
468        "apos" => Some('\''),
469        "nbsp" => Some('\u{a0}'),
470        _ => inner
471            .strip_prefix('#')
472            .and_then(|n| match n.strip_prefix(['x', 'X']) {
473                Some(hex) => u32::from_str_radix(hex, 16).ok(),
474                None => n.parse().ok(),
475            })
476            .and_then(char::from_u32),
477    };
478    decoded.map_or_else(|| entity.to_string(), String::from)
479}
480
481fn collect_ids(term: &QTerm, out: &mut Vec<String>) {
482    if let Some(id) = element_id(term) {
483        out.push(id);
484    }
485    for child in children(term) {
486        collect_ids(child, out);
487    }
488}
489
490/// Bake a fragment's layout into its text: every `NewLine` becomes a
491/// literal newline carrying the prefix the fragment's *own* pushes had built
492/// at that point, and the pushes and pops are dropped. A `Write` ignores the
493/// prefix stack, so a baked fragment renders the same wherever it is
494/// grafted — the enclosing element's indentation cannot reach it. The cost
495/// is cosmetic: a grafted fragment is not re-indented to match its
496/// neighbours.
497#[must_use]
498pub fn bake_layout(term: &Arc<QTerm>) -> Arc<QTerm> {
499    fn go(term: &Arc<QTerm>, stack: &mut Vec<Box<str>>) -> Arc<QTerm> {
500        let (cmds, terms): (&[CmdOrHole], &[Arc<QTerm>]) = match &**term {
501            QTerm::Tuple { terms, cmds, .. } => (cmds, terms),
502            QTerm::Quote { term, cmds, .. } | QTerm::Unquote { term, cmds, .. } => {
503                (cmds, std::slice::from_ref(term))
504            }
505        };
506        let mut new_cmds = Vec::with_capacity(cmds.len());
507        let mut new_terms = Vec::with_capacity(terms.len());
508        let mut children = terms.iter();
509        for cmd in cmds {
510            match cmd {
511                CmdOrHole::Hole => {
512                    if let Some(child) = children.next() {
513                        let depth = stack.len();
514                        new_terms.push(go(child, stack));
515                        stack.truncate(depth);
516                    }
517                    new_cmds.push(CmdOrHole::Hole);
518                }
519                CmdOrHole::Cmd(StrCmd::NewLine) => {
520                    let mut line = String::from("\n");
521                    for prefix in stack.iter() {
522                        line.push_str(prefix);
523                    }
524                    new_cmds.push(CmdOrHole::Cmd(StrCmd::Write(line.into())));
525                }
526                CmdOrHole::Cmd(StrCmd::Push(prefix)) => stack.push(prefix.clone()),
527                CmdOrHole::Cmd(StrCmd::Pop) => {
528                    stack.pop();
529                }
530                CmdOrHole::Cmd(write @ StrCmd::Write(_)) => {
531                    new_cmds.push(CmdOrHole::Cmd(write.clone()));
532                }
533            }
534        }
535        // Children beyond the holes (none, for a parsed term) are kept.
536        new_terms.extend(children.map(|c| go(c, stack)));
537        match &**term {
538            QTerm::Tuple { tag, .. } => tuple(tag, &new_terms, &new_cmds),
539            QTerm::Quote {
540                tag,
541                index,
542                lang,
543                span,
544                ..
545            } => arc(crate::qterm::qquote_at(
546                tag,
547                *index,
548                lang,
549                new_terms.remove(0),
550                &new_cmds,
551                span.clone(),
552            )),
553            QTerm::Unquote {
554                tag,
555                index,
556                lang,
557                span,
558                ..
559            } => arc(crate::qterm::qunquote_at(
560                tag,
561                *index,
562                lang,
563                new_terms.remove(0),
564                &new_cmds,
565                span.clone(),
566            )),
567        }
568    }
569    go(term, &mut Vec::new())
570}
571
572/// The first node (pre-order) satisfying `pred`.
573fn find_first(term: &Arc<QTerm>, pred: &dyn Fn(&QTerm) -> bool) -> Option<Arc<QTerm>> {
574    if pred(term) {
575        return Some(term.clone());
576    }
577    children(term).iter().find_map(|c| find_first(c, pred))
578}
579
580/// Rebuild the tree with the first node (pre-order) satisfying `pred`
581/// replaced by `f(node)`; `None` if nothing matched.
582fn map_first(
583    term: &Arc<QTerm>,
584    pred: &dyn Fn(&QTerm) -> bool,
585    f: &dyn Fn(&Arc<QTerm>) -> Arc<QTerm>,
586) -> Option<Arc<QTerm>> {
587    if pred(term) {
588        return Some(f(term));
589    }
590    let QTerm::Tuple { tag, terms, cmds } = &**term else {
591        return None;
592    };
593    let (i, new) = terms
594        .iter()
595        .enumerate()
596        .find_map(|(i, c)| map_first(c, pred, f).map(|n| (i, n)))?;
597    let mut terms = terms.to_vec();
598    terms[i] = new;
599    Some(tuple(tag, &terms, cmds))
600}
601
602/// Rebuild the tree with the first tuple that has a *direct child*
603/// satisfying `pred` replaced by `f(parent, index_of_that_child)`; `None`
604/// if nothing matched. The sibling-position counterpart of [`map_first`].
605fn map_parent(
606    term: &Arc<QTerm>,
607    pred: &dyn Fn(&QTerm) -> bool,
608    f: &dyn Fn(&Arc<QTerm>, usize) -> Arc<QTerm>,
609) -> Option<Arc<QTerm>> {
610    let QTerm::Tuple { tag, terms, cmds } = &**term else {
611        return None;
612    };
613    if let Some(index) = terms.iter().position(|c| pred(c)) {
614        return Some(f(term, index));
615    }
616    let (i, new) = terms
617        .iter()
618        .enumerate()
619        .find_map(|(i, c)| map_parent(c, pred, f).map(|n| (i, n)))?;
620    let mut terms = terms.to_vec();
621    terms[i] = new;
622    Some(tuple(tag, &terms, cmds))
623}
624
625/// `container` with `child` inserted after the child at `index`, on its own
626/// line. Children are interleaved with the layout by *hole position*, so the
627/// new hole goes directly after the `index`-th one and the new term directly
628/// after the `index`-th term.
629fn insert_child_after(container: &Arc<QTerm>, index: usize, child: &Arc<QTerm>) -> Arc<QTerm> {
630    let QTerm::Tuple { tag, terms, cmds } = &**container else {
631        return container.clone();
632    };
633    let mut seen = 0;
634    let mut at = cmds.len();
635    for (i, c) in cmds.iter().enumerate() {
636        if matches!(c, CmdOrHole::Hole) {
637            if seen == index {
638                at = i + 1;
639                break;
640            }
641            seen += 1;
642        }
643    }
644    let mut cmds: Vec<CmdOrHole> = cmds.to_vec();
645    cmds.splice(at..at, [CmdOrHole::Cmd(StrCmd::NewLine), CmdOrHole::Hole]);
646    let mut terms = terms.to_vec();
647    terms.insert(index + 1, child.clone());
648    tuple(tag, &terms, &cmds)
649}
650
651/// `container` with `child` appended: before the end tag of an element,
652/// at the end of anything else. The new child lands on its own line, at the
653/// indentation of its new siblings when the layout commands say what that
654/// is.
655fn append_child(container: &Arc<QTerm>, child: &Arc<QTerm>) -> Arc<QTerm> {
656    let QTerm::Tuple { tag, terms, cmds } = &**container else {
657        return container.clone();
658    };
659    let mut cmds: Vec<CmdOrHole> = cmds.to_vec();
660    let mut terms = terms.to_vec();
661    let closes = terms.last().is_some_and(|t| tag_is(t, "end_tag"));
662    if closes {
663        // Insert before the end tag's hole — and before the newline/pop
664        // run that precedes it, so the child is indented like its siblings.
665        let end_hole = cmds
666            .iter()
667            .rposition(|c| matches!(c, CmdOrHole::Hole))
668            .expect("an element with an end tag has a hole for it");
669        let mut at = end_hole;
670        while at > 0 && matches!(cmds[at - 1], CmdOrHole::Cmd(StrCmd::NewLine | StrCmd::Pop)) {
671            at -= 1;
672        }
673        let index = cmds[..at]
674            .iter()
675            .filter(|c| matches!(c, CmdOrHole::Hole))
676            .count();
677        cmds.splice(at..at, [CmdOrHole::Cmd(StrCmd::NewLine), CmdOrHole::Hole]);
678        terms.insert(index, child.clone());
679    } else {
680        if !terms.is_empty() {
681            cmds.push(CmdOrHole::Cmd(StrCmd::NewLine));
682        }
683        cmds.push(CmdOrHole::Hole);
684        terms.push(child.clone());
685    }
686    tuple(tag, &terms, &cmds)
687}
688
689/**************************************************************/
690
691#[cfg(all(test, feature = "html"))]
692mod tests {
693    use super::*;
694    use crate::lang::{flat_nodes, Language as _};
695    use crate::langs::html::lang::HtmlLanguage;
696
697    fn html(src: &str) -> Arc<QTerm> {
698        HtmlLanguage::default()
699            .parse_as(None, &flat_nodes(src))
700            .expect("fixture parses")
701    }
702
703    fn feed(m: &mut HtmlMachine, src: &str) -> Answer {
704        m.feed(InnerKind::File, &html(src)).expect("feed")
705    }
706
707    fn ask(m: &mut HtmlMachine, src: &str) -> String {
708        m.eval(&html(src)).expect("eval").value.unwrap().to_string()
709    }
710
711    #[test]
712    fn definitions_are_ids_and_queries_are_selectors() {
713        let mut m = HtmlMachine::default();
714        feed(&mut m, "<p id=\"y\">40</p>");
715        assert_eq!(ask(&mut m, "#y"), "<p id=\"y\">40</p>");
716        assert_eq!(m.text("y").as_deref(), Some("40"));
717    }
718
719    #[test]
720    fn redefining_an_id_replaces_in_place() {
721        let mut m = HtmlMachine::new(&html(
722            "<div id=\"a\">\n  <p id=\"y\">40</p>\n  <p id=\"z\">1</p>\n</div>",
723        ));
724        feed(&mut m, "<b id=\"y\">42</b>");
725        let doc = m.document().coparse();
726        assert_eq!(
727            doc, "<div id=\"a\">\n  <b id=\"y\">42</b>\n  <p id=\"z\">1</p>\n</div>",
728            "replaced where it stood, layout kept"
729        );
730        assert_eq!(m.ids(), ["a", "y", "z"]);
731    }
732
733    #[test]
734    fn unknown_ids_and_idless_nodes_append_into_body() {
735        let mut m = HtmlMachine::new(&html(
736            "<html>\n<body>\n  <p id=\"a\">1</p>\n</body>\n</html>",
737        ));
738        feed(&mut m, "<p id=\"b\">2</p>");
739        feed(&mut m, "plain text");
740        let doc = m.document().coparse();
741        assert_eq!(
742            doc,
743            "<html>\n<body>\n  <p id=\"a\">1</p>\n  <p id=\"b\">2</p>\n  plain text\n</body>\n</html>"
744        );
745    }
746
747    #[test]
748    fn fragments_without_a_body_append_at_the_end() {
749        let mut m = HtmlMachine::default();
750        feed(&mut m, "<p>a</p>");
751        feed(&mut m, "<p>b</p>\n<p>c</p>");
752        assert_eq!(m.document().coparse(), "<p>a</p>\n<p>b</p>\n<p>c</p>");
753    }
754
755    #[test]
756    fn a_fragment_queried_answers_itself() {
757        let mut m = HtmlMachine::default();
758        assert_eq!(ask(&mut m, "<b>x</b>"), "<b>x</b>");
759        assert!(m.ids().is_empty(), "a query defines nothing");
760    }
761
762    #[test]
763    fn a_missing_id_is_an_error() {
764        let mut m = HtmlMachine::default();
765        let err = m.eval(&html("#nope")).unwrap_err();
766        assert!(err.to_string().contains("\"nope\""), "{err}");
767    }
768
769    /// `<style>` and `<script>` carry ids like any element, under the
770    /// grammar's own node kinds for them.
771    #[test]
772    fn style_and_script_elements_have_ids() {
773        let mut m = HtmlMachine::default();
774        feed(
775            &mut m,
776            "<style id=\"s\">.a{}</style><script id=\"j\">1</script>",
777        );
778        assert_eq!(m.ids(), ["s", "j"]);
779        feed(&mut m, "<style id=\"s\">.b{}</style>");
780        // Appended nodes land one per line; the replacement keeps the layout.
781        assert_eq!(
782            m.document().coparse(),
783            "<style id=\"s\">.b{}</style>\n<script id=\"j\">1</script>"
784        );
785    }
786
787    #[test]
788    fn types_are_tag_names() {
789        let mut m = HtmlMachine::default();
790        feed(&mut m, "<section id=\"s\"><p>x</p></section>");
791        let ty = |m: &mut HtmlMachine, s: &str| m.type_of(&html(s)).unwrap().value.unwrap();
792        assert_eq!(&*ty(&mut m, "#s"), "section");
793        assert_eq!(&*ty(&mut m, "<input id=\"q\"/>"), "input");
794        assert_eq!(&*ty(&mut m, "hello"), "text");
795    }
796
797    #[test]
798    fn text_content_decodes_entities_and_drops_markup() {
799        let el = html("<p id=\"t\">a &amp; <b>b</b> &#x27;c&#39; &lt;d&gt;</p>");
800        assert_eq!(text_content(&el), "a & b 'c' <d>");
801    }
802
803    #[test]
804    fn snapshots_roll_the_document_back() {
805        let mut m = HtmlMachine::default();
806        feed(&mut m, "<p id=\"y\">1</p>");
807        let snap = m.snapshot().unwrap();
808        feed(&mut m, "<p id=\"y\">2</p>");
809        assert_eq!(m.text("y").as_deref(), Some("2"));
810        m.restore(&snap).unwrap();
811        assert_eq!(m.text("y").as_deref(), Some("1"));
812    }
813
814    #[test]
815    fn defs_are_the_ids() {
816        let mut m = HtmlMachine::default();
817        feed(&mut m, "<p id=\"a\">1</p><p id=\"b\">2</p>");
818        let defs: Vec<_> = m.defs().unwrap().into_iter().map(|d| d.name).collect();
819        assert_eq!(defs, ["a".into(), "b".into()]);
820    }
821
822    #[test]
823    fn machines_are_isolated() {
824        let mut a = HtmlMachine::default();
825        let mut b = HtmlMachine::default();
826        feed(&mut a, "<p id=\"y\">1</p>");
827        assert!(b.eval(&html("#y")).is_err());
828    }
829
830    /// A multi-line fragment grafted into an indented position keeps its
831    /// own lines exactly — inside a `<pre>` the enclosing indentation would
832    /// be content.
833    #[test]
834    fn grafted_fragments_keep_their_layout() {
835        let mut m = HtmlMachine::new(&html("<div>\n    <p id=\"slot\">x</p>\n</div>"));
836        feed(&mut m, "<pre id=\"slot\">a\nb\n  c</pre>");
837        let doc = m.document().coparse();
838        assert!(
839            doc.contains("<pre id=\"slot\">a\nb\n  c</pre>"),
840            "lines must not be re-indented: {doc}"
841        );
842        assert_eq!(m.text("slot").as_deref(), Some("a\nb\n  c"));
843    }
844}