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
use crate::{
    lang::{Arity, Comments, InnerKind},
    qterm::{QTerm, QTermTag},
    term::Term,
    treesitter::{DynTSLanguage, TSLanguage, TSProvider},
};
use miette::Result;
use tree_sitter::Parser;

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

pub struct TypeScriptProvider(tree_sitter::Parser);

impl Default for TypeScriptProvider {
    fn default() -> Self {
        let mut parser = Parser::new();
        parser
            .set_language(&crate::grammars::typescript::LANGUAGE_TYPESCRIPT.into())
            .expect("Error loading TypeScript parser");
        Self(parser)
    }
}

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

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

    fn hashbang(&self) -> Option<&'static str> {
        Some("#!/usr/bin/env -S node --experimental-strip-types")
    }

    /// `JSON.stringify` spells numbers, strings, arrays and plain objects as
    /// valid TypeScript literals — the value's own denotation, like Python's
    /// `repr`. (Values JSON can't spell — functions, `undefined` — answer
    /// nothing; a richer provider can bind those to names instead.)
    /// Registered in `machine::script_spec`; see `PythonProvider::machine_spec`.
    fn machine_spec(&self) -> Option<crate::machine::MachineSpec> {
        crate::machine::script_spec("typescript")
    }

    /// Preferred over the replay spec: one long-lived `node` running a small
    /// `vm`-context kernel (`machine::TYPESCRIPT_KERNEL`), so a `const` fed
    /// by one feed is real process state for the next, and effects run once.
    fn repl_spec(&self) -> Option<crate::machine::ReplSpec> {
        crate::machine::repl_spec("typescript")
    }

    /// 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::TYPESCRIPT, tag)
    }

    /// `,` for the kinds `bin/gen-arity` finds comma-separated (#293).
    fn separator(&self, tag: &str) -> Option<&'static str> {
        crate::lang::comma_separator(crate::langs::arity::TYPESCRIPT_COMMA_SEPARATED, tag)
    }

    fn typ(&self, tag: &str) -> InnerKind {
        if tag == "program" {
            InnerKind::File
        } else if tag.ends_with("_statement")
            || tag.ends_with("_declaration")
            || tag.ends_with("_definition")
        {
            InnerKind::Stmt
        } else {
            InnerKind::Expr
        }
    }

    /// Strip the `program` root around a quoted fragment and infer whether the
    /// content is an expression, statement, or whole file — mirroring the
    /// Python provider. A single top-level `expression_statement` squashes to
    /// its inner expression (so `ts↖foo()↗` splices in expression position);
    /// the hole's known position (`ikind`) settles the ambiguous cases.
    fn unwrap(&self, qterm: QTerm, ikind: Option<InnerKind>) -> Result<(QTerm, InnerKind)> {
        // empty file, or several top-level nodes — keep the `program` whole.
        if qterm.len() != 1 {
            return Ok((qterm, InnerKind::File));
        }
        let qterm = qterm.squash();
        if qterm.tag() == QTermTag::tuple("expression_statement") {
            // An expression with a trailing `;` (len 2) or a bare comma
            // sequence: keep the statement, but it splices flat as an
            // expression.
            if qterm.len() != 1 {
                return Ok((qterm, InnerKind::Expr));
            }
            let inner = qterm.squash();
            // When the caller explicitly placed the hole in statement position,
            // honour that (keep the `expression_statement`); otherwise treat a
            // bare expression statement as an expression.
            if ikind == Some(InnerKind::Stmt) {
                return Ok((qterm, InnerKind::Stmt));
            }
            return Ok((inner, InnerKind::Expr));
        }
        // A declaration / control-flow statement / other top-level node. Trust
        // an explicit expression expectation over the default Stmt guess.
        if ikind == Some(InnerKind::Expr) {
            return Ok((qterm, InnerKind::Expr));
        }
        let tag = match &qterm {
            QTerm::Tuple { tag, .. } => self.typ(tag),
            _ => InnerKind::Stmt,
        };
        Ok((qterm, tag))
    }
}

pub type TypeScriptLanguage = TSLanguage<TypeScriptProvider>;
pub type DynTypeScriptLanguage = DynTSLanguage<TypeScriptProvider>;

/// The `//` default is right for TypeScript, header included: it once emitted
/// Rust's `//!` — valid, but a Rust idiom leaking into another language.
impl Comments for TypeScriptLanguage {}