Skip to main content

bynk_ts/
await_scan.rs

1//! Whether an expression awaits (1A.21, #3722, Decision C): the structural form of the
2//! `v.contains("await")` text inspection `Json.encodePlain` made of its lowered argument. It
3//! looks inside nested arrows and object methods too, as the text search did, so an argument that
4//! awaits anywhere is hoisted ahead of the flag it must not run under.
5//!
6//! An [`TsExpr::Ident`] never awaits, even if it spells "await" (`awaiter`, `this.awaited`):
7//! only [`TsExpr::Await`] nodes count. An `Ident` holds an identifier path and nothing else —
8//! 1A.40c retired the text classes, the printer debug-asserts it, and the identifier audit
9//! covers every module the emitter and the test harness build (1B.5e) — so there is no text in
10//! an `Ident` left to search (1A.40 Decision F, landing in whichever of 1A.40c and 1B.5e came
11//! last).
12
13use crate::program::{TsArrowBody, TsExpr, TsObjectEntry, TsStmt, TsStmtKind};
14
15/// Whether `expr` contains an `await`, at any depth. A [`TsExpr::VerbatimExpr`] or
16/// [`TsExpr::RawUsing`] is foreign text, so it is searched as text; an `Ident` is an
17/// identifier path, so it never awaits.
18pub fn expr_contains_await(expr: &TsExpr) -> bool {
19    match expr {
20        TsExpr::Await(_) => true,
21        TsExpr::Lit(_) => false,
22        // An identifier never awaits, even if it spells "await" (`awaiter`, `awaitedValue`).
23        TsExpr::Ident(_) => false,
24        // Foreign text is the other place an `await` can hide outside a node: search it as text (a
25        // false positive only hoists).
26        TsExpr::VerbatimExpr(text, _) | TsExpr::RawUsing(text, _) => text.contains("await"),
27        TsExpr::Member { object, .. } | TsExpr::OptionalMember { object, .. } => {
28            expr_contains_await(object)
29        }
30        TsExpr::TypeApp { callee, .. } => expr_contains_await(callee),
31        TsExpr::Index { object, index } | TsExpr::OptionalIndex { object, index } => {
32            expr_contains_await(object) || expr_contains_await(index)
33        }
34        TsExpr::DefaultIife { default, body, .. } => {
35            expr_contains_await(default) || body.iter().any(stmt_contains_await)
36        }
37        TsExpr::Arrow { body, .. } => match &**body {
38            TsArrowBody::Expr(e) => expr_contains_await(e),
39            TsArrowBody::Block(stmts)
40            | TsArrowBody::Multiline(stmts)
41            | TsArrowBody::Flat(stmts) => stmts.iter().any(stmt_contains_await),
42        },
43        TsExpr::Call { callee, args }
44        | TsExpr::New { callee, args }
45        | TsExpr::OptionalCall { callee, args } => {
46            expr_contains_await(callee) || args.iter().any(expr_contains_await)
47        }
48        TsExpr::Sequence(items) => items.iter().any(expr_contains_await),
49        TsExpr::Function { body, .. } => body.iter().any(stmt_contains_await),
50        TsExpr::Object { entries, .. } => entries.iter().any(|e| match e {
51            TsObjectEntry::Prop { value: v, .. } | TsObjectEntry::Spread(v) => {
52                expr_contains_await(v)
53            }
54            TsObjectEntry::Shorthand(_) => false,
55            TsObjectEntry::Method { body, .. } => body.iter().any(stmt_contains_await),
56        }),
57        TsExpr::Array { items, .. } | TsExpr::LinesArray(items) => {
58            items.iter().any(expr_contains_await)
59        }
60        TsExpr::TemplateLit { exprs, .. } => exprs.iter().any(expr_contains_await),
61        TsExpr::As { expr, .. } | TsExpr::Unary { expr, .. } => expr_contains_await(expr),
62        TsExpr::Paren(e)
63        | TsExpr::Spread(e)
64        | TsExpr::NonNull(e)
65        | TsExpr::AsConst(e)
66        | TsExpr::Yield(e) => expr_contains_await(e),
67        TsExpr::Binary { left, right, .. } => {
68            expr_contains_await(left) || expr_contains_await(right)
69        }
70        TsExpr::Conditional {
71            test,
72            consequent,
73            alternate,
74        }
75        | TsExpr::MultilineConditional {
76            test,
77            consequent,
78            alternate,
79        } => {
80            expr_contains_await(test)
81                || expr_contains_await(consequent)
82                || expr_contains_await(alternate)
83        }
84        TsExpr::Assign { target, value }
85        | TsExpr::AddAssign { target, value }
86        | TsExpr::NullishAssign { target, value } => {
87            expr_contains_await(target) || expr_contains_await(value)
88        }
89    }
90}
91
92/// Whether `stmt` contains an `await` in an expression of its own or of a nested statement.
93fn stmt_contains_await(stmt: &TsStmt) -> bool {
94    match &stmt.kind {
95        TsStmtKind::Const { init, .. } => expr_contains_await(init),
96        TsStmtKind::Let { init, .. } => init.as_ref().is_some_and(expr_contains_await),
97        TsStmtKind::ExprStmt(e) | TsStmtKind::Throw(e) | TsStmtKind::Increment(e) => {
98            expr_contains_await(e)
99        }
100        TsStmtKind::Return(e) => e.as_ref().is_some_and(expr_contains_await),
101        TsStmtKind::If {
102            cond,
103            then_branch,
104            else_branch,
105            ..
106        } => {
107            expr_contains_await(cond)
108                || stmt_contains_await(then_branch)
109                || else_branch.as_deref().is_some_and(stmt_contains_await)
110        }
111        // A `for await` awaits each step, whatever its body does.
112        TsStmtKind::ForOf {
113            iter,
114            body,
115            is_await,
116            ..
117        } => *is_await || expr_contains_await(iter) || stmt_contains_await(body),
118        TsStmtKind::While { cond, body } => expr_contains_await(cond) || stmt_contains_await(body),
119        TsStmtKind::Labelled { body, .. } => stmt_contains_await(body),
120        TsStmtKind::LetList(decls) => decls
121            .iter()
122            .any(|d| d.init.as_ref().is_some_and(expr_contains_await)),
123        TsStmtKind::For {
124            init, test, body, ..
125        } => expr_contains_await(init) || expr_contains_await(test) || stmt_contains_await(body),
126        TsStmtKind::TryCatch {
127            try_block,
128            catch_block,
129            finally_block,
130            ..
131        } => {
132            stmt_contains_await(try_block)
133                || catch_block.as_deref().is_some_and(stmt_contains_await)
134                || finally_block.as_deref().is_some_and(stmt_contains_await)
135        }
136        TsStmtKind::Block(stmts) | TsStmtKind::InlineBlock(stmts) => {
137            stmts.iter().any(stmt_contains_await)
138        }
139        TsStmtKind::Assign { target, value } => {
140            expr_contains_await(target) || expr_contains_await(value)
141        }
142        TsStmtKind::Switch {
143            discriminant,
144            cases,
145        } => {
146            expr_contains_await(discriminant)
147                || cases.iter().any(|c| {
148                    c.labels.iter().any(expr_contains_await)
149                        || c.body.iter().any(stmt_contains_await)
150                })
151        }
152        TsStmtKind::Verbatim { text, .. } | TsStmtKind::Raw(text, _) => text.contains("await"),
153        TsStmtKind::Decl(_)
154        | TsStmtKind::Continue(_)
155        | TsStmtKind::Break(_)
156        | TsStmtKind::Comment(_)
157        | TsStmtKind::DocComment(_)
158        | TsStmtKind::Blank => false,
159    }
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165    use crate::program::{TsBinaryOp, TsLit, TsParam, TsStmt};
166
167    fn id(n: &str) -> TsExpr {
168        TsExpr::Ident(n.to_string())
169    }
170
171    fn awaiting() -> TsExpr {
172        TsExpr::Await(Box::new(TsExpr::Call {
173            callee: Box::new(id("f")),
174            args: vec![],
175        }))
176    }
177
178    #[test]
179    fn a_plain_expression_does_not_await() {
180        let e = TsExpr::Binary {
181            op: TsBinaryOp::Add,
182            left: Box::new(id("a")),
183            right: Box::new(TsExpr::Lit(TsLit::Num("1".to_string()))),
184        };
185        assert!(!expr_contains_await(&e));
186    }
187
188    /// An identifier never awaits, whatever it spells. Foreign text (`VerbatimExpr`,
189    /// `RawUsing`) is still searched as text.
190    #[test]
191    fn only_await_nodes_and_foreign_text_count() {
192        assert!(!expr_contains_await(&id("awaiter")));
193        assert!(!expr_contains_await(&id("this.awaited")));
194        assert!(!expr_contains_await(&id("plain")));
195        assert!(expr_contains_await(&TsExpr::VerbatimExpr(
196            "(await f())".to_string(),
197            crate::program::VerbatimOrigin::Emit
198        )));
199    }
200
201    #[test]
202    fn an_await_is_found_at_any_depth() {
203        let nested = TsExpr::Call {
204            callee: Box::new(id("g")),
205            args: vec![TsExpr::Paren(Box::new(TsExpr::As {
206                expr: Box::new(awaiting()),
207                ty: crate::program::TsType::named("T"),
208            }))],
209        };
210        assert!(expr_contains_await(&awaiting()));
211        assert!(expr_contains_await(&nested));
212    }
213
214    #[test]
215    fn an_await_inside_a_nested_arrow_body_is_found() {
216        let arrow = TsExpr::Arrow {
217            params: vec![TsParam::new("x".to_string(), None)],
218            is_async: true,
219            generics: Vec::new(),
220            return_type: None,
221            body: Box::new(TsArrowBody::Block(vec![TsStmt::return_stmt(
222                Some(awaiting()),
223                None,
224            )])),
225        };
226        assert!(expr_contains_await(&arrow));
227        let quiet = TsExpr::Arrow {
228            params: Vec::new(),
229            is_async: false,
230            generics: Vec::new(),
231            return_type: None,
232            body: Box::new(TsArrowBody::Expr(Box::new(id("x")))),
233        };
234        assert!(!expr_contains_await(&quiet));
235    }
236}