viperjs 0.3.0

An embeddable JavaScript engine in safe Rust, with zero runtime dependencies.
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
//! The two early errors a statement list has about the names it declares (§14.2.1, §16.1.1).
//!
//! Both rules are stated identically for a `Block` and for a `Script`, and both are about the
//! lists [`crate::static_semantics`] computes:
//!
//! 1. The `LexicallyDeclaredNames` may not contain duplicates — `{ let a; let a; }`.
//! 2. None of them may also occur in the `VarDeclaredNames` — `{ let a; var a; }`.
//!
//! # Why the second rule needs a walk and the first does not
//!
//! Because `var` hoists out of the block it was written in and `let` does not. `{ let a; { let a;
//! } }` is two names in two scopes and is fine; `{ let a; { var a; } }` is two names in one scope
//! and is not, and nothing at the outer level looks like a redeclaration until you go and find
//! the `var`. That is the whole reason the second rule cannot be checked by looking at the list
//! in front of you.
//!
//! # Why a `Script` no longer shares this with a `Block`
//!
//! Both of the things this file once said it could not catch turn on a `HoistableDeclaration`, and
//! both are here now:
//!
//! §8.2.10 and §8.2.12's **`TopLevel` variants** are a different answer rather than a refinement: a
//! function declaration at a script's top level is a *var* name and not a lexical one, so
//! `var a; function a() {}` is legal there and `{ var a; function a() {} }` is not.
//! [`check_declared_names`] takes a [`Level`] and asks the pair that level names.
//!
//! §14.2.1's carve-out under **Web Legacy Compatibility Semantics** is §B.3.3.5, and it belongs to
//! a `Block` alone — a top level needs none, because the clause above already left a
//! `HoistableDeclaration` out of the lexical list. It exempts one shape from rule 1: two
//! `FunctionDeclaration`s of a name in the same `StatementList` of **sloppy** code. So
//! `{ function f() {} function f() {} }` parses, `'use strict';` in front of it does not, and
//! §B.3.3.5 states the same over a `CaseBlock` — a `switch` with one in two cases parses too. It is
//! the only rule here that asks whether the code is strict, and a module (§11.2.2) is never exempt.

use super::export::{exported_bindings, exported_names};
use super::{ParseError, ParseErrorKind};
use crate::ast::{
    BindingName, Declaration, ImportClause, ImportDeclaration, ImportSpecifier, ModuleExportName,
    ModuleItem, Stmt, SwitchCase,
};
use crate::span::Span;
use crate::static_semantics::{
    DeclaredName, LabelProblemKind, bound_names, first_label_problem, function_declared_names,
    lexically_declared_names, top_level_lexically_declared_names, top_level_var_declared_names,
    var_declared_names,
};
use std::collections::{HashMap, HashSet};

/// Apply both rules to a completed statement list, whether a `Block`'s or a `Script`'s.
///
/// Called once per list rather than maintained as the parser goes — DR-0007 — so it runs on a
/// finished tree and can be read straight against §14.2.1. A free function rather than a method
/// on the parser because it needs nothing the parser knows: the tree is the whole input, which is
/// the point of computing early errors this way.
pub(super) fn check_declared_names(body: &[Stmt], level: Level) -> Result<(), ParseError> {
    match level {
        Level::Block { strict } => {
            let lexical = lexically_declared_names(body);
            let repeatable =
                functions_that_may_repeat(&lexical, function_declared_names(body), strict);
            check(lexical, var_declared_names(body), &repeatable)
        }
        // A top level needs no carve-out. §8.2.10 leaves a `HoistableDeclaration` out of
        // `TopLevelLexicallyDeclaredNames` altogether, so two functions of one name were never a
        // duplicate there — which is the same fact §B.3.3.5 is restoring for a block.
        Level::Top => check(
            top_level_lexically_declared_names(body),
            top_level_var_declared_names(body),
            &HashSet::new(),
        ),
    }
}

/// §B.3.3.5's carve-out, as the set of names it exempts from rule 1.
///
/// "It is a Syntax Error if the LexicallyDeclaredNames of StatementList contains any duplicate
/// entries, **unless the source text matched by this production is not strict mode code and the
/// duplicate entries are only bound by FunctionDeclarations**." So a name is exempt when every
/// lexical binding of it here is a function: `{ function a() {} function a() {} }` is ordinary
/// sloppy code, and `{ let a; function a() {} }` is still the Syntax Error §14.2.1 makes it.
///
/// Counted rather than tested for membership, which is what makes the "only" in that sentence
/// load-bearing — a name with one function binding and one `let` is in both lists and is not exempt.
fn functions_that_may_repeat<'a>(
    lexical: &[DeclaredName<'a>],
    functions: Vec<DeclaredName<'a>>,
    strict: bool,
) -> HashSet<&'a str> {
    // Conditioned on sloppiness and on nothing else — DR-0008's amendment, and the same condition
    // §B.3.2 and §B.3.4 carry.
    if strict {
        return HashSet::new();
    }
    let mut lexical_count: HashMap<&str, usize> = HashMap::new();
    for declared in lexical {
        *lexical_count.entry(declared.name).or_default() += 1;
    }
    let mut function_count: HashMap<&str, usize> = HashMap::new();
    for declared in functions {
        *function_count.entry(declared.name).or_default() += 1;
    }
    function_count
        .into_iter()
        .filter(|(name, count)| lexical_count.get(name) == Some(count))
        .map(|(name, _)| name)
        .collect()
}

/// Which of §8.2's two readings of a `StatementList` applies.
///
/// The rules are the same; the lists are not. A function declaration is var-scoped at a top level
/// and lexically scoped in a block, so `function f() {} function f() {}` is fine at the top of a
/// script and `{ let f; function f() {} }` is a redeclaration. Everything else reads alike.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Level {
    /// A `Block` (§14.2.1) or a `CaseBlock` (§14.12.1).
    ///
    /// `strict` is whether the block is strict code, which §B.3.3.5 is the only rule here to ask
    /// about. It rides on this variant rather than beside the level because at a top level the
    /// answer decides nothing — a function is not lexically declared there at all — and a
    /// parameter that is read in one case and ignored in the other is a parameter a caller can get
    /// wrong without a test noticing.
    Block {
        /// Whether §11.2.2's strict mode is in force for the list being checked.
        strict: bool,
    },
    /// A `Script` body (§16.1.1) or a `FunctionStatementList` (§15.2.1).
    Top,
}

/// The same two rules over a `CaseBlock` (§14.12.1).
///
/// The clauses are not scopes — the `CaseBlock` is the scope — so §8.2.6 and §8.2.8 both define
/// their lists over it as the concatenation across every clause. Doing exactly that is what makes
/// `case 1: let a; case 2: let a;` a redeclaration, and it is why this is a second caller of the
/// same rules rather than a second rule.
pub(super) fn check_case_block_declared_names(
    cases: &[SwitchCase],
    strict: bool,
) -> Result<(), ParseError> {
    let lexical: Vec<DeclaredName<'_>> = cases
        .iter()
        .flat_map(|case| lexically_declared_names(&case.body))
        .collect();
    // §B.3.3.5 states the same carve-out over a `CaseBlock`, and over the same concatenation: two
    // `case` clauses each declaring `function f` are two entries in one list, and both are bound by
    // functions, so both are exempt. Concatenated first for that reason — asked one clause at a
    // time, neither would see the other's binding and neither would be exempt.
    let repeatable = functions_that_may_repeat(
        &lexical,
        cases
            .iter()
            .flat_map(|case| function_declared_names(&case.body))
            .collect(),
        strict,
    );
    check(
        lexical,
        cases
            .iter()
            .flat_map(|case| var_declared_names(&case.body))
            .collect(),
        &repeatable,
    )
}

/// §16.2.1.1's two declared-name rules, asked of a finished `ModuleItemList`.
///
/// The same two rules §16.1.1 asks of a `Script`, over a list that reads differently in two ways:
///
/// - The `LexicallyDeclaredNames` are the *non*-`TopLevel` ones, so a function declared at the top
///   of a module is lexically scoped. That single difference is why
///   `function f() {} function f() {}` is a redeclaration in a module and ordinary in a script.
/// - An `ImportDeclaration` declares names too, and lexically — §8.2.6 gives `ModuleItem :
///   ImportDeclaration` the `BoundNames` of the declaration. So `import a from "b"; var a;`
///   collides exactly as `let a; var a;` would.
pub(super) fn check_module_declared_names(body: &[ModuleItem]) -> Result<(), ParseError> {
    let statements: Vec<Stmt> = body
        .iter()
        .filter_map(super::module::module_statement)
        .collect();
    let mut lexical = lexically_declared_names(&statements);
    for item in body {
        let ModuleItem::Import(declaration) = item else {
            continue;
        };
        for name in imported_names(declaration) {
            lexical.push(name);
        }
    }
    // Source order, which `check` relies on to put the caret on the redeclaration rather than on
    // the declaration it collided with. The imports were appended after the statements, so the
    // list has to be put back in the order the file was written.
    lexical.sort_by_key(|declared| declared.span.start);
    // A module is strict code (§11.2.2), so §B.3.3.5 exempts nothing here.
    check(lexical, var_declared_names(&statements), &HashSet::new())
}

/// The `BoundNames` of an `ImportDeclaration` (§8.2.1).
///
/// Every shape of `ImportClause` binds its locals and nothing else — a `ModuleExportName` names
/// something in the *other* module and is not a binding here, which is why
/// `import {a as b, a as c} from "d"` binds two names and not one.
fn imported_names(declaration: &ImportDeclaration) -> Vec<DeclaredName<'_>> {
    let (singles, specifiers): (&[&BindingName], &[ImportSpecifier]) = match &declaration.clause {
        None => (&[], &[]),
        Some(ImportClause::Default(name) | ImportClause::Namespace(name)) => (&[name], &[]),
        Some(ImportClause::Named(specifiers)) => (&[], specifiers),
        Some(ImportClause::DefaultAndNamespace(default, namespace)) => (&[default, namespace], &[]),
        Some(ImportClause::DefaultAndNamed(default, specifiers)) => (&[default], specifiers),
    };
    singles
        .iter()
        .copied()
        .chain(specifiers.iter().map(|specifier| &specifier.local))
        .map(|name| DeclaredName {
            name: &name.name,
            span: name.span,
        })
        .collect()
}

/// §16.2.1.1's two export rules, asked of a finished `ModuleItemList`.
///
/// One about each side of an export. The exported names may not repeat — two modules asking for
/// the same name would get two different things — and every local name an export mentions must be
/// declared somewhere in the module. Both wait for the whole list, because `export {a}; var a;` is
/// ordinary code.
pub(super) fn check_exports(body: &[ModuleItem]) -> Result<(), ParseError> {
    let mut seen: HashSet<Vec<u16>> = HashSet::new();
    for item in body {
        let ModuleItem::Export(declaration) = item else {
            continue;
        };
        for (name, span) in exported_names(declaration) {
            if !seen.insert(name) {
                return Err(ParseError {
                    kind: ParseErrorKind::DuplicateExportedName,
                    span,
                });
            }
        }
    }
    // The declared names, which is every name this module binds by any means — the same two lists
    // the rules above are stated over, plus the imports.
    let statements: Vec<Stmt> = body
        .iter()
        .filter_map(super::module::module_statement)
        .collect();
    let mut declared: HashSet<&str> = HashSet::new();
    for name in lexically_declared_names(&statements)
        .iter()
        .chain(var_declared_names(&statements).iter())
    {
        declared.insert(name.name);
    }
    for item in body {
        if let ModuleItem::Import(declaration) = item {
            for name in imported_names(declaration) {
                declared.insert(name.name);
            }
        }
    }
    for item in body {
        let ModuleItem::Export(declaration) = item else {
            continue;
        };
        for local in exported_bindings(declaration) {
            // A string is never a local name, whatever it spells: `export {"a"}` has nothing it
            // could be referring to, where `export {"a"} from "b"` names the other module's.
            let ModuleExportName::Identifier(name) = local else {
                return Err(ParseError {
                    kind: ParseErrorKind::UndeclaredExportedName,
                    span: declaration.span,
                });
            };
            if !declared.contains(&**name) {
                return Err(ParseError {
                    kind: ParseErrorKind::UndeclaredExportedName,
                    span: declaration.span,
                });
            }
        }
    }
    Ok(())
}

/// §16.1.1: the five rules of §8.3, §14.8.1 and §14.9.1, asked of a finished `Script`.
///
/// The walk answers all five and this only names them, which is the seam DR-0007 asks for: the
/// operations return what they found and the parser decides what to call it.
pub(super) fn check_labels(body: &[Stmt]) -> Result<(), ParseError> {
    let Some(problem) = first_label_problem(body) else {
        return Ok(());
    };
    Err(ParseError {
        kind: match problem.kind {
            LabelProblemKind::DuplicateLabel => ParseErrorKind::DuplicateLabel,
            LabelProblemKind::UndefinedBreakTarget => ParseErrorKind::UndefinedBreakTarget,
            LabelProblemKind::UndefinedContinueTarget => ParseErrorKind::UndefinedContinueTarget,
            LabelProblemKind::BreakOutsideLoopOrSwitch => ParseErrorKind::BreakOutsideLoop,
            LabelProblemKind::ContinueOutsideLoop => ParseErrorKind::ContinueOutsideLoop,
        },
        span: problem.span,
    })
}

/// §14.7.4.1: a `for` header's lexical names may not be `var`-declared in its body.
///
/// The header is a scope of its own, between the enclosing one and the body's, so the body may
/// shadow it with a `let` — `for (let a;;) { let a; }` is fine. A `var` is not shadowing: it
/// belongs to the enclosing function and passes through the header's scope on its way out, where
/// the header's name is already sitting.
pub(super) fn check_header_against_body(
    declaration: &Declaration,
    body: &[Stmt],
) -> Result<(), ParseError> {
    let mut header: HashMap<&str, Span> = HashMap::new();
    for declarator in &declaration.declarators {
        // `BoundNames`, which a pattern makes a list of: `for (let [a, b];;) { var a; }` collides
        // on `a` exactly as `for (let a;;) { var a; }` does.
        for declared in bound_names(&declarator.binding) {
            header.insert(declared.name, declared.span);
        }
    }
    for declared in var_declared_names(body) {
        if let Some(&header_span) = header.get(declared.name) {
            return Err(ParseError {
                kind: ParseErrorKind::ConflictingVarAndLexicalDeclaration,
                span: std::cmp::max_by_key(header_span, declared.span, |span| span.start),
            });
        }
    }
    Ok(())
}

/// §14.2.1, §16.1.1 and §14.12.1, which state the same two rules about different lists.
fn check<'a>(
    lexical_names: Vec<DeclaredName<'a>>,
    var_names: Vec<DeclaredName<'_>>,
    repeatable: &HashSet<&'a str>,
) -> Result<(), ParseError> {
    let mut lexical: HashMap<&str, Span> = HashMap::new();
    for declared in lexical_names {
        // The list is in source order, so the one that collides is always the later of the
        // two and there is nothing to compare — the caret goes on the redeclaration because
        // that is where it was found, not because a rule picked it.
        //
        // `repeatable` is §B.3.3.5's exemption and is empty everywhere it does not apply, so rule
        // 1 is unchanged for strict code, for a top level and for every name a `let` also bound.
        if lexical.insert(declared.name, declared.span).is_some()
            && !repeatable.contains(declared.name)
        {
            return Err(ParseError {
                kind: ParseErrorKind::DuplicateLexicalBinding,
                span: declared.span,
            });
        }
    }
    // No short-circuit when there are no lexical names, though the loop below can then do
    // nothing: a branch no input can tell from its absence is one mutation testing
    // call untested, and it is not the parser's business to guess where the time goes.
    for declared in var_names {
        if let Some(&lexical_span) = lexical.get(declared.name) {
            return Err(ParseError {
                kind: ParseErrorKind::ConflictingVarAndLexicalDeclaration,
                // Here the two lists are separate walks, so either name may have been written
                // first — `let a; var a;` and `var a; let a;` are both this error. The caret
                // goes on the later, which is the redeclaration. Stated as a maximum rather
                // than as a comparison of my own: the two can never start at the same offset,
                // so a branch for that case would be one no input could reach.
                span: std::cmp::max_by_key(lexical_span, declared.span, |span| span.start),
            });
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::parse_script;
    use crate::parser::test_support::*;

    #[test]
    fn a_name_may_not_be_declared_lexically_twice_in_one_scope() {
        // §14.2.1 and §16.1.1, rule 1. `let a, a;` is already refused one level down by
        // §14.3.1.1, which is about one declaration; this is about the whole list.
        assert_eq!(
            script_error("let a; let a;").kind,
            ParseErrorKind::DuplicateLexicalBinding
        );
        assert_eq!(
            script_error("{ let a; let a; }").kind,
            ParseErrorKind::DuplicateLexicalBinding
        );
        assert_eq!(
            script_error("let a; const a = 1;").kind,
            ParseErrorKind::DuplicateLexicalBinding
        );
        assert_eq!(
            script_error("const a = 1; let a;").kind,
            ParseErrorKind::DuplicateLexicalBinding
        );
        assert_eq!(
            script_error("let a, b; let b;").kind,
            ParseErrorKind::DuplicateLexicalBinding
        );
        // The caret goes on the redeclaration, not on the declaration it collides with.
        assert_eq!(script_error("let a; let a;").span, Span::new(11, 12));
        assert_eq!(
            script_error("let ab = 1; let ab = 2;").span,
            Span::new(16, 18)
        );
        // A name is its StringValue, so two spellings of one name are one name.
        assert_eq!(
            script_error(r"let a; let a;").kind,
            ParseErrorKind::DuplicateLexicalBinding
        );
        // …and separate scopes are separate. This is the half that makes the rule non-trivial.
        assert!(parse_script("let a; { let a; }").is_ok());
        assert!(parse_script("{ let a; } { let a; }").is_ok());
        assert!(parse_script("{ let a; } let a;").is_ok());
        assert!(parse_script("let a; if (x) { let a; }").is_ok());
        assert!(parse_script("let a; while (x) { let a; }").is_ok());
        // `var` may repeat as much as it likes — it is not a lexical declaration.
        assert!(parse_script("var a; var a;").is_ok());
        assert!(parse_script("var a, a, a;").is_ok());
    }

    #[test]
    fn a_var_may_not_collide_with_a_lexical_name_however_deeply_it_is_buried() {
        // §14.2.1 and §16.1.1, rule 2 — and the reason it needs `VarDeclaredNames` rather than a
        // look at the list in front of you: a `var` belongs to the enclosing function, so it
        // collides from inside any number of blocks and bodies.
        assert_eq!(
            script_error("let a; var a;").kind,
            ParseErrorKind::ConflictingVarAndLexicalDeclaration
        );
        assert_eq!(
            script_error("var a; let a;").kind,
            ParseErrorKind::ConflictingVarAndLexicalDeclaration
        );
        for source in [
            "let a; { var a; }",
            "let a; { { { var a; } } }",
            "let a; if (x) var a;",
            "let a; if (x) b; else var a;",
            "let a; while (x) var a;",
            "let a; do var a; while (x);",
            "let a; while (x) { if (y) { var a; } }",
            "{ let a; { var a; } }",
            "const a = 1; { var a; }",
        ] {
            assert_eq!(
                script_error(source).kind,
                ParseErrorKind::ConflictingVarAndLexicalDeclaration,
                "{source:?}"
            );
        }
        // The caret goes on whichever was written second, in both directions.
        assert_eq!(script_error("let a; var a;").span, Span::new(11, 12));
        assert_eq!(script_error("var a; let a;").span, Span::new(11, 12));
        // …and a `var` in a scope the lexical name does not reach is not a collision. The `let`
        // here is inside the block; the `var` hoists past it to the top level, and the two never
        // share a scope.
        assert!(parse_script("var a; { let a; }").is_ok());
        assert!(parse_script("{ let a; } var a;").is_ok());
        assert!(parse_script("if (x) { let a; } var a;").is_ok());
        // A lexical name inside a nested block does not see an outer `var` either.
        assert!(parse_script("var a; if (x) { let a; }").is_ok());
    }

    #[test]
    fn the_rules_apply_to_a_script_and_to_every_block_it_contains() {
        // Both §14.2.1 (Block) and §16.1.1 (Script) state the same two rules, which is why one
        // function serves both — and why a block nested anywhere is checked, not just the top.
        assert!(parse_script("{ { { let a; let a; } } }").is_err());
        assert!(parse_script("while (x) { let a; var a; }").is_err());
        assert!(parse_script("if (x) { let a; let a; }").is_err());
        assert!(parse_script("do { let a; let a; } while (x);").is_err());
        // A clean script with a great many declarations is not accidentally quadratic or
        // accidentally wrong — the names differ, so nothing collides.
        let many: String = (0..2_000)
            .map(|i| format!("let a{i}; var b{i};\n"))
            .collect();
        assert!(parse_script(&many).is_ok());
        // …and one collision anywhere in that many still lands.
        assert_eq!(
            script_error(&(many + "var a7;")).kind,
            ParseErrorKind::ConflictingVarAndLexicalDeclaration
        );
    }
}