quiltlang 0.6.0

Quilt, a polyglot metaprogramming language: source code with arrow-bracket syntax for embedding and manipulating code fragments of other languages at code-generation time.
Documentation
//! The HTML target language.
//!
//! HTML is only ever a *quoted* language (e.g. `html↖ … ↗` inside Rust): Quilt
//! parses HTML fragments into a `QTerm` and the host language's `MetaLanguage`
//! (Rust's) drives expansion. There is therefore no `HtmlMetaLanguage` — only
//! this `Language` impl, built on the shared tree-sitter helper.
//!
//! The forked grammar accepts holes in node position, interleaved with the
//! `raw_text` of `<script>`/`<style>` elements, and in attribute values — the
//! places interpolation is needed when templating a page.

use crate::{
    lang::{Arity, Comments, InnerKind},
    qterm::QTerm,
    treesitter::{DynTSLanguage, TSLanguage, TSProvider},
};
use miette::Result;
use tree_sitter::Parser;

/**************************************************************/

pub struct HtmlProvider(tree_sitter::Parser);

impl Default for HtmlProvider {
    fn default() -> Self {
        let mut parser = Parser::new();
        parser
            .set_language(&crate::grammars::html::LANGUAGE.into())
            .expect("Error loading HTML parser");
        Self(parser)
    }
}

impl TSProvider for HtmlProvider {
    fn parser(&mut self) -> &mut tree_sitter::Parser {
        &mut self.0
    }

    fn hole_str(&self) -> &'static str {
        // Matches `quilt_hole: $ => "__QUILT_HOLE__"` in the forked grammar.
        "__QUILT_HOLE__"
    }

    /// HTML has no `identifier` node kind, so the trait default would tag a
    /// deferred operator with a kind this grammar does not define. `text` is the
    /// nearest thing: character data, which is where an operator inside an
    /// `html↖ … ↗` quote sits.
    fn ident_tag(&self) -> &'static str {
        "text"
    }

    /// Squash the `document` wrapper around a single quoted fragment so the
    /// term is the fragment itself (element / text / …). A multi-node fragment
    /// (a whole page) stays a `document`.
    ///
    /// The returned `InnerKind` is advisory only (`parse_pre` discards it); like
    /// the WGSL provider, we accept any shape here rather than rejecting
    /// unrecognised ones (only the Rust provider errors on shapes it can't
    /// place).
    fn unwrap(&self, qterm: QTerm, _ikind: Option<InnerKind>) -> Result<(QTerm, InnerKind)> {
        let QTerm::Tuple { tag, terms, .. } = &qterm else {
            return Ok((qterm, InnerKind::default()));
        };
        if &**tag != "document" {
            return Ok((qterm, InnerKind::default()));
        }
        if terms.len() != 1 {
            // empty file, or several top-level nodes (a whole page)
            return Ok((qterm, InnerKind::File));
        }
        let kind = match &*terms[0] {
            QTerm::Tuple { tag, .. } if is_expr_tag(tag) => InnerKind::Expr,
            _ => InnerKind::Stmt,
        };
        Ok((qterm.squash(), kind))
    }

    /// Derived from the grammar's `REPEAT` rules by `bin/gen-arity`, not
    /// hand-curated — see `quilt/src/langs/arity.rs` (#202).
    fn arity(&self, tag: &str) -> Arity {
        Arity::from_table(crate::langs::arity::HTML, tag)
    }

    fn hashbang(&self) -> Option<&'static str> {
        None
    }

    /// Markup runs nothing, but a document *holds* things: the HTML machine
    /// is a document whose definitions are its ids, kept in-process as a
    /// term — see `machine::html`. Registered in `machine::native_machine`,
    /// the way the interpreters are registered in `script_spec`/`repl_spec`.
    fn native_machine(&self) -> Option<Box<dyn crate::machine::Machine>> {
        crate::machine::native_machine("html")
    }
}

/// Tags that are HTML "expressions" (used only to label squashed
/// single-fragment quotes; the label is advisory).
fn is_expr_tag(tag: &str) -> bool {
    matches!(
        tag,
        "text" | "entity" | "raw_text" | "attribute_value" | "quilt_hole"
    )
}

pub type HtmlLanguage = TSLanguage<HtmlProvider>;
pub type DynHtmlLanguage = DynTSLanguage<HtmlProvider>;

impl Comments for HtmlLanguage {
    /// HTML's comments are *delimited* (`<!-- … -->`): a prefix alone would open
    /// one that never closes, so there is no honest answer here. Callers that
    /// need something anyway supply their own — see quilt-lsp's `HtmlAdapter`,
    /// which deliberately projects `<!--` and accepts the over-colored tail.
    const LINE: Option<&'static str> = None;
}