hermes-sema 0.1.2

A Rust port of the Hermes semantic analysis (scope resolution and validation) pass by Tzvetan Mikov, the architect of Hermes. Not an official Meta project.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

//! Port of `hermes::sema::ASTPrinter` and the untyped arm of `semDump`
//! (`lib/Sema/SemResolve.cpp:20-161,258-297`). Byte-exact text dumper (the
//! `-dump-sema` AST half, paired with [`crate::dump_context`]'s
//! `SemContextDumper` for the `SemContext` half) that the differential
//! oracle depends on — every space, quote, and (see below) quirk is
//! transcribed straight from the C++ `<<` chain it replaces.
//!
//! **Stability: advanced / port-internal.** This module exists to serve the
//! differential harness: its output is compared byte-for-byte against
//! `hermesc -dump-sema`, and its shape is therefore dictated by the C++
//! printer rather than chosen for consumers. The stable spelling of "give me
//! the dump" is [`crate::ResolvedJS::to_sema_dump`]. This module is `pub`
//! because `tools`' `sema-dump` bin and the differential test drive it
//! directly, and it may change, or be demoted to `pub(crate)`, in a 0.x
//! release. See the crate doc for the stable surface.
//!
//! ## `ESTreeVisit` mapping
//!
//! C++ dispatches through the `ESTreeVisit`/`Node::visit` protocol: each
//! concrete node's macro-generated `visit(Visitor&)` calls
//! `V.shouldVisit(this)` (skip entirely if false), `V.enter(this)`,
//! `ESTreeVisit(V, child)` for each child field in `.def` order, then
//! `V.leave(this)` — with `enter`/`leave`/`shouldVisit` overloadable per
//! concrete node type (`BinaryExpressionNode`, `IdentifierNode`,
//! `TypeAnnotationNode`) and falling back to the generic `Node*` overload
//! otherwise.
//!
//! `hermes_ast::Visitor` (`rust/crates/ast/src/visitor.rs`) is far thinner: one
//! method, `visit_node(&mut self, node)`, whose default body just recurses
//! via `node.visit_children(self)` — no `shouldVisit`/`enter`/`leave` split
//! and no per-node-kind override point. Rather than force that shape to
//! fit (which would mean re-deriving the split manually at every call site
//! anyway), `AstPrinter` implements `Visitor` with a `visit_node` that
//! reconstructs the same three-step protocol directly:
//!
//! ```text
//! fn visit_node(node):
//!     if !should_visit(node): return   // shouldVisit
//!     enter(node)                      // enter — dispatches on node kind
//!     node.visit_children(self)        // ESTreeVisit(V, child) for each child
//!     leave(node)                      // leave
//! ```
//!
//! `node.visit_children` (generated per `.def` entry, `hermes_ast::node`) is
//! exactly the C++ macro's per-node child-field enumeration, so reusing it
//! here reproduces the same traversal order for every node kind for free.
//! `enter`/`leave` internally match on node kind to reach the
//! `BinaryExpression`/`Identifier` special cases, mirroring the C++
//! overload set.
//!
//! ## The `BinaryExpression` `+`/`-` linearization and its `BinOp` quirk
//!
//! `enter(BinaryExpressionNode*)` (cpp:70-95) prints the node itself, then
//! — for `+`/`-` only — flattens the left-recursive chain via
//! `linearizeLeft` and walks it iteratively instead of recursing normally,
//! setting `parentLinearized_ = true` right before returning. Because the
//! macro-generated `visit()` *unconditionally* calls `ESTreeVisit(V,
//! _left)`/`ESTreeVisit(V, _right)` right after `enter()` returns, that
//! flag is what suppresses the would-be duplicate re-visit of the two
//! children already handled manually inside `enter()`; `leave()` resets it
//! so an outer (non-linearized) `BinaryExpression` isn't affected.
//!
//! The Rust port reconstructs this exactly: `enter_binary_expression`
//! performs the manual traversal (via recursive `self.visit_node` calls,
//! matching `->visit(*this)`) and sets `self.parent_linearized = true`;
//! back in `visit_node`, `node.visit_children(self)` then tries to visit
//! `left`/`right` again but `should_visit` returns `false` (mirroring the
//! generic `shouldVisit(Node*) { return !parentLinearized_; }` override),
//! so both calls are no-ops; `leave` unconditionally resets the flag to
//! `false` for every `BinaryExpression`, linearized or not (matching
//! `leave(BinaryExpressionNode*)`, cpp:133-137).
//!
//! **Quirk, reproduced on purpose:** inside the loop that prints each
//! `BinOp` line (cpp:79-84), the C++ prints `list[0]->_operator->str()`
//! *every iteration* — not `e->_operator`. For a mixed chain like
//! `1 + 2 - 3` (`list[0]` is the `+` node, `list[1]` is the `-` node),
//! this means **both** `BinOp` lines print `+`, never `-`. This looks like
//! an oversight in the C++ (probably meant `e->_operator`), but the
//! differential oracle compares byte-for-byte against real `hermesc`
//! output, so it is reproduced verbatim here rather than "fixed" — see
//! `enter_binary_expression` and the `linearized_binary_1_plus_2_minus_3`
//! test, which locks this in.
//!
//! ## `getExpressionDecl` on an unresolvable identifier
//!
//! `enter(IdentifierNode*)` (cpp:101-102) used to call `getExpressionDecl`
//! unconditionally, right after `getDeclarationDecl` — even when the
//! identifier `isUnresolvable()`. C++'s `getExpressionDecl` has
//! `assert(!node->isUnresolvable())` (SemContext.h:559-561), which is
//! compiled out in `NDEBUG`/Release builds; in that configuration the call
//! was harmless, because the *only* call site that ever marks an identifier
//! unresolvable (`Unresolver::visit`, `SemanticResolver.cpp:3222-3236`)
//! always clears the "have expression decl" bit first via
//! `setExpressionDecl(node, nullptr)` — so `getExpressionDecl` would
//! return `nullptr` there regardless of the assert. A debug C++ build,
//! however, aborted; the shape is reachable only through
//! `resolveASTForParser` (identifiers inside `with` — `with` is a
//! `compile_`-gated error on the driver path).
//!
//! This port's `SemContext::get_expression_decl` (`sem_context.rs`) uses
//! `assert!`, which Rust never compiles out, so `enter_identifier` below
//! checks `unresolvable` first and substitutes `None` — reproducing the
//! *value* a Release C++ build produces. That used to be a documented
//! divergence from a debug C++ build (which aborted); it is one no longer.
//! Upstream `918158cb0` made the C++ dumper guard the call the same way
//! (`sema::Decl *exprD = V->isUnresolvable() ? nullptr :
//! semCtx_.getExpressionDecl(V);`, `SemResolve.cpp:99-110`), so debug now
//! matches release upstream and both match this port: `with(o){x;}` dumps
//! `Id 'x' UNR` on every side, in every build configuration. It is a live
//! differential corpus file — `sema_corpus_parser/parser-mode-with-statement.js`.
//!
//! ## `should_visit` and `TypeAnnotation`
//!
//! `shouldVisit(TypeAnnotationNode*) { return false; }` (cpp:52, Flow-only
//! in C++) unconditionally skips the Flow type-annotation wrapper node —
//! not just hiding its print, but (per the macro above) also skipping
//! entirely into its subtree. Ported unconditionally here (no `#if
//! HERMES_PARSE_FLOW`-equivalent gate — this crate doesn't split builds by
//! dialect) since it doesn't matter for untyped ASTs and matters once
//! Flow/TS corpora are dumped.

use hermes_ast::context::GCLock;
use hermes_ast::node::{BinaryExpression, Identifier, Node};
use hermes_ast::visitor::Visitor;
use hermes_ast::SemaId;

use crate::dump_context::{push_atom, push_indent, push_str, SemContextDumper};
use crate::ids::{FunctionInfoId, ScopeId};
use crate::linearize::linearize_left;
use crate::sem_context::SemContext;

/// Port of `hermes::sema::semDump`'s untyped arm (`SemResolve.cpp:258-274`).
/// The typed/`FlowContext` arm (cpp:275-296) is deferred to the
/// FlowChecker component, per the task brief — this crate has no
/// `FlowContext` yet.
///
/// Prints `printSemContext(root_func)` + `'\n'` + an `ASTPrinter` run over
/// `root` (which itself ends with a trailing `'\n'`, cpp:48).
pub fn sem_dump<'n, 'ast, 'ctx>(
    out: &mut Vec<u8>,
    gc: &GCLock<'ast, 'ctx>,
    sem_ctx: &SemContext,
    root: &'n Node<'n>,
) {
    // "If the root is a function-like node, start the dump from its
    // FunctionInfo." (cpp:264-267)
    let root_func =
        function_like_sem_info(root).map(FunctionInfoId::from_sema_id);

    let mut sem_dumper = SemContextDumper::new();
    sem_dumper.print_sem_context(out, gc, sem_ctx, root_func);
    out.push(b'\n');

    let mut printer = AstPrinter {
        out,
        gc,
        sem_ctx,
        sem_dumper: &mut sem_dumper,
        depth: 0,
        parent_linearized: false,
    };
    printer.run(root);
}

/// Port of `hermes::sema::ASTPrinter` (`SemResolve.cpp:20-161`), untyped
/// arm only (no `flowDumper_`/`flowContext_` — see the module doc). See
/// the module doc for how this maps onto the C++ `ESTreeVisit`
/// `shouldVisit`/`enter`/`leave` protocol.
struct AstPrinter<'p, 'ast, 'ctx> {
    out: &'p mut Vec<u8>,
    gc: &'p GCLock<'ast, 'ctx>,
    sem_ctx: &'p SemContext,
    sem_dumper: &'p mut SemContextDumper,
    /// Port of `depth_` (cpp:26).
    depth: u32,
    /// Port of `parentLinearized_` (cpp:31) — see the module doc's
    /// linearization section.
    parent_linearized: bool,
}

impl<'p, 'ast, 'ctx> AstPrinter<'p, 'ast, 'ctx> {
    /// Port of `ASTPrinter::run` (cpp:46-49).
    fn run<'n>(&mut self, root: &'n Node<'n>) {
        self.visit_node(root);
        self.out.push(b'\n');
    }

    /// Port of the two `shouldVisit` overloads (cpp:52-60): the
    /// Flow-`TypeAnnotationNode`-specific one (always `false`) and the
    /// generic `Node*` one (`!parentLinearized_`).
    fn should_visit(&self, node: &Node) -> bool {
        if matches!(node, Node::TypeAnnotation(_)) {
            return false;
        }
        !self.parent_linearized
    }

    /// Dispatches to the `enter` overload matching `node`'s kind, mirroring
    /// C++ overload resolution on `enter(BinaryExpressionNode*)`,
    /// `enter(IdentifierNode*)`, and the generic `enter(Node*)` fallback
    /// (cpp:62-129).
    fn enter<'n>(&mut self, node: &'n Node<'n>) {
        match node {
            Node::BinaryExpression(bin) => {
                self.enter_binary_expression(node, bin)
            }
            Node::Identifier(ident) => self.enter_identifier(ident),
            _ => self.enter_generic(node),
        }
    }

    /// Port of the generic `enter(ESTree::Node *V)` (cpp:62-69): indent,
    /// node name, scope ref, newline. Also the first half of
    /// `enter(BinaryExpressionNode*)` (cpp:71-72), which explicitly calls
    /// this before its own special-casing.
    fn enter_generic(&mut self, node: &Node) {
        self.depth += 1;
        push_indent(self.out, self.depth - 1);
        push_str(self.out, node.node_type_str());
        self.print_scope_ref(node);
        self.out.push(b'\n');
    }

    /// Port of `printScopeRef` (cpp:140-147).
    fn print_scope_ref(&mut self, node: &Node) {
        if let Some(scope) = node_scope(node) {
            self.out.push(b' ');
            self.sem_dumper
                .print_scope_ref(self.out, ScopeId::from_sema_id(scope));
        }
    }

    /// Port of `enter(ESTree::BinaryExpressionNode *V)` (cpp:70-95). See
    /// the module doc for the linearization protocol and the `BinOp`
    /// quirk this deliberately reproduces.
    fn enter_binary_expression<'n>(
        &mut self,
        node: &'n Node<'n>,
        bin: &'n BinaryExpression<'n>,
    ) {
        // "Still print the BinaryExpressionNode itself." (cpp:71-72)
        self.enter_generic(node);

        let op = bin.operator.get();
        let ops = [self.sem_ctx.kw.ident_plus, self.sem_ctx.kw.ident_minus];
        if op == ops[0] || op == ops[1] {
            // cpp:76 — `linearizeLeft(V, {"+", "-"})`.
            let list = linearize_left(bin, &ops);

            self.visit_node(list[0].left);
            for e in &list {
                push_indent(self.out, self.depth);
                push_str(self.out, "BinOp ");
                // NOT `e.operator`: cpp:82 prints `list[0]->_operator`
                // unconditionally on every iteration — see the module
                // doc's "BinOp quirk" section.
                push_atom(self.out, self.gc, list[0].operator.get());
                self.out.push(b'\n');
                self.visit_node(e.right);
            }

            // Suppresses the re-visit `node.visit_children` is about to
            // attempt on `bin.left`/`bin.right` (both already handled
            // above); `leave` resets this. See the module doc.
            self.parent_linearized = true;
        }
    }

    /// Port of `enter(ESTree::IdentifierNode *V)` (cpp:96-129).
    fn enter_identifier(&mut self, ident: &Identifier) {
        self.depth += 1;
        push_indent(self.out, self.depth - 1);
        push_str(self.out, "Id '");
        push_atom(self.out, self.gc, ident.name.get());
        self.out.push(b'\'');

        let decl_d = self.sem_ctx.get_declaration_decl(ident);
        // Guarding on `unresolvable` matches cpp:99-110 since upstream
        // `918158cb0`; see the module doc's "getExpressionDecl on an
        // unresolvable identifier" section.
        let expr_d = if ident.unresolvable.get() {
            None
        } else {
            self.sem_ctx.get_expression_decl(ident)
        };

        if decl_d.is_some() || expr_d.is_some() {
            push_str(self.out, " [");
            // Matches the C++ if/else-if/else (cpp:107-122) branch by
            // branch, via exhaustive destructuring instead of
            // `Option::unwrap`/`expect` (an earlier version used those and
            // clippy correctly couldn't prove them sound from a separate
            // `if decl_d.is_none() || ...` check higher up).
            match (decl_d, expr_d) {
                // "!declD" half of cpp:109.
                (None, Some(e)) => {
                    push_str(self.out, "D:E:");
                    self.sem_dumper.print_decl_ref(
                        self.out, self.gc, self.sem_ctx, e, true,
                    );
                }
                // "declD == exprD" half of cpp:109.
                (Some(d), Some(e)) if d == e => {
                    push_str(self.out, "D:E:");
                    self.sem_dumper.print_decl_ref(
                        self.out, self.gc, self.sem_ctx, e, true,
                    );
                }
                // cpp:112-116: declD and exprD both present and distinct.
                (Some(d), Some(e)) => {
                    push_str(self.out, "D:");
                    self.sem_dumper.print_decl_ref(
                        self.out, self.gc, self.sem_ctx, d, false,
                    );
                    push_str(self.out, " E:");
                    self.sem_dumper.print_decl_ref(
                        self.out, self.gc, self.sem_ctx, e, true,
                    );
                }
                // cpp:117-122: "the only remaining case", declD && !exprD.
                (Some(d), None) => {
                    push_str(self.out, "D:");
                    self.sem_dumper.print_decl_ref(
                        self.out, self.gc, self.sem_ctx, d, true,
                    );
                }
                (None, None) => {
                    unreachable!("guarded by the `if` above")
                }
            }
            self.out.push(b']');
        }
        if ident.unresolvable.get() {
            push_str(self.out, " UNR");
        }
        self.out.push(b'\n');
    }

    /// Port of the generic `leave(ESTree::Node *V)` (cpp:130-132) plus
    /// `leave(ESTree::BinaryExpressionNode *V)`'s extra flag reset
    /// (cpp:133-137).
    fn leave(&mut self, node: &Node) {
        self.depth -= 1;
        if matches!(node, Node::BinaryExpression(_)) {
            self.parent_linearized = false;
        }
    }
}

impl<'gc, 'p, 'ast, 'ctx> Visitor<'gc> for AstPrinter<'p, 'ast, 'ctx> {
    /// Reconstructs the C++ `shouldVisit`/`enter`/(children)/`leave`
    /// protocol — see the module doc.
    fn visit_node(&mut self, node: &'gc Node<'gc>) {
        if !self.should_visit(node) {
            return;
        }
        self.enter(node);
        node.visit_children(self);
        self.leave(node);
    }
}

/// The `FunctionInfo` a function-like `root`'s `sem_info` decoration points
/// at, or `None` if `root` isn't function-like. Port of the
/// `llvh::dyn_cast<ESTree::FunctionLikeNode>(root)` + `getSemInfo()` guard
/// at the top of `semDump` (cpp:265-267); enumerates the 6 node kinds that
/// carry a `sem_info` Cell (`rust/crates/ast/src/node.rs`; grep
/// `sem_info: Cell<Option<SemaId>>` — `Program` counts, since
/// `ESTREE_NODE_1_ARGS(Program, FunctionLike, ...)` makes it a
/// `FunctionLikeNode` in C++ too).
fn function_like_sem_info(node: &Node) -> Option<SemaId> {
    match node {
        Node::Program(n) => n.sem_info.get(),
        Node::FunctionExpression(n) => n.sem_info.get(),
        Node::ArrowFunctionExpression(n) => n.sem_info.get(),
        Node::FunctionDeclaration(n) => n.sem_info.get(),
        Node::ComponentDeclaration(n) => n.sem_info.get(),
        Node::HookDeclaration(n) => n.sem_info.get(),
        _ => None,
    }
}

/// The scope a scope-bearing node decorates, if any. Port of
/// `ESTree::getDecoration<ScopeDecorationBase>(n)` + `getScope()`
/// (cpp:140-146): enumerates the 15 node kinds that carry a `scope` Cell
/// (`rust/crates/ast/src/node.rs`; grep `scope: Cell<Option<SemaId>>`).
fn node_scope(node: &Node) -> Option<SemaId> {
    match node {
        Node::Program(n) => n.scope.get(),
        Node::FunctionExpression(n) => n.scope.get(),
        Node::ArrowFunctionExpression(n) => n.scope.get(),
        Node::FunctionDeclaration(n) => n.scope.get(),
        Node::ComponentDeclaration(n) => n.scope.get(),
        Node::HookDeclaration(n) => n.scope.get(),
        Node::ForInStatement(n) => n.scope.get(),
        Node::ForOfStatement(n) => n.scope.get(),
        Node::ForStatement(n) => n.scope.get(),
        Node::BlockStatement(n) => n.scope.get(),
        Node::StaticBlock(n) => n.scope.get(),
        Node::SwitchStatement(n) => n.scope.get(),
        Node::CatchClause(n) => n.scope.get(),
        Node::ClassDeclaration(n) => n.scope.get(),
        Node::ClassExpression(n) => n.scope.get(),
        _ => None,
    }
}