1mod 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#[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 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 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 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 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 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 #[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 #[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 #[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 assert_ne!(
313 TsExpr::Ident("x".to_string()),
314 TsExpr::VerbatimExpr("x".to_string(), VerbatimOrigin::Emit)
315 );
316 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 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 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 #[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 #[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}