mozjs_sys 0.67.1

System crate for the Mozilla SpiderMonkey JavaScript engine.
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 * vim: set ts=8 sts=2 et sw=2 tw=80:
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "frontend/BinASTParserPerTokenizer.h"

#include "mozilla/ArrayUtils.h"
#include "mozilla/Casting.h"
#include "mozilla/Maybe.h"
#include "mozilla/Move.h"
#include "mozilla/PodOperations.h"
#include "mozilla/ScopeExit.h"
#include "mozilla/Vector.h"

#include "frontend/BinAST-macros.h"
#include "frontend/BinASTParser.h"
#include "frontend/BinASTTokenReaderMultipart.h"
#include "frontend/FullParseHandler.h"
#include "frontend/ParseNode.h"
#include "frontend/Parser.h"
#include "frontend/SharedContext.h"

#include "js/Result.h"
#include "vm/RegExpObject.h"

#include "frontend/ParseContext-inl.h"
#include "frontend/SharedContext-inl.h"
#include "vm/JSContext-inl.h"

// # About compliance with EcmaScript
//
// For the moment, this parser implements ES5. Future versions will be extended
// to ES6 and further on.
//
// By design, it does NOT implement Annex B.3.3. If possible, we would like
// to avoid going down that rabbit hole.
//
//
// # About the AST
//
// At this stage of experimentation, the AST specifications change often. This
// version of the parser attempts to implement
// https://gist.github.com/Yoric/2390f0367515c079172be2526349b294
//
//
// # About validating the AST
//
// Normally, this implementation validates all properties of the AST *except*
// the order of fields, which is partially constrained by the AST spec (e.g. in
// a block, field `scope` must appear before field `body`, etc.).
//
//
// # About names and scopes
//
// One of the key objectives of the BinAST syntax is to be able to entirely skip
// parsing inner functions until they are needed. With a purely syntactic AST,
// this is generally impossible, as we would need to walk the AST to find
// lexically-bound/var-bound variables, instances of direct eval, etc.
//
// To achieve this, BinAST files contain scope data, as instances of
// `BinJS:Scope` nodes. Rather than walking the AST to assign bindings
// to scopes, we extract data from the `BinJS:Scope` and check it lazily,
// once we actually need to walk the AST.
//
// WARNING: The current implementation DOES NOT perform the check yet. It
// is therefore unsafe.
//
// # About directives
//
// Currently, directives are ignored and treated as regular strings.
//
// They should be treated lazily (whenever we open a subscope), like bindings.

namespace js {
namespace frontend {

using UsedNamePtr = UsedNameTracker::UsedNameMap::Ptr;

// ------------- Toplevel constructions

template <typename Tok>
BinASTParserPerTokenizer<Tok>::BinASTParserPerTokenizer(
    JSContext* cx, LifoAlloc& alloc, UsedNameTracker& usedNames,
    const JS::ReadOnlyCompileOptions& options,
    HandleScriptSourceObject sourceObject,
    Handle<LazyScript*> lazyScript /* = nullptr */)
    : BinASTParserBase(cx, alloc, usedNames, sourceObject),
      options_(options),
      lazyScript_(cx, lazyScript),
      handler_(cx, alloc, nullptr, SourceKind::Binary),
      variableDeclarationKind_(VariableDeclarationKind::Var) {
  MOZ_ASSERT_IF(lazyScript_, lazyScript_->isBinAST());
}

template <typename Tok>
JS::Result<ParseNode*> BinASTParserPerTokenizer<Tok>::parse(
    GlobalSharedContext* globalsc, const Vector<uint8_t>& data,
    BinASTSourceMetadata** metadataPtr) {
  return parse(globalsc, data.begin(), data.length(), metadataPtr);
}

template <typename Tok>
JS::Result<ParseNode*> BinASTParserPerTokenizer<Tok>::parse(
    GlobalSharedContext* globalsc, const uint8_t* start, const size_t length,
    BinASTSourceMetadata** metadataPtr) {
  auto result = parseAux(globalsc, start, length, metadataPtr);
  poison();  // Make sure that the parser is never used again accidentally.
  return result;
}

template <typename Tok>
JS::Result<ParseNode*> BinASTParserPerTokenizer<Tok>::parseAux(
    GlobalSharedContext* globalsc, const uint8_t* start, const size_t length,
    BinASTSourceMetadata** metadataPtr) {
  MOZ_ASSERT(globalsc);

  tokenizer_.emplace(cx_, this, start, length);

  BinASTParseContext globalpc(cx_, this, globalsc,
                              /* newDirectives = */ nullptr);
  if (!globalpc.init()) {
    return cx_->alreadyReportedError();
  }

  ParseContext::VarScope varScope(cx_, &globalpc, usedNames_);
  if (!varScope.init(&globalpc)) {
    return cx_->alreadyReportedError();
  }

  MOZ_TRY(tokenizer_->readHeader());

  ParseNode* result(nullptr);
  MOZ_TRY_VAR(result, asFinalParser()->parseProgram());

  mozilla::Maybe<GlobalScope::Data*> bindings =
      NewGlobalScopeData(cx_, varScope, alloc_, pc_);
  if (!bindings) {
    return cx_->alreadyReportedError();
  }
  globalsc->bindings = *bindings;

  if (metadataPtr) {
    *metadataPtr = tokenizer_->takeMetadata();
  }

  return result;  // Magic conversion to Ok.
}

template <typename Tok>
JS::Result<FunctionNode*> BinASTParserPerTokenizer<Tok>::parseLazyFunction(
    ScriptSource* scriptSource, const size_t firstOffset) {
  MOZ_ASSERT(lazyScript_);
  MOZ_ASSERT(scriptSource->length() > firstOffset);

  tokenizer_.emplace(cx_, this, scriptSource->binASTSource(),
                     scriptSource->length());

  MOZ_TRY(tokenizer_->initFromScriptSource(scriptSource));

  tokenizer_->seek(firstOffset);

  // For now, only function declarations and function expression are supported.
  RootedFunction func(cx_, lazyScript_->functionNonDelazifying());
  bool isExpr = func->isLambda();
  MOZ_ASSERT(func->kind() == JSFunction::FunctionKind::NormalFunction);

  // Poison the tokenizer when we leave to ensure that it's not used again by
  // accident.
  auto onExit = mozilla::MakeScopeExit([&]() { poison(); });

  // TODO: This should be actually shared with the auto-generated version.

  auto syntaxKind =
      isExpr ? FunctionSyntaxKind::Expression : FunctionSyntaxKind::Statement;
  BINJS_MOZ_TRY_DECL(
      funbox, buildFunctionBox(lazyScript_->generatorKind(),
                               lazyScript_->asyncKind(), syntaxKind, nullptr));

  // Push a new ParseContext. It will be used to parse `scope`, the arguments,
  // the function.
  BinASTParseContext funpc(cx_, this, funbox, /* newDirectives = */ nullptr);
  BINJS_TRY(funpc.init());
  pc_->functionScope().useAsVarScope(pc_);
  MOZ_ASSERT(pc_->isFunctionBox());

  ParseContext::Scope lexicalScope(cx_, pc_, usedNames_);
  BINJS_TRY(lexicalScope.init(pc_));
  ListNode* params;
  ListNode* tmpBody;
  auto parseFunc = isExpr ? &FinalParser::parseFunctionExpressionContents
                          : &FinalParser::parseFunctionOrMethodContents;
  MOZ_TRY((asFinalParser()->*parseFunc)(func->nargs(), &params, &tmpBody));

  BINJS_TRY_DECL(lexicalScopeData,
                 NewLexicalScopeData(cx_, lexicalScope, alloc_, pc_));
  BINJS_TRY_DECL(body, handler_.newLexicalScope(*lexicalScopeData, tmpBody));

  auto binASTKind = isExpr ? BinASTKind::LazyFunctionExpression
                           : BinASTKind::LazyFunctionDeclaration;
  return buildFunction(firstOffset, binASTKind, nullptr, params, body);
}

template <typename Tok>
void BinASTParserPerTokenizer<Tok>::forceStrictIfNecessary(
    SharedContext* sc, ListNode* directives) {
  JSAtom* useStrict = cx_->names().useStrict;

  for (const ParseNode* directive : directives->contents()) {
    if (directive->as<NameNode>().atom() == useStrict) {
      sc->strictScript = true;
      break;
    }
  }
}

template <typename Tok>
JS::Result<FunctionBox*> BinASTParserPerTokenizer<Tok>::buildFunctionBox(
    GeneratorKind generatorKind, FunctionAsyncKind functionAsyncKind,
    FunctionSyntaxKind syntax, ParseNode* name) {
  MOZ_ASSERT_IF(!pc_, lazyScript_);

  RootedAtom atom(cx_);

  // Name might be any of {Identifier,ComputedPropertyName,LiteralPropertyName}
  if (name && name->is<NameNode>()) {
    atom = name->as<NameNode>().atom();
  }

  if (pc_ && syntax == FunctionSyntaxKind::Statement) {
    auto ptr = pc_->varScope().lookupDeclaredName(atom);
    if (!ptr) {
      return raiseError(
          "FunctionDeclaration without corresponding AssertedDeclaredName.");
    }

    DeclarationKind declaredKind = ptr->value()->kind();
    if (DeclarationKindIsVar(declaredKind)) {
      if (!pc_->atBodyLevel()) {
        return raiseError(
            "body-level FunctionDeclaration inside non-body-level context.");
      }
      RedeclareVar(ptr, DeclarationKind::BodyLevelFunction);
    }
  }

  // Allocate the function before walking down the tree.
  RootedFunction fun(cx_);
  BINJS_TRY_VAR(fun, !pc_ ? lazyScript_->functionNonDelazifying()
                          : AllocNewFunction(cx_, atom, syntax, generatorKind,
                                             functionAsyncKind, nullptr));
  MOZ_ASSERT_IF(pc_, fun->explicitName() == atom);

  mozilla::Maybe<Directives> directives;
  if (pc_) {
    directives.emplace(pc_);
  } else {
    directives.emplace(lazyScript_->strict());
  }

  auto* funbox = alloc_.new_<FunctionBox>(
      cx_, traceListHead_, fun, /* toStringStart = */ 0, *directives,
      /* extraWarning = */ false, generatorKind, functionAsyncKind);
  if (!funbox) {
    return raiseOOM();
  }

  traceListHead_ = funbox;
  if (pc_) {
    funbox->initWithEnclosingParseContext(pc_, syntax);
  } else {
    funbox->initFromLazyFunction();
  }
  return funbox;
}

FunctionSyntaxKind BinASTKindToFunctionSyntaxKind(const BinASTKind kind) {
  // FIXME: this doesn't cover FunctionSyntaxKind::ClassConstructor and
  // FunctionSyntaxKind::DerivedClassConstructor.
  switch (kind) {
    case BinASTKind::EagerFunctionDeclaration:
    case BinASTKind::LazyFunctionDeclaration:
      return FunctionSyntaxKind::Statement;
    case BinASTKind::EagerFunctionExpression:
    case BinASTKind::LazyFunctionExpression:
      return FunctionSyntaxKind::Expression;
    case BinASTKind::EagerArrowExpressionWithFunctionBody:
    case BinASTKind::LazyArrowExpressionWithFunctionBody:
    case BinASTKind::EagerArrowExpressionWithExpression:
    case BinASTKind::LazyArrowExpressionWithExpression:
      return FunctionSyntaxKind::Arrow;
    case BinASTKind::EagerMethod:
    case BinASTKind::LazyMethod:
      return FunctionSyntaxKind::Method;
    case BinASTKind::EagerGetter:
    case BinASTKind::LazyGetter:
      return FunctionSyntaxKind::Getter;
    case BinASTKind::EagerSetter:
    case BinASTKind::LazySetter:
      return FunctionSyntaxKind::Setter;
    default:
      MOZ_CRASH("Invalid/ kind");
  }
}

template <typename Tok>
JS::Result<FunctionNode*> BinASTParserPerTokenizer<Tok>::makeEmptyFunctionNode(
    const size_t start, const BinASTKind kind, FunctionBox* funbox) {
  // LazyScript compilation requires basically none of the fields filled out.
  TokenPos pos = tokenizer_->pos(start);
  FunctionSyntaxKind syntaxKind = BinASTKindToFunctionSyntaxKind(kind);

  BINJS_TRY_DECL(result, handler_.newFunction(syntaxKind, pos));

  handler_.setFunctionBox(result, funbox);

  return result;
}

template <typename Tok>
JS::Result<FunctionNode*> BinASTParserPerTokenizer<Tok>::buildFunction(
    const size_t start, const BinASTKind kind, ParseNode* name,
    ListNode* params, ParseNode* body) {
  FunctionBox* funbox = pc_->functionBox();

  // Set the argument count for building argument packets. Function.length is
  // handled by setting the appropriate funbox field during argument parsing.
  if (!lazyScript_ ||
      lazyScript_->functionNonDelazifying() != funbox->function()) {
    funbox->function()->setArgCount(params ? uint16_t(params->count()) : 0);
  }

  // ParseNode represents the body as concatenated after the params.
  params->appendWithoutOrderAssumption(body);

  BINJS_MOZ_TRY_DECL(result, makeEmptyFunctionNode(start, kind, funbox));

  handler_.setFunctionFormalParametersAndBody(result, params);

  if (funbox->needsDotGeneratorName()) {
    BINJS_TRY(pc_->declareDotGeneratorName());

    HandlePropertyName dotGenerator = cx_->names().dotGenerator;
    BINJS_TRY(usedNames_.noteUse(cx_, dotGenerator, pc_->scriptId(),
                                 pc_->innermostScope()->id()));

    if (funbox->isGenerator()) {
      BINJS_TRY_DECL(
          dotGen, handler_.newName(dotGenerator,
                                   tokenizer_->pos(tokenizer_->offset()), cx_));

      ListNode* stmtList =
          &body->as<LexicalScopeNode>().scopeBody()->as<ListNode>();
      BINJS_TRY(handler_.prependInitialYield(stmtList, dotGen));
    }
  }

  const bool canSkipLazyClosedOverBindings = false;
  BINJS_TRY(pc_->declareFunctionArgumentsObject(usedNames_,
                                                canSkipLazyClosedOverBindings));
  BINJS_TRY(
      pc_->declareFunctionThis(usedNames_, canSkipLazyClosedOverBindings));

  // Check all our bindings after maybe adding function metavars.
  MOZ_TRY(checkFunctionClosedVars());

  BINJS_TRY_DECL(bindings, NewFunctionScopeData(cx_, pc_->functionScope(),
                                                /* hasParameterExprs = */ false,
                                                alloc_, pc_));

  funbox->functionScopeBindings().set(*bindings);

  if (funbox->function()->isNamedLambda()) {
    BINJS_TRY_DECL(
        recursiveBinding,
        NewLexicalScopeData(cx_, pc_->namedLambdaScope(), alloc_, pc_));

    funbox->namedLambdaBindings().set(*recursiveBinding);
  }

  return result;
}

template <typename Tok>
JS::Result<Ok> BinASTParserPerTokenizer<Tok>::addScopeName(
    AssertedScopeKind scopeKind, HandleAtom name, ParseContext::Scope* scope,
    DeclarationKind declKind, bool isCaptured, bool allowDuplicateName) {
  auto ptr = scope->lookupDeclaredNameForAdd(name);
  if (ptr) {
    if (allowDuplicateName) {
      return Ok();
    }
    return raiseError("Variable redeclaration");
  }

  BINJS_TRY(scope->addDeclaredName(pc_, ptr, name.get(), declKind,
                                   tokenizer_->offset()));

  if (isCaptured) {
    auto declaredPtr = scope->lookupDeclaredName(name);
    MOZ_ASSERT(declaredPtr);
    declaredPtr->value()->setClosedOver();
  }

  return Ok();
}

template <typename Tok>
void BinASTParserPerTokenizer<Tok>::captureFunctionName() {
  MOZ_ASSERT(pc_->isFunctionBox());
  MOZ_ASSERT(pc_->functionBox()->function()->isNamedLambda());

  RootedAtom funName(cx_, pc_->functionBox()->function()->explicitName());
  MOZ_ASSERT(funName);

  auto ptr = pc_->namedLambdaScope().lookupDeclaredName(funName);
  MOZ_ASSERT(ptr);
  ptr->value()->setClosedOver();
}

template <typename Tok>
JS::Result<Ok> BinASTParserPerTokenizer<Tok>::getDeclaredScope(
    AssertedScopeKind scopeKind, AssertedDeclaredKind kind,
    ParseContext::Scope*& scope, DeclarationKind& declKind) {
  MOZ_ASSERT(scopeKind == AssertedScopeKind::Block ||
             scopeKind == AssertedScopeKind::Global ||
             scopeKind == AssertedScopeKind::Var);
  switch (kind) {
    case AssertedDeclaredKind::Var:
      if (scopeKind == AssertedScopeKind::Block) {
        return raiseError("AssertedBlockScope cannot contain 'var' binding");
      }
      declKind = DeclarationKind::Var;
      scope = &pc_->varScope();
      break;
    case AssertedDeclaredKind::NonConstLexical:
      declKind = DeclarationKind::Let;
      scope = pc_->innermostScope();
      break;
    case AssertedDeclaredKind::ConstLexical:
      declKind = DeclarationKind::Const;
      scope = pc_->innermostScope();
      break;
  }

  return Ok();
}

template <typename Tok>
JS::Result<Ok> BinASTParserPerTokenizer<Tok>::getBoundScope(
    AssertedScopeKind scopeKind, ParseContext::Scope*& scope,
    DeclarationKind& declKind) {
  MOZ_ASSERT(scopeKind == AssertedScopeKind::Catch ||
             scopeKind == AssertedScopeKind::Parameter);
  switch (scopeKind) {
    case AssertedScopeKind::Catch:
      declKind = DeclarationKind::CatchParameter;
      scope = pc_->innermostScope();
      break;
    case AssertedScopeKind::Parameter:
      MOZ_ASSERT(pc_->isFunctionBox());
      declKind = DeclarationKind::PositionalFormalParameter;
      scope = &pc_->functionScope();
      break;
    default:
      MOZ_ASSERT_UNREACHABLE("Unexpected AssertedScopeKind");
      break;
  }

  return Ok();
}

template <typename Tok>
JS::Result<Ok> BinASTParserPerTokenizer<Tok>::checkBinding(JSAtom* name) {
  // Check that the variable appears in the corresponding scope.
  ParseContext::Scope& scope =
      variableDeclarationKind_ == VariableDeclarationKind::Var
          ? pc_->varScope()
          : *pc_->innermostScope();

  auto ptr = scope.lookupDeclaredName(name->asPropertyName());
  if (!ptr) {
    return raiseMissingVariableInAssertedScope(name);
  }

  return Ok();
}

// Binary AST (revision 8eab67e0c434929a66ff6abe99ff790bca087dda)
// 3.1.5 CheckPositionalParameterIndices.
template <typename Tok>
JS::Result<Ok> BinASTParserPerTokenizer<Tok>::checkPositionalParameterIndices(
    Handle<GCVector<JSAtom*>> positionalParams, ListNode* params) {
  // positionalParams should have the corresponding entry up to the last
  // positional parameter.

  // `positionalParams` corresponds to `expectedParams` parameter in the spec.
  // `params` corresponds to `parseTree` in 3.1.9 CheckAssertedScope, and
  // `positionalParamNames` parameter

  // Steps 1-3.
  // PositionalParameterNames (3.1.9 CheckAssertedScope step 5.d) and
  // CreatePositionalParameterIndices (3.1.5 CheckPositionalParameterIndices
  // step 1) are done implicitly.
  uint32_t i = 0;
  const bool hasRest = pc_->functionBox()->hasRest();
  for (ParseNode* param : params->contents()) {
    if (param->isKind(ParseNodeKind::AssignExpr)) {
      param = param->as<AssignmentNode>().left();
    }

    // At this point, function body is not part of params list.
    const bool isRest = hasRest && !param->pn_next;
    if (isRest) {
      // Rest parameter

      // Step 3.
      if (i >= positionalParams.get().length()) {
        continue;
      }

      if (positionalParams.get()[i]) {
        return raiseError(
            "Expected positional parameter per "
            "AssertedParameterScope.paramNames, got rest parameter");
      }
    } else if (param->isKind(ParseNodeKind::Name)) {
      // Simple or default parameter.

      // Step 2.a.
      if (i >= positionalParams.get().length()) {
        return raiseError(
            "AssertedParameterScope.paramNames doesn't have corresponding "
            "entry to positional parameter");
      }

      JSAtom* name = positionalParams.get()[i];
      if (!name) {
        // Step 2.a.ii.1.
        return raiseError(
            "Expected destructuring/rest parameter per "
            "AssertedParameterScope.paramNames, got positional parameter");
      }

      // Step 2.a.i.
      if (param->as<NameNode>().name() != name) {
        // Step 2.a.ii.1.
        return raiseError(
            "Name mismatch between AssertedPositionalParameterName in "
            "AssertedParameterScope.paramNames and actual parameter");
      }

      // Step 2.a.i.1.
      // Implicitly done.
    } else {
      // Destructuring parameter.

      MOZ_ASSERT(param->isKind(ParseNodeKind::ObjectExpr) ||
                 param->isKind(ParseNodeKind::ArrayExpr));

      // Step 3.
      if (i >= positionalParams.get().length()) {
        continue;
      }

      if (positionalParams.get()[i]) {
        return raiseError(
            "Expected positional parameter per "
            "AssertedParameterScope.paramNames, got destructuring parameter");
      }
    }

    i++;
  }

  // Step 3.
  if (positionalParams.get().length() > params->count()) {
    // `positionalParams` has unchecked entries.
    return raiseError(
        "AssertedParameterScope.paramNames has unmatching items than the "
        "actual parameters");
  }

  return Ok();
}

// Binary AST (revision 8eab67e0c434929a66ff6abe99ff790bca087dda)
// 3.1.13 CheckFunctionLength.
template <typename Tok>
JS::Result<Ok> BinASTParserPerTokenizer<Tok>::checkFunctionLength(
    uint32_t expectedLength) {
  if (pc_->functionBox()->length != expectedLength) {
    return raiseError("Function length does't match");
  }
  return Ok();
}

template <typename Tok>
JS::Result<Ok> BinASTParserPerTokenizer<Tok>::checkClosedVars(
    ParseContext::Scope& scope) {
  for (ParseContext::Scope::BindingIter bi = scope.bindings(pc_); bi; bi++) {
    if (UsedNamePtr p = usedNames_.lookup(bi.name())) {
      bool closedOver;
      p->value().noteBoundInScope(pc_->scriptId(), scope.id(), &closedOver);
      if (closedOver && !bi.closedOver()) {
        return raiseInvalidClosedVar(bi.name());
      }
    }
  }

  return Ok();
}

template <typename Tok>
JS::Result<Ok> BinASTParserPerTokenizer<Tok>::checkFunctionClosedVars() {
  MOZ_ASSERT(pc_->isFunctionBox());

  MOZ_TRY(checkClosedVars(*pc_->innermostScope()));
  MOZ_TRY(checkClosedVars(pc_->functionScope()));
  if (pc_->functionBox()->function()->isNamedLambda()) {
    MOZ_TRY(checkClosedVars(pc_->namedLambdaScope()));
  }

  return Ok();
}

template <typename Tok>
JS::Result<Ok> BinASTParserPerTokenizer<Tok>::prependDirectivesToBody(
    ListNode* body, ListNode* directives) {
  if (!directives) {
    return Ok();
  }

  if (directives->empty()) {
    return Ok();
  }

  MOZ_TRY(prependDirectivesImpl(body, directives->head()));

  return Ok();
}

template <typename Tok>
JS::Result<Ok> BinASTParserPerTokenizer<Tok>::prependDirectivesImpl(
    ListNode* body, ParseNode* directive) {
  BINJS_TRY(CheckRecursionLimit(cx_));

  // Prepend in the reverse order by using stack, so that the directives are
  // prepended in the original order.
  if (ParseNode* next = directive->pn_next) {
    MOZ_TRY(prependDirectivesImpl(body, next));
  }

  BINJS_TRY_DECL(statement,
                 handler_.newExprStatement(directive, directive->pn_pos.end));
  body->prependAndUpdatePos(statement);

  return Ok();
}

template <typename Tok>
mozilla::GenericErrorResult<JS::Error&>
BinASTParserPerTokenizer<Tok>::raiseInvalidClosedVar(JSAtom* name) {
  return raiseError("Captured variable was not declared as captured");
}

template <typename Tok>
mozilla::GenericErrorResult<JS::Error&>
BinASTParserPerTokenizer<Tok>::raiseMissingVariableInAssertedScope(
    JSAtom* name) {
  // For the moment, we don't trust inputs sufficiently to put the name
  // in an error message.
  return raiseError("Missing variable in AssertedScope");
}

template <typename Tok>
mozilla::GenericErrorResult<JS::Error&>
BinASTParserPerTokenizer<Tok>::raiseMissingDirectEvalInAssertedScope() {
  return raiseError("Direct call to `eval` was not declared in AssertedScope");
}

template <typename Tok>
mozilla::GenericErrorResult<JS::Error&>
BinASTParserPerTokenizer<Tok>::raiseInvalidKind(const char* superKind,
                                                const BinASTKind kind) {
  Sprinter out(cx_);
  BINJS_TRY(out.init());
  BINJS_TRY(out.printf("In %s, invalid kind %s", superKind,
                       describeBinASTKind(kind)));
  return raiseError(out.string());
}

template <typename Tok>
mozilla::GenericErrorResult<JS::Error&>
BinASTParserPerTokenizer<Tok>::raiseInvalidVariant(const char* kind,
                                                   const BinASTVariant value) {
  Sprinter out(cx_);
  BINJS_TRY(out.init());
  BINJS_TRY(out.printf("In %s, invalid variant '%s'", kind,
                       describeBinASTVariant(value)));

  return raiseError(out.string());
}

template <typename Tok>
mozilla::GenericErrorResult<JS::Error&>
BinASTParserPerTokenizer<Tok>::raiseMissingField(const char* kind,
                                                 const BinASTField field) {
  Sprinter out(cx_);
  BINJS_TRY(out.init());
  BINJS_TRY(out.printf("In %s, missing field '%s'", kind,
                       describeBinASTField(field)));

  return raiseError(out.string());
}

template <typename Tok>
mozilla::GenericErrorResult<JS::Error&>
BinASTParserPerTokenizer<Tok>::raiseEmpty(const char* description) {
  Sprinter out(cx_);
  BINJS_TRY(out.init());
  BINJS_TRY(out.printf("Empty %s", description));

  return raiseError(out.string());
}

template <typename Tok>
mozilla::GenericErrorResult<JS::Error&>
BinASTParserPerTokenizer<Tok>::raiseOOM() {
  return tokenizer_->raiseOOM();
}

template <typename Tok>
mozilla::GenericErrorResult<JS::Error&>
BinASTParserPerTokenizer<Tok>::raiseError(BinASTKind kind,
                                          const char* description) {
  Sprinter out(cx_);
  BINJS_TRY(out.init());
  BINJS_TRY(out.printf("In %s, %s", describeBinASTKind(kind), description));
  return tokenizer_->raiseError(out.string());
}

template <typename Tok>
mozilla::GenericErrorResult<JS::Error&>
BinASTParserPerTokenizer<Tok>::raiseError(const char* description) {
  return tokenizer_->raiseError(description);
}

template <typename Tok>
void BinASTParserPerTokenizer<Tok>::poison() {
  tokenizer_.reset();
}

template <typename Tok>
bool BinASTParserPerTokenizer<Tok>::computeErrorMetadata(
    ErrorMetadata* err, const ErrorOffset& errorOffset) {
  err->filename = getFilename();
  err->lineNumber = 0;
  if (errorOffset.is<uint32_t>()) {
    err->columnNumber = errorOffset.as<uint32_t>();
  } else if (errorOffset.is<Current>()) {
    err->columnNumber = offset();
  } else {
    errorOffset.is<NoOffset>();
    err->columnNumber = 0;
  }

  err->isMuted = options().mutedErrors();
  return true;
}

void TraceBinASTParser(JSTracer* trc, JS::AutoGCRooter* parser) {
  static_cast<BinASTParserBase*>(parser)->trace(trc);
}

template <typename Tok>
void BinASTParserPerTokenizer<Tok>::doTrace(JSTracer* trc) {
  if (tokenizer_) {
    tokenizer_->traceMetadata(trc);
  }
}

template <typename Tok>
inline typename BinASTParserPerTokenizer<Tok>::FinalParser*
BinASTParserPerTokenizer<Tok>::asFinalParser() {
  // Same as GeneralParser::asFinalParser, verify the inheritance to
  // make sure the static downcast works.
  static_assert(
      mozilla::IsBaseOf<BinASTParserPerTokenizer<Tok>, FinalParser>::value,
      "inheritance relationship required by the static_cast<> below");

  return static_cast<FinalParser*>(this);
}

template <typename Tok>
inline const typename BinASTParserPerTokenizer<Tok>::FinalParser*
BinASTParserPerTokenizer<Tok>::asFinalParser() const {
  static_assert(
      mozilla::IsBaseOf<BinASTParserPerTokenizer<Tok>, FinalParser>::value,
      "inheritance relationship required by the static_cast<> below");

  return static_cast<const FinalParser*>(this);
}

// Force class instantiation.
// This ensures that the symbols are built, without having to export all our
// code (and its baggage of #include and macros) in the header.
template class BinASTParserPerTokenizer<BinASTTokenReaderMultipart>;

}  // namespace frontend
}  // namespace js