Skip to main content

bynk_check/
emitted_names.rs

1//! #2476: the names the emitter gives Bynk locals in the TypeScript it writes.
2//!
3//! A debugger sees the emitted names, not Bynk's, so a feature that points a
4//! debug session at a Bynk binding (inline values) needs the emitter's mapping.
5//! It lives here, below both the emitter and the language server, so neither
6//! re-derives it: the emitter calls [`ts_ident`] when it declares a binding,
7//! and [`emitted_local_name`] mirrors `Emitter::bind_local_name`'s choice for a
8//! `let`.
9
10use crate::locals::{LocalBinding, LocalKind};
11
12/// The TypeScript spelling of a user identifier in a *binding or reference*
13/// position (params, locals, function names, import names). Bynk identifiers
14/// that are illegal as TS binding names — the JS reserved words plus the
15/// strict-mode/module sets (emitted modules are always strict ESM) — and
16/// names the emitter itself introduces alongside user bindings (`deps`) are
17/// renamed into the generated-name namespace (`__id_<name>`), which the
18/// parser keeps free of user identifiers. Property/field names never pass
19/// through here: reserved words are legal there, and record field names are
20/// wire format.
21pub fn ts_ident(name: &str) -> String {
22    const RESERVED: &[&str] = &[
23        // ES reserved words.
24        "break",
25        "case",
26        "catch",
27        "class",
28        "const",
29        "continue",
30        "debugger",
31        "default",
32        "delete",
33        "do",
34        "else",
35        "enum",
36        "export",
37        "extends",
38        "false",
39        "finally",
40        "for",
41        "function",
42        "if",
43        "import",
44        "in",
45        "instanceof",
46        "new",
47        "null",
48        "return",
49        "super",
50        "switch",
51        "this",
52        "throw",
53        "true",
54        "try",
55        "typeof",
56        "var",
57        "void",
58        "while",
59        "with",
60        // Strict-mode reserved (emitted modules are always strict).
61        "implements",
62        "interface",
63        "let",
64        "package",
65        "private",
66        "protected",
67        "public",
68        "static",
69        "yield",
70        // Module-code reserved.
71        "await",
72        // Illegal binding targets in strict mode.
73        "arguments",
74        "eval",
75        // #1653: the emitted code reaches host globals through `globalThis`
76        // (`globalThis.JSON`), so no user binding may take that name.
77        "globalThis",
78        // Generated identifiers a user binding may sit next to: handler
79        // signatures append a `deps` parameter, so a user param named `deps`
80        // would otherwise duplicate it.
81        "deps",
82    ];
83    if RESERVED.contains(&name) {
84        format!("__id_{name}")
85    } else {
86        name.to_string()
87    }
88}
89
90/// The JS identifier the emitter declares for `binding`, or `None` when it
91/// cannot be known from the source alone.
92///
93/// A parameter or pattern binder is always its [`ts_ident`] name. A `let` is
94/// too, unless the name is already bound in an enclosing scope (a re-`let`):
95/// the emitter then declares a throwaway `__r<N>`, numbered by a counter that
96/// runs across the whole emitted body, so there is no name to look up and a
97/// guess would show another variable's value.
98pub fn emitted_local_name(binding: &LocalBinding, locals: &[LocalBinding]) -> Option<String> {
99    if binding.kind == LocalKind::Let && binding.name == "_" {
100        return None; // always a fresh throwaway, and never read
101    }
102    if binding.kind == LocalKind::Let
103        && locals.iter().any(|b| {
104            b.name == binding.name
105                && b.def_span.start < binding.def_span.start
106                && b.scope.start <= binding.def_span.start
107                && binding.def_span.start <= b.scope.end
108        })
109    {
110        return None;
111    }
112    Some(ts_ident(&binding.name))
113}
114
115#[cfg(test)]
116mod tests {
117    use super::*;
118    use bynk_syntax::span::Span;
119
120    fn binding(name: &str, def: usize, kind: LocalKind, scope: (usize, usize)) -> LocalBinding {
121        LocalBinding {
122            name: name.into(),
123            def_span: Span::new(def, def + name.len()),
124            kind,
125            ty: "Int".into(),
126            scope: Span::new(scope.0, scope.1),
127        }
128    }
129
130    #[test]
131    fn reserved_words_are_renamed_and_others_kept() {
132        assert_eq!(ts_ident("class"), "__id_class");
133        assert_eq!(ts_ident("deps"), "__id_deps");
134        assert_eq!(ts_ident("total"), "total");
135    }
136
137    #[test]
138    fn a_plain_let_and_a_param_keep_their_names() {
139        let locals = vec![
140            binding("n", 5, LocalKind::Param, (20, 60)),
141            binding("class", 26, LocalKind::Let, (34, 60)),
142        ];
143        assert_eq!(
144            emitted_local_name(&locals[0], &locals).as_deref(),
145            Some("n")
146        );
147        assert_eq!(
148            emitted_local_name(&locals[1], &locals).as_deref(),
149            Some("__id_class")
150        );
151    }
152
153    #[test]
154    fn a_re_let_has_no_knowable_name_but_the_first_binding_does() {
155        let locals = vec![
156            binding("x", 26, LocalKind::Let, (34, 90)),
157            binding("x", 40, LocalKind::Let, (48, 90)),
158        ];
159        assert_eq!(
160            emitted_local_name(&locals[0], &locals).as_deref(),
161            Some("x")
162        );
163        assert_eq!(emitted_local_name(&locals[1], &locals), None);
164    }
165
166    #[test]
167    fn a_let_shadowing_a_param_is_renamed_by_the_emitter() {
168        let locals = vec![
169            binding("n", 5, LocalKind::Param, (20, 60)),
170            binding("n", 26, LocalKind::Let, (34, 60)),
171        ];
172        assert_eq!(
173            emitted_local_name(&locals[0], &locals).as_deref(),
174            Some("n")
175        );
176        assert_eq!(emitted_local_name(&locals[1], &locals), None);
177    }
178
179    #[test]
180    fn sibling_scopes_do_not_shadow_each_other() {
181        let locals = vec![
182            binding("x", 26, LocalKind::Let, (34, 50)),
183            binding("x", 60, LocalKind::Let, (68, 90)),
184        ];
185        assert_eq!(
186            emitted_local_name(&locals[1], &locals).as_deref(),
187            Some("x")
188        );
189    }
190
191    #[test]
192    fn a_discarded_let_has_no_name() {
193        let locals = vec![binding("_", 26, LocalKind::Let, (34, 50))];
194        assert_eq!(emitted_local_name(&locals[0], &locals), None);
195    }
196}