Skip to main content

bynk_ts/
program.rs

1//! [`TsProgram`]/[`TsStmt`] — the tree. P7.5 built it wide enough only for
2//! the `Verbatim` escape hatch (Q2, `design/tracks/the-typescript-tree.md`
3//! §3.2). P7.8 (#1313) adds the real node algebra ([`TsExpr`]/[`TsType`]/
4//! [`TsDecl`], plus real [`TsStmt`] variants) — not the full §7.1 reference
5//! sketch as literally written (a variant-name list with almost no
6//! field-level design), but the subset `bynk-emit/src/emitter/
7//! events_fanout.rs` (Arc C's real next file — P7.8's own proposal
8//! corrected the track doc's stale schedule, see `design/tracks/
9//! the-typescript-tree.md` §6/§9) concretely needs, grounded against that
10//! file's own real shape rather than guessed. Building the rest of the
11//! sketch's unvalidated variants now would repeat the exact "guessing, not
12//! designing" risk `bynk-ts`'s own module doc (`lib.rs`) already named for
13//! this layer — Arc C's later slices add more variants file by file, the
14//! same precedent [`VerbatimOrigin`] already set.
15
16mod decl;
17mod expr;
18mod spans;
19mod stmt;
20mod types;
21mod verbatim;
22
23pub use decl::{TsClassCtor, TsClassField, TsClassMethod, TsDecl, TsParam};
24pub use expr::{TsArrowBody, TsBinaryOp, TsExpr, TsLit, TsObjectEntry, TsUnaryOp};
25pub(crate) use stmt::TsStmtKind;
26pub use stmt::{ExportedName, TsBindingName, TsDeclarator, TsStmt, TsSwitchCase};
27pub use types::{TsMappedModifier, TsType, TsTypeMember};
28pub use verbatim::VerbatimOrigin;
29
30/// A whole generated TypeScript module, as an ordered sequence of top-level
31/// statements. `Vec<TsStmt>`, plain — no richer container yet (P7.6's own
32/// `Artefacts { docs: BTreeMap<PathBuf, Document> }` is where a *project's*
33/// documents get keyed; this is one document's own tree).
34#[derive(Debug, Default)]
35pub struct TsProgram {
36    pub stmts: Vec<TsStmt>,
37}
38
39impl TsProgram {
40    pub fn new() -> Self {
41        Self::default()
42    }
43
44    pub fn push(&mut self, stmt: TsStmt) {
45        self.stmts.push(stmt);
46    }
47
48    /// This program without its top-level import declarations (named, namespace
49    /// and default): the body an import list is derived from (1A.36a, #3737).
50    /// [`crate::unbound_names`] over it is the set the module must import.
51    pub fn without_imports(&self) -> TsProgram {
52        TsProgram {
53            stmts: self
54                .stmts
55                .iter()
56                .filter(|s| {
57                    !matches!(
58                        &s.kind,
59                        TsStmtKind::Decl(
60                            TsDecl::Import { .. }
61                                | TsDecl::ImportNamespace { .. }
62                                | TsDecl::ImportDefault { .. }
63                        )
64                    )
65                })
66                .cloned()
67                .collect(),
68        }
69    }
70
71    /// Every local name the top-level import declarations bind: each entry of a
72    /// named import (`X`, `type X`, `X as Y` bind `X`, `X`, `Y`), a namespace
73    /// alias, and a default import's alias and named entries. Imports written
74    /// inside opaque text are not reported.
75    pub fn imported_names(&self) -> std::collections::BTreeSet<String> {
76        fn local(spec: &str) -> String {
77            let spec = spec.trim();
78            let spec = spec.strip_prefix("type ").unwrap_or(spec).trim();
79            spec.rsplit(" as ")
80                .next()
81                .unwrap_or(spec)
82                .trim()
83                .to_string()
84        }
85        let mut out = std::collections::BTreeSet::new();
86        for stmt in &self.stmts {
87            let TsStmtKind::Decl(decl) = &stmt.kind else {
88                continue;
89            };
90            match decl {
91                TsDecl::Import { names, .. } => out.extend(names.iter().map(|n| local(n))),
92                TsDecl::ImportNamespace { alias, .. } => {
93                    out.insert(alias.clone());
94                }
95                TsDecl::ImportDefault { alias, named, .. } => {
96                    out.insert(alias.clone());
97                    out.extend(named.iter().map(|n| local(n)));
98                }
99                TsDecl::ReExport { .. }
100                | TsDecl::ExportNames { .. }
101                | TsDecl::ReExportAll { .. }
102                | TsDecl::Export(_)
103                | TsDecl::Interface { .. }
104                | TsDecl::ConstDecl { .. }
105                | TsDecl::Class { .. }
106                | TsDecl::Function { .. }
107                | TsDecl::TypeAlias { .. }
108                | TsDecl::ExportDefault(_)
109                | TsDecl::DeclareConst { .. } => {}
110            }
111        }
112        out
113    }
114
115    /// Drop every import this program never uses (1A.36b-2): an entry of a named import whose
116    /// local name no other statement uses, and a namespace import whose alias none does. A named
117    /// import left with no entry goes altogether. The order of what stays is kept, and so is
118    /// each import's `type` prefix; a default import is left alone.
119    ///
120    /// A use is what [`crate::unbound_names_in`] reports over the program without its imports,
121    /// so text the tree cannot see (a `Verbatim` or `Raw` statement, bar the names
122    /// `raw_using` declares) uses nothing. It is how a module whose imports were assembled from
123    /// facts that cannot all hold at once (a fixed header, an import the driver adds for a
124    /// feature a body may not reach) ends up importing what its tree uses and no more.
125    pub fn prune_unused_imports(&mut self) {
126        fn local(spec: &str) -> &str {
127            let spec = spec.trim();
128            let spec = spec.strip_prefix("type ").unwrap_or(spec).trim();
129            spec.rsplit(" as ").next().unwrap_or(spec).trim()
130        }
131        let used: std::collections::BTreeSet<String> =
132            crate::unbound_names_in(&self.without_imports().stmts, |_| true)
133                .into_iter()
134                .collect();
135        self.stmts.retain_mut(|stmt| {
136            let TsStmtKind::Decl(decl) = &mut stmt.kind else {
137                return true;
138            };
139            match decl {
140                TsDecl::Import { names, .. } => {
141                    names.retain(|n| used.contains(local(n)));
142                    !names.is_empty()
143                }
144                TsDecl::ImportNamespace { alias, .. } => used.contains(alias.as_str()),
145                TsDecl::ImportDefault { .. }
146                | TsDecl::ReExport { .. }
147                | TsDecl::ExportNames { .. }
148                | TsDecl::ReExportAll { .. }
149                | TsDecl::Export(_)
150                | TsDecl::Interface { .. }
151                | TsDecl::ConstDecl { .. }
152                | TsDecl::Class { .. }
153                | TsDecl::Function { .. }
154                | TsDecl::TypeAlias { .. }
155                | TsDecl::ExportDefault(_)
156                | TsDecl::DeclareConst { .. } => true,
157            }
158        });
159    }
160
161    /// The local names the top-level named imports from a specifier `from_matches`
162    /// accepts bind (`X`, `type X`, `X as Y` bind `X`, `X`, `Y`): what a module takes
163    /// from one place, such as the runtime (1A.36b-1).
164    pub fn names_imported_from(
165        &self,
166        from_matches: impl Fn(&str) -> bool,
167    ) -> std::collections::BTreeSet<String> {
168        let mut out = std::collections::BTreeSet::new();
169        for stmt in &self.stmts {
170            if let TsStmtKind::Decl(TsDecl::Import { names, from, .. }) = &stmt.kind
171                && from_matches(from)
172            {
173                for spec in names {
174                    let spec = spec.trim();
175                    let spec = spec.strip_prefix("type ").unwrap_or(spec).trim();
176                    out.insert(
177                        spec.rsplit(" as ")
178                            .next()
179                            .unwrap_or(spec)
180                            .trim()
181                            .to_string(),
182                    );
183                }
184            }
185        }
186        out
187    }
188
189    /// The module specifier of every top-level import declaration (named,
190    /// namespace or default), in statement order.
191    pub fn import_specifiers(&self) -> Vec<&str> {
192        self.stmts
193            .iter()
194            .filter_map(|s| match &s.kind {
195                TsStmtKind::Decl(
196                    TsDecl::Import { from, .. }
197                    | TsDecl::ImportNamespace { from, .. }
198                    | TsDecl::ImportDefault { from, .. },
199                ) => Some(from.as_str()),
200                TsStmtKind::Verbatim { .. }
201                | TsStmtKind::Decl(_)
202                | TsStmtKind::Const { .. }
203                | TsStmtKind::Let { .. }
204                | TsStmtKind::ExprStmt(_)
205                | TsStmtKind::Return(_)
206                | TsStmtKind::Throw(_)
207                | TsStmtKind::If { .. }
208                | TsStmtKind::ForOf { .. }
209                | TsStmtKind::For { .. }
210                | TsStmtKind::TryCatch { .. }
211                | TsStmtKind::Block(_)
212                | TsStmtKind::Continue(_)
213                | TsStmtKind::Break(_)
214                | TsStmtKind::While { .. }
215                | TsStmtKind::Labelled { .. }
216                | TsStmtKind::LetList(_)
217                | TsStmtKind::Assign { .. }
218                | TsStmtKind::Comment(_)
219                | TsStmtKind::DocComment(_)
220                | TsStmtKind::Blank
221                | TsStmtKind::Switch { .. }
222                | TsStmtKind::InlineBlock(_)
223                | TsStmtKind::Increment(_)
224                | TsStmtKind::Raw(..) => None,
225            })
226            .collect()
227    }
228}
229
230#[cfg(test)]
231mod tests {
232    use super::*;
233    use bynk_syntax::span::Span;
234
235    /// `without_export` drops one `export` and nothing else: an exported declaration is its
236    /// inner one, a plain declaration is unchanged, and it keeps its own spacing flag.
237    #[test]
238    fn without_export_unwraps_an_exported_declaration_only() {
239        let function = |name: &str| TsDecl::Function {
240            name: name.to_string(),
241            generics: Vec::new(),
242            params: Vec::new(),
243            return_type: None,
244            body: Vec::new(),
245            is_async: false,
246            inline: false,
247        };
248        let mut exported = TsStmt::decl(TsDecl::Export(Box::new(function("f"))), None);
249        exported.no_blank_before = true;
250        let plain = exported.clone().without_export();
251        assert_eq!(plain.kind, TsStmtKind::Decl(function("f")));
252        assert!(plain.no_blank_before);
253        assert_eq!(
254            plain.clone().without_export().kind,
255            TsStmtKind::Decl(function("f"))
256        );
257    }
258
259    /// Only an `await`, a unary operator, a number literal (`Num` or `Raw`) and a spread need
260    /// a bracket before a member access; every other kind of expression does not.
261    #[test]
262    fn receiver_brackets_are_needed_for_await_unary_number_and_spread_only() {
263        let id = || TsExpr::Ident("a".to_string());
264        for needs in [
265            TsExpr::Await(Box::new(id())),
266            TsExpr::Unary {
267                op: TsUnaryOp::Not,
268                expr: Box::new(id()),
269            },
270            TsExpr::Lit(TsLit::Num("1".to_string())),
271            TsExpr::bigint(1),
272            TsExpr::Lit(TsLit::Raw("0x1".to_string())),
273            TsExpr::Spread(Box::new(id())),
274        ] {
275            assert!(needs.needs_receiver_brackets(), "{needs:?}");
276        }
277        for fine in [
278            id(),
279            TsExpr::Lit(TsLit::Str("s".to_string())),
280            TsExpr::Lit(TsLit::Null),
281            TsExpr::Lit(TsLit::Bool(true)),
282            TsExpr::Paren(Box::new(id())),
283            TsExpr::Member {
284                object: Box::new(id()),
285                property: "p".to_string(),
286            },
287            TsExpr::Call {
288                callee: Box::new(id()),
289                args: vec![],
290            },
291            TsExpr::array(vec![]),
292            TsExpr::object(vec![]),
293        ] {
294            assert!(!fine.needs_receiver_brackets(), "{fine:?}");
295        }
296    }
297
298    /// The tree compares structurally (1A.35b): two separately built, equal trees are equal, a
299    /// difference anywhere inside is not, and a node never equals a different node that prints
300    /// the same text. This is what lets a recursion check compare witnesses without printing.
301    #[test]
302    fn the_tree_compares_structurally() {
303        let call = |callee: &str, arg: TsExpr| TsExpr::Call {
304            callee: Box::new(TsExpr::Ident(callee.to_string())),
305            args: vec![arg],
306        };
307        let num = |n: &str| TsExpr::Lit(TsLit::Num(n.to_string()));
308        assert_eq!(call("f", num("1")), call("f", num("1")));
309        assert_ne!(call("f", num("1")), call("f", num("2")));
310        assert_ne!(call("f", num("1")), call("g", num("1")));
311        // An identifier and a verbatim fragment can print alike and are still different nodes.
312        assert_ne!(
313            TsExpr::Ident("x".to_string()),
314            TsExpr::VerbatimExpr("x".to_string(), VerbatimOrigin::Emit)
315        );
316        // Types, including an array over a union, compare the same way.
317        let list = |t: TsType| TsType::readonly_array(t);
318        assert_eq!(list(TsType::named("A")), list(TsType::named("A")));
319        assert_ne!(list(TsType::named("A")), TsType::array(TsType::named("A")));
320        assert_eq!(
321            TsType::named_with_args("Result", vec![TsType::named("A"), TsType::named("B")]),
322            TsType::named_with_args("Result", vec![TsType::named("A"), TsType::named("B")])
323        );
324        // A statement inside an arrow body is part of the comparison.
325        let arrow = |ret: TsExpr| TsExpr::Arrow {
326            params: Vec::new(),
327            is_async: false,
328            generics: Vec::new(),
329            return_type: None,
330            body: Box::new(TsArrowBody::Block(vec![TsStmt::return_stmt(
331                Some(ret),
332                None,
333            )])),
334        };
335        assert_eq!(arrow(num("1")), arrow(num("1")));
336        assert_ne!(arrow(num("1")), arrow(num("2")));
337    }
338
339    #[test]
340    fn verbatim_carries_its_own_span() {
341        let span = Span::new(3, 8);
342        let stmt = TsStmt::verbatim(VerbatimOrigin::RuntimeUse, "x", Some(span));
343        assert_eq!(stmt.span, Some(span));
344    }
345
346    #[test]
347    fn a_program_prints_its_statements_in_push_order() {
348        // Kept as a construction-order check (not a print check — printer.rs
349        // owns that) since `TsStmtKind` is `pub(crate)` and no longer
350        // exposes a uniform `text()` accessor once non-`Verbatim` kinds
351        // exist; span order is what's left to check at this layer.
352        let mut program = TsProgram::new();
353        program.push(TsStmt::verbatim(VerbatimOrigin::Contracts, "a", None));
354        program.push(TsStmt::verbatim(
355            VerbatimOrigin::Secrets,
356            "b",
357            Some(Span::new(0, 1)),
358        ));
359        assert_eq!(program.stmts[0].span, None);
360        assert_eq!(program.stmts[1].span, Some(Span::new(0, 1)));
361    }
362
363    /// Review of #1326, finding 1: `TsExpr::template_lit`'s own
364    /// `debug_assert_eq!` must actually fire on a malformed tree, not just
365    /// exist as documentation — proves the guard guards, the same "prove
366    /// it" discipline this crate applies to every other invariant.
367    #[test]
368    #[should_panic(expected = "parts.len() must be exprs.len() + 1")]
369    fn template_lit_rejects_a_parts_exprs_count_mismatch() {
370        let _ = TsExpr::template_lit(
371            vec!["a".to_string()],
372            vec![TsExpr::Ident("too_many".to_string())],
373        );
374    }
375
376    /// 1A.36b-2: an import the tree never uses is dropped, entry by entry; what stays keeps its
377    /// order and its `type` prefix, and a namespace goes with its alias.
378    #[test]
379    fn unused_imports_are_pruned_entry_by_entry() {
380        let import = |type_only: bool, names: &[&str], from: &str| {
381            TsStmt::decl(
382                TsDecl::Import {
383                    type_only,
384                    names: names.iter().map(|n| n.to_string()).collect(),
385                    from: from.to_string(),
386                },
387                None,
388            )
389        };
390        let namespace = |alias: &str, from: &str| {
391            TsStmt::decl(
392                TsDecl::ImportNamespace {
393                    type_only: false,
394                    alias: alias.to_string(),
395                    from: from.to_string(),
396                },
397                None,
398            )
399        };
400        let mut program = TsProgram {
401            stmts: vec![
402                import(false, &["Ok", "type Result", "Err", "x as y"], "./r.js"),
403                import(true, &["Unused"], "./u.js"),
404                namespace("used_ns", "./a.js"),
405                namespace("unused_ns", "./b.js"),
406                TsStmt::expr_stmt(
407                    TsExpr::Call {
408                        callee: Box::new(TsExpr::Ident("Ok".to_string())),
409                        args: vec![TsExpr::Ident("y".to_string())],
410                    },
411                    None,
412                ),
413                TsStmt::expr_stmt(
414                    TsExpr::Member {
415                        object: Box::new(TsExpr::Ident("used_ns".to_string())),
416                        property: "f".to_string(),
417                    },
418                    None,
419                ),
420                TsStmt::decl(
421                    TsDecl::ExportNames {
422                        names: vec!["type Result".to_string()],
423                    },
424                    None,
425                ),
426            ],
427        };
428        program.prune_unused_imports();
429        let printed = crate::print(&program, "", "", "").text;
430        assert!(
431            printed.contains("import { Ok, type Result, x as y } from \"./r.js\";"),
432            "{printed}"
433        );
434        assert!(printed.contains("import * as used_ns"), "{printed}");
435        assert!(
436            !printed.contains("Unused") && !printed.contains("unused_ns"),
437            "{printed}"
438        );
439        assert!(!printed.contains("Err"), "{printed}");
440    }
441}