Skip to main content

quilt/langs/typescript/
lang.rs

1use crate::{
2    lang::{Arity, Comments, InnerKind},
3    qterm::{QTerm, QTermTag},
4    term::Term,
5    treesitter::{DynTSLanguage, TSLanguage, TSProvider},
6};
7use miette::Result;
8use tree_sitter::Parser;
9
10/**************************************************************/
11
12pub struct TypeScriptProvider(tree_sitter::Parser);
13
14impl Default for TypeScriptProvider {
15    fn default() -> Self {
16        let mut parser = Parser::new();
17        parser
18            .set_language(&crate::grammars::typescript::LANGUAGE_TYPESCRIPT.into())
19            .expect("Error loading TypeScript parser");
20        Self(parser)
21    }
22}
23
24impl TSProvider for TypeScriptProvider {
25    fn parser(&mut self) -> &mut tree_sitter::Parser {
26        &mut self.0
27    }
28
29    fn hole_str(&self) -> &'static str {
30        // Matches `quilt_hole: _ => '__HOLE__'` in the forked grammar.
31        "__HOLE__"
32    }
33
34    fn hashbang(&self) -> Option<&'static str> {
35        Some("#!/usr/bin/env -S node --experimental-strip-types")
36    }
37
38    /// `JSON.stringify` spells numbers, strings, arrays and plain objects as
39    /// valid TypeScript literals — the value's own denotation, like Python's
40    /// `repr`. (Values JSON can't spell — functions, `undefined` — answer
41    /// nothing; a richer provider can bind those to names instead.)
42    /// Registered in `machine::script_spec`; see `PythonProvider::machine_spec`.
43    fn machine_spec(&self) -> Option<crate::machine::MachineSpec> {
44        crate::machine::script_spec("typescript")
45    }
46
47    /// Preferred over the replay spec: one long-lived `node` running a small
48    /// `vm`-context kernel (`machine::TYPESCRIPT_KERNEL`), so a `const` fed
49    /// by one feed is real process state for the next, and effects run once.
50    fn repl_spec(&self) -> Option<crate::machine::ReplSpec> {
51        crate::machine::repl_spec("typescript")
52    }
53
54    /// Derived from the grammar's `REPEAT` rules by `bin/gen-arity`, not
55    /// hand-curated — see `quilt/src/langs/arity.rs` (#202).
56    fn arity(&self, tag: &str) -> Arity {
57        Arity::from_table(crate::langs::arity::TYPESCRIPT, tag)
58    }
59
60    /// `,` for the kinds `bin/gen-arity` finds comma-separated (#293).
61    fn separator(&self, tag: &str) -> Option<&'static str> {
62        crate::lang::comma_separator(crate::langs::arity::TYPESCRIPT_COMMA_SEPARATED, tag)
63    }
64
65    fn typ(&self, tag: &str) -> InnerKind {
66        if tag == "program" {
67            InnerKind::File
68        } else if tag.ends_with("_statement")
69            || tag.ends_with("_declaration")
70            || tag.ends_with("_definition")
71        {
72            InnerKind::Stmt
73        } else {
74            InnerKind::Expr
75        }
76    }
77
78    /// Strip the `program` root around a quoted fragment and infer whether the
79    /// content is an expression, statement, or whole file — mirroring the
80    /// Python provider. A single top-level `expression_statement` squashes to
81    /// its inner expression (so `ts↖foo()↗` splices in expression position);
82    /// the hole's known position (`ikind`) settles the ambiguous cases.
83    fn unwrap(&self, qterm: QTerm, ikind: Option<InnerKind>) -> Result<(QTerm, InnerKind)> {
84        // empty file, or several top-level nodes — keep the `program` whole.
85        if qterm.len() != 1 {
86            return Ok((qterm, InnerKind::File));
87        }
88        let qterm = qterm.squash();
89        if qterm.tag() == QTermTag::tuple("expression_statement") {
90            // An expression with a trailing `;` (len 2) or a bare comma
91            // sequence: keep the statement, but it splices flat as an
92            // expression.
93            if qterm.len() != 1 {
94                return Ok((qterm, InnerKind::Expr));
95            }
96            let inner = qterm.squash();
97            // When the caller explicitly placed the hole in statement position,
98            // honour that (keep the `expression_statement`); otherwise treat a
99            // bare expression statement as an expression.
100            if ikind == Some(InnerKind::Stmt) {
101                return Ok((qterm, InnerKind::Stmt));
102            }
103            return Ok((inner, InnerKind::Expr));
104        }
105        // A declaration / control-flow statement / other top-level node. Trust
106        // an explicit expression expectation over the default Stmt guess.
107        if ikind == Some(InnerKind::Expr) {
108            return Ok((qterm, InnerKind::Expr));
109        }
110        let tag = match &qterm {
111            QTerm::Tuple { tag, .. } => self.typ(tag),
112            _ => InnerKind::Stmt,
113        };
114        Ok((qterm, tag))
115    }
116}
117
118pub type TypeScriptLanguage = TSLanguage<TypeScriptProvider>;
119pub type DynTypeScriptLanguage = DynTSLanguage<TypeScriptProvider>;
120
121/// The `//` default is right for TypeScript, header included: it once emitted
122/// Rust's `//!` — valid, but a Rust idiom leaking into another language.
123impl Comments for TypeScriptLanguage {}