js/src/frontend/Parser.cpp
author Jeff Walden <jwalden@mit.edu>
Tue, 07 Nov 2017 16:12:33 -0800
changeset 444110 af596055be2169def86749be7d8c8e4fbf3ede2f
parent 444108 d8441c69c0831e7b497991ff20c8fb09506afd9b
child 444437 67fe0ac257b8a1169a208bf4c7f5c2369c3239ee
permissions -rw-r--r--
Bug 1414805 - Use proper modifiers when parsing default expressions that end in an arrow function with block body, in function parameters. r=arai

/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 * vim: set ts=8 sts=4 et sw=4 tw=99:
 * 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/. */

/*
 * JS parser.
 *
 * This is a recursive-descent parser for the JavaScript language specified by
 * "The ECMAScript Language Specification" (Standard ECMA-262).  It uses
 * lexical and semantic feedback to disambiguate non-LL(1) structures.  It
 * generates trees of nodes induced by the recursive parsing (not precise
 * syntax trees, see Parser.h).  After tree construction, it rewrites trees to
 * fold constants and evaluate compile-time expressions.
 *
 * This parser attempts no error recovery.
 */

#include "frontend/Parser.h"

#include "mozilla/Range.h"
#include "mozilla/Sprintf.h"

#include "jsapi.h"
#include "jsatom.h"
#include "jscntxt.h"
#include "jsfun.h"
#include "jsopcode.h"
#include "jsscript.h"
#include "jstypes.h"

#include "builtin/ModuleObject.h"
#include "builtin/SelfHostingDefines.h"
#include "frontend/BytecodeCompiler.h"
#include "frontend/FoldConstants.h"
#include "frontend/TokenStream.h"
#include "irregexp/RegExpParser.h"
#include "vm/RegExpObject.h"
#include "wasm/AsmJS.h"

#include "jsatominlines.h"
#include "jsscriptinlines.h"

#include "frontend/ParseNode-inl.h"
#include "vm/EnvironmentObject-inl.h"

using namespace js;
using namespace js::gc;

using mozilla::Maybe;
using mozilla::Move;
using mozilla::Nothing;
using mozilla::PodCopy;
using mozilla::PodZero;
using mozilla::Some;

using JS::AutoGCRooter;

namespace js {
namespace frontend {

using DeclaredNamePtr = ParseContext::Scope::DeclaredNamePtr;
using AddDeclaredNamePtr = ParseContext::Scope::AddDeclaredNamePtr;
using BindingIter = ParseContext::Scope::BindingIter;
using UsedNamePtr = UsedNameTracker::UsedNameMap::Ptr;

// Read a token. Report an error and return null() if that token doesn't match
// to the condition.  Do not use MUST_MATCH_TOKEN_INTERNAL directly.
#define MUST_MATCH_TOKEN_INTERNAL(cond, modifier, errorReport)                              \
    JS_BEGIN_MACRO                                                                          \
        TokenKind token;                                                                    \
        if (!tokenStream.getToken(&token, modifier))                                        \
            return null();                                                                  \
        if (!(cond)) {                                                                      \
            errorReport;                                                                    \
            return null();                                                                  \
        }                                                                                   \
    JS_END_MACRO

#define MUST_MATCH_TOKEN_MOD(tt, modifier, errorNumber) \
    MUST_MATCH_TOKEN_INTERNAL(token == tt, modifier, error(errorNumber))

#define MUST_MATCH_TOKEN(tt, errorNumber) \
    MUST_MATCH_TOKEN_MOD(tt, TokenStream::None, errorNumber)

#define MUST_MATCH_TOKEN_FUNC_MOD(func, modifier, errorNumber) \
    MUST_MATCH_TOKEN_INTERNAL((func)(token), modifier, error(errorNumber))

#define MUST_MATCH_TOKEN_FUNC(func, errorNumber) \
    MUST_MATCH_TOKEN_FUNC_MOD(func, TokenStream::None, errorNumber)

#define MUST_MATCH_TOKEN_MOD_WITH_REPORT(tt, modifier, errorReport) \
    MUST_MATCH_TOKEN_INTERNAL(token == tt, modifier, errorReport)

template <class T, class U>
static inline void
PropagateTransitiveParseFlags(const T* inner, U* outer)
{
    if (inner->bindingsAccessedDynamically())
        outer->setBindingsAccessedDynamically();
    if (inner->hasDebuggerStatement())
        outer->setHasDebuggerStatement();
    if (inner->hasDirectEval())
        outer->setHasDirectEval();
}

static const char*
DeclarationKindString(DeclarationKind kind)
{
    switch (kind) {
      case DeclarationKind::PositionalFormalParameter:
      case DeclarationKind::FormalParameter:
        return "formal parameter";
      case DeclarationKind::CoverArrowParameter:
        return "cover arrow parameter";
      case DeclarationKind::Var:
        return "var";
      case DeclarationKind::Let:
        return "let";
      case DeclarationKind::Const:
        return "const";
      case DeclarationKind::Class:
        return "class";
      case DeclarationKind::Import:
        return "import";
      case DeclarationKind::BodyLevelFunction:
      case DeclarationKind::ModuleBodyLevelFunction:
      case DeclarationKind::LexicalFunction:
      case DeclarationKind::SloppyLexicalFunction:
        return "function";
      case DeclarationKind::VarForAnnexBLexicalFunction:
        return "annex b var";
      case DeclarationKind::ForOfVar:
        return "var in for-of";
      case DeclarationKind::SimpleCatchParameter:
      case DeclarationKind::CatchParameter:
        return "catch parameter";
    }

    MOZ_CRASH("Bad DeclarationKind");
}

static bool
StatementKindIsBraced(StatementKind kind)
{
    return kind == StatementKind::Block ||
           kind == StatementKind::Switch ||
           kind == StatementKind::Try ||
           kind == StatementKind::Catch ||
           kind == StatementKind::Finally ||
           kind == StatementKind::Class;
}

void
ParseContext::Scope::dump(ParseContext* pc)
{
    JSContext* cx = pc->sc()->context;

    fprintf(stdout, "ParseScope %p", this);

    fprintf(stdout, "\n  decls:\n");
    for (DeclaredNameMap::Range r = declared_->all(); !r.empty(); r.popFront()) {
        JSAutoByteString bytes;
        if (!AtomToPrintableString(cx, r.front().key(), &bytes))
            return;
        DeclaredNameInfo& info = r.front().value().wrapped;
        fprintf(stdout, "    %s %s%s\n",
                DeclarationKindString(info.kind()),
                bytes.ptr(),
                info.closedOver() ? " (closed over)" : "");
    }

    fprintf(stdout, "\n");
}

bool
ParseContext::Scope::addPossibleAnnexBFunctionBox(ParseContext* pc, FunctionBox* funbox)
{
    if (!possibleAnnexBFunctionBoxes_) {
        if (!possibleAnnexBFunctionBoxes_.acquire(pc->sc()->context))
            return false;
    }

    return possibleAnnexBFunctionBoxes_->append(funbox);
}

bool
ParseContext::Scope::propagateAndMarkAnnexBFunctionBoxes(ParseContext* pc)
{
    // Strict mode doesn't have wack Annex B function semantics.
    if (pc->sc()->strict() ||
        !possibleAnnexBFunctionBoxes_ ||
        possibleAnnexBFunctionBoxes_->empty())
    {
        return true;
    }

    if (this == &pc->varScope()) {
        // Base case: actually declare the Annex B vars and mark applicable
        // function boxes as Annex B.
        RootedPropertyName name(pc->sc()->context);
        Maybe<DeclarationKind> redeclaredKind;
        uint32_t unused;
        for (FunctionBox* funbox : *possibleAnnexBFunctionBoxes_) {
            if (pc->annexBAppliesToLexicalFunctionInInnermostScope(funbox)) {
                name = funbox->function()->explicitName()->asPropertyName();
                if (!pc->tryDeclareVar(name,
                                       DeclarationKind::VarForAnnexBLexicalFunction,
                                       DeclaredNameInfo::npos, &redeclaredKind, &unused))
                {
                    return false;
                }

                MOZ_ASSERT(!redeclaredKind);
                funbox->isAnnexB = true;
            }
        }
    } else {
        // Inner scope case: propagate still applicable function boxes to the
        // enclosing scope.
        for (FunctionBox* funbox : *possibleAnnexBFunctionBoxes_) {
            if (pc->annexBAppliesToLexicalFunctionInInnermostScope(funbox)) {
                if (!enclosing()->addPossibleAnnexBFunctionBox(pc, funbox))
                    return false;
            }
        }
    }

    return true;
}

static bool
DeclarationKindIsCatchParameter(DeclarationKind kind)
{
    return kind == DeclarationKind::SimpleCatchParameter ||
           kind == DeclarationKind::CatchParameter;
}

bool
ParseContext::Scope::addCatchParameters(ParseContext* pc, Scope& catchParamScope)
{
    if (pc->useAsmOrInsideUseAsm())
        return true;

    for (DeclaredNameMap::Range r = catchParamScope.declared_->all(); !r.empty(); r.popFront()) {
        DeclarationKind kind = r.front().value()->kind();
        uint32_t pos = r.front().value()->pos();
        MOZ_ASSERT(DeclarationKindIsCatchParameter(kind));
        JSAtom* name = r.front().key();
        AddDeclaredNamePtr p = lookupDeclaredNameForAdd(name);
        MOZ_ASSERT(!p);
        if (!addDeclaredName(pc, p, name, kind, pos))
            return false;
    }

    return true;
}

void
ParseContext::Scope::removeCatchParameters(ParseContext* pc, Scope& catchParamScope)
{
    if (pc->useAsmOrInsideUseAsm())
        return;

    for (DeclaredNameMap::Range r = catchParamScope.declared_->all(); !r.empty(); r.popFront()) {
        DeclaredNamePtr p = declared_->lookup(r.front().key());
        MOZ_ASSERT(p);

        // This check is needed because the catch body could have declared
        // vars, which would have been added to catchParamScope.
        if (DeclarationKindIsCatchParameter(r.front().value()->kind()))
            declared_->remove(p);
    }
}

void
SharedContext::computeAllowSyntax(Scope* scope)
{
    for (ScopeIter si(scope); si; si++) {
        if (si.kind() == ScopeKind::Function) {
            JSFunction* fun = si.scope()->as<FunctionScope>().canonicalFunction();
            if (fun->isArrow())
                continue;
            allowNewTarget_ = true;
            allowSuperProperty_ = fun->allowSuperProperty();
            allowSuperCall_ = fun->isDerivedClassConstructor();
            return;
        }
    }
}

void
SharedContext::computeThisBinding(Scope* scope)
{
    for (ScopeIter si(scope); si; si++) {
        if (si.kind() == ScopeKind::Module) {
            thisBinding_ = ThisBinding::Module;
            return;
        }

        if (si.kind() == ScopeKind::Function) {
            JSFunction* fun = si.scope()->as<FunctionScope>().canonicalFunction();

            // Arrow functions and generator expression lambdas don't have
            // their own `this` binding.
            if (fun->isArrow() || fun->nonLazyScript()->isGeneratorExp())
                continue;

            // Derived class constructors (including nested arrow functions and
            // eval) need TDZ checks when accessing |this|.
            if (fun->isDerivedClassConstructor())
                needsThisTDZChecks_ = true;

            thisBinding_ = ThisBinding::Function;
            return;
        }
    }

    thisBinding_ = ThisBinding::Global;
}

void
SharedContext::computeInWith(Scope* scope)
{
    for (ScopeIter si(scope); si; si++) {
        if (si.kind() == ScopeKind::With) {
            inWith_ = true;
            break;
        }
    }
}

EvalSharedContext::EvalSharedContext(JSContext* cx, JSObject* enclosingEnv,
                                     Scope* enclosingScope, Directives directives,
                                     bool extraWarnings)
  : SharedContext(cx, Kind::Eval, directives, extraWarnings),
    enclosingScope_(cx, enclosingScope),
    bindings(cx)
{
    computeAllowSyntax(enclosingScope);
    computeInWith(enclosingScope);
    computeThisBinding(enclosingScope);

    // Like all things Debugger, Debugger.Frame.eval needs special
    // handling. Since the environment chain of such evals are non-syntactic
    // (DebuggerEnvironmentProxy is not an EnvironmentObject), computing the
    // this binding with respect to enclosingScope is incorrect if the
    // Debugger.Frame is a function frame. Recompute the this binding if we
    // are such an eval.
    if (enclosingEnv && enclosingScope->hasOnChain(ScopeKind::NonSyntactic)) {
        // For Debugger.Frame.eval with bindings, the environment chain may
        // have more than the DebugEnvironmentProxy.
        JSObject* env = enclosingEnv;
        while (env) {
            if (env->is<DebugEnvironmentProxy>())
                env = &env->as<DebugEnvironmentProxy>().environment();

            if (env->is<CallObject>()) {
                computeThisBinding(env->as<CallObject>().callee().nonLazyScript()->bodyScope());
                break;
            }

            env = env->enclosingEnvironment();
        }
    }
}

bool
ParseContext::init()
{
    if (scriptId_ == UINT32_MAX) {
        errorReporter_.reportErrorNoOffset(JSMSG_NEED_DIET, js_script_str);
        return false;
    }

    JSContext* cx = sc()->context;

    if (isFunctionBox()) {
        // Named lambdas always need a binding for their own name. If this
        // binding is closed over when we finish parsing the function in
        // finishExtraFunctionScopes, the function box needs to be marked as
        // needing a dynamic DeclEnv object.
        RootedFunction fun(cx, functionBox()->function());
        if (fun->isNamedLambda()) {
            if (!namedLambdaScope_->init(this))
                return false;
            AddDeclaredNamePtr p =
                namedLambdaScope_->lookupDeclaredNameForAdd(fun->explicitName());
            MOZ_ASSERT(!p);
            if (!namedLambdaScope_->addDeclaredName(this, p, fun->explicitName(),
                                                    DeclarationKind::Const,
                                                    DeclaredNameInfo::npos))
            {
                return false;
            }
        }

        if (!functionScope_->init(this))
            return false;

        if (!positionalFormalParameterNames_.acquire(cx))
            return false;
    }

    if (!closedOverBindingsForLazy_.acquire(cx))
        return false;

    return true;
}

bool
UsedNameTracker::noteUse(JSContext* cx, JSAtom* name, uint32_t scriptId, uint32_t scopeId)
{
    if (UsedNameMap::AddPtr p = map_.lookupForAdd(name)) {
        if (!p->value().noteUsedInScope(scriptId, scopeId))
            return false;
    } else {
        UsedNameInfo info(cx);
        if (!info.noteUsedInScope(scriptId, scopeId))
            return false;
        if (!map_.add(p, name, Move(info)))
            return false;
    }

    return true;
}

void
UsedNameTracker::UsedNameInfo::resetToScope(uint32_t scriptId, uint32_t scopeId)
{
    while (!uses_.empty()) {
        Use& innermost = uses_.back();
        if (innermost.scopeId < scopeId)
            break;
        MOZ_ASSERT(innermost.scriptId >= scriptId);
        uses_.popBack();
    }
}

void
UsedNameTracker::rewind(RewindToken token)
{
    scriptCounter_ = token.scriptId;
    scopeCounter_ = token.scopeId;

    for (UsedNameMap::Range r = map_.all(); !r.empty(); r.popFront())
        r.front().value().resetToScope(token.scriptId, token.scopeId);
}

FunctionBox::FunctionBox(JSContext* cx, LifoAlloc& alloc, ObjectBox* traceListHead,
                         JSFunction* fun, uint32_t toStringStart,
                         Directives directives, bool extraWarnings,
                         GeneratorKind generatorKind, FunctionAsyncKind asyncKind)
  : ObjectBox(fun, traceListHead),
    SharedContext(cx, Kind::FunctionBox, directives, extraWarnings),
    enclosingScope_(nullptr),
    namedLambdaBindings_(nullptr),
    functionScopeBindings_(nullptr),
    extraVarScopeBindings_(nullptr),
    functionNode(nullptr),
    bufStart(0),
    bufEnd(0),
    startLine(1),
    startColumn(0),
    toStringStart(toStringStart),
    toStringEnd(0),
    length(0),
    generatorKind_(GeneratorKindAsBit(generatorKind)),
    asyncKindBits_(AsyncKindAsBits(asyncKind)),
    isGenexpLambda(false),
    hasDestructuringArgs(false),
    hasParameterExprs(false),
    hasDirectEvalInParameterExpr(false),
    hasDuplicateParameters(false),
    useAsm(false),
    insideUseAsm(false),
    isAnnexB(false),
    wasEmitted(false),
    declaredArguments(false),
    usesArguments(false),
    usesApply(false),
    usesThis(false),
    usesReturn(false),
    hasRest_(false),
    isExprBody_(false),
    funCxFlags()
{
    // Functions created at parse time may be set singleton after parsing and
    // baked into JIT code, so they must be allocated tenured. They are held by
    // the JSScript so cannot be collected during a minor GC anyway.
    MOZ_ASSERT(fun->isTenured());
}

void
FunctionBox::initFromLazyFunction()
{
    JSFunction* fun = function();
    if (fun->lazyScript()->isDerivedClassConstructor())
        setDerivedClassConstructor();
    if (fun->lazyScript()->needsHomeObject())
        setNeedsHomeObject();
    enclosingScope_ = fun->lazyScript()->enclosingScope();
    initWithEnclosingScope(enclosingScope_);
}

void
FunctionBox::initStandaloneFunction(Scope* enclosingScope)
{
    // Standalone functions are Function or Generator constructors and are
    // always scoped to the global.
    MOZ_ASSERT(enclosingScope->is<GlobalScope>());
    enclosingScope_ = enclosingScope;
    allowNewTarget_ = true;
    thisBinding_ = ThisBinding::Function;
}

void
FunctionBox::initWithEnclosingParseContext(ParseContext* enclosing, FunctionSyntaxKind kind)
{
    SharedContext* sc = enclosing->sc();
    useAsm = sc->isFunctionBox() && sc->asFunctionBox()->useAsmOrInsideUseAsm();

    JSFunction* fun = function();

    // Arrow functions and generator expression lambdas don't have
    // their own `this` binding.
    if (fun->isArrow()) {
        allowNewTarget_ = sc->allowNewTarget();
        allowSuperProperty_ = sc->allowSuperProperty();
        allowSuperCall_ = sc->allowSuperCall();
        needsThisTDZChecks_ = sc->needsThisTDZChecks();
        thisBinding_ = sc->thisBinding();
    } else {
        allowNewTarget_ = true;
        allowSuperProperty_ = fun->allowSuperProperty();

        if (kind == ClassConstructor || kind == DerivedClassConstructor) {
            auto stmt = enclosing->findInnermostStatement<ParseContext::ClassStatement>();
            MOZ_ASSERT(stmt);
            stmt->constructorBox = this;

            if (kind == DerivedClassConstructor) {
                setDerivedClassConstructor();
                allowSuperCall_ = true;
                needsThisTDZChecks_ = true;
            }
        }

        if (isGenexpLambda)
            thisBinding_ = sc->thisBinding();
        else
            thisBinding_ = ThisBinding::Function;
    }

    if (sc->inWith()) {
        inWith_ = true;
    } else {
        auto isWith = [](ParseContext::Statement* stmt) {
            return stmt->kind() == StatementKind::With;
        };

        inWith_ = enclosing->findInnermostStatement(isWith);
    }
}

void
FunctionBox::initWithEnclosingScope(Scope* enclosingScope)
{
    if (!function()->isArrow()) {
        allowNewTarget_ = true;
        allowSuperProperty_ = function()->allowSuperProperty();

        if (isDerivedClassConstructor()) {
            setDerivedClassConstructor();
            allowSuperCall_ = true;
            needsThisTDZChecks_ = true;
        }

        thisBinding_ = ThisBinding::Function;
    } else {
        computeAllowSyntax(enclosingScope);
        computeThisBinding(enclosingScope);
    }

    computeInWith(enclosingScope);
}

void
ParserBase::error(unsigned errorNumber, ...)
{
    va_list args;
    va_start(args, errorNumber);

    ErrorMetadata metadata;
    if (tokenStream.computeErrorMetadata(&metadata, pos().begin))
        ReportCompileError(context, Move(metadata), nullptr, JSREPORT_ERROR, errorNumber, args);

    va_end(args);
}

void
ParserBase::errorWithNotes(UniquePtr<JSErrorNotes> notes, unsigned errorNumber, ...)
{
    va_list args;
    va_start(args, errorNumber);

    ErrorMetadata metadata;
    if (tokenStream.computeErrorMetadata(&metadata, pos().begin)) {
        ReportCompileError(context, Move(metadata), Move(notes), JSREPORT_ERROR, errorNumber,
                           args);
    }

    va_end(args);
}

void
ParserBase::errorAt(uint32_t offset, unsigned errorNumber, ...)
{
    va_list args;
    va_start(args, errorNumber);

    ErrorMetadata metadata;
    if (tokenStream.computeErrorMetadata(&metadata, offset))
        ReportCompileError(context, Move(metadata), nullptr, JSREPORT_ERROR, errorNumber, args);

    va_end(args);
}

void
ParserBase::errorWithNotesAt(UniquePtr<JSErrorNotes> notes, uint32_t offset,
                             unsigned errorNumber, ...)
{
    va_list args;
    va_start(args, errorNumber);

    ErrorMetadata metadata;
    if (tokenStream.computeErrorMetadata(&metadata, offset)) {
        ReportCompileError(context, Move(metadata), Move(notes), JSREPORT_ERROR, errorNumber,
                           args);
    }

    va_end(args);
}

bool
ParserBase::warning(unsigned errorNumber, ...)
{
    va_list args;
    va_start(args, errorNumber);

    ErrorMetadata metadata;
    bool result =
        tokenStream.computeErrorMetadata(&metadata, pos().begin) &&
        tokenStream.compileWarning(Move(metadata), nullptr, JSREPORT_WARNING, errorNumber, args);

    va_end(args);
    return result;
}

bool
ParserBase::warningAt(uint32_t offset, unsigned errorNumber, ...)
{
    va_list args;
    va_start(args, errorNumber);

    ErrorMetadata metadata;
    bool result = tokenStream.computeErrorMetadata(&metadata, offset);
    if (result) {
        result =
            tokenStream.compileWarning(Move(metadata), nullptr, JSREPORT_WARNING, errorNumber,
                                       args);
    }

    va_end(args);
    return result;
}

bool
ParserBase::extraWarning(unsigned errorNumber, ...)
{
    va_list args;
    va_start(args, errorNumber);

    bool result =
        tokenStream.reportExtraWarningErrorNumberVA(nullptr, pos().begin, errorNumber, args);

    va_end(args);
    return result;
}

bool
ParserBase::extraWarningAt(uint32_t offset, unsigned errorNumber, ...)
{
    va_list args;
    va_start(args, errorNumber);

    bool result =
        tokenStream.reportExtraWarningErrorNumberVA(nullptr, offset, errorNumber, args);

    va_end(args);
    return result;
}

bool
ParserBase::strictModeError(unsigned errorNumber, ...)
{
    va_list args;
    va_start(args, errorNumber);

    bool res =
        tokenStream.reportStrictModeErrorNumberVA(nullptr, pos().begin, pc->sc()->strict(),
                                                  errorNumber, args);

    va_end(args);
    return res;
}

bool
ParserBase::strictModeErrorAt(uint32_t offset, unsigned errorNumber, ...)
{
    va_list args;
    va_start(args, errorNumber);

    bool res =
        tokenStream.reportStrictModeErrorNumberVA(nullptr, offset, pc->sc()->strict(),
                                                  errorNumber, args);

    va_end(args);
    return res;
}

bool
ParserBase::reportNoOffset(ParseReportKind kind, bool strict, unsigned errorNumber, ...)
{
    va_list args;
    va_start(args, errorNumber);

    bool result = false;
    switch (kind) {
      case ParseError:
      case ParseWarning: {
        ErrorMetadata metadata;
        tokenStream.computeErrorMetadataNoOffset(&metadata);

        if (kind == ParseError) {
            ReportCompileError(context, Move(metadata), nullptr, JSREPORT_ERROR, errorNumber,
                               args);
            MOZ_ASSERT(!result);
        } else {
            result =
                tokenStream.compileWarning(Move(metadata), nullptr, JSREPORT_WARNING, errorNumber,
                                           args);
        }

        break;
      }
      case ParseExtraWarning:
        result = tokenStream.reportExtraWarningErrorNumberVA(nullptr, TokenStream::NoOffset,
                                                             errorNumber, args);
        break;
      case ParseStrictError:
        result = tokenStream.reportStrictModeErrorNumberVA(nullptr, TokenStream::NoOffset, strict,
                                                           errorNumber, args);
        break;
    }

    va_end(args);
    return result;
}

#define ABORTED_SYNTAX_PARSE_SENTINEL (SyntaxParser*)(0x1)

template <>
bool
Parser<FullParseHandler, char16_t>::hadAbortedSyntaxParse()
{
    return false;
}

template <>
bool
Parser<SyntaxParseHandler, char16_t>::hadAbortedSyntaxParse()
{
    return syntaxParser_ == ABORTED_SYNTAX_PARSE_SENTINEL;
}

template <>
void
Parser<FullParseHandler, char16_t>::clearAbortedSyntaxParse()
{
}

template <>
void
Parser<SyntaxParseHandler, char16_t>::clearAbortedSyntaxParse()
{
    syntaxParser_ = nullptr;
}

template <>
void
Parser<FullParseHandler, char16_t>::disableSyntaxParser()
{
    syntaxParser_ = nullptr;
}

template <>
void
Parser<SyntaxParseHandler, char16_t>::disableSyntaxParser()
{
}

template <>
inline bool
Parser<FullParseHandler, char16_t>::abortIfSyntaxParser()
{
    disableSyntaxParser();
    return true;
}

template <>
inline bool
Parser<SyntaxParseHandler, char16_t>::abortIfSyntaxParser()
{
    syntaxParser_ = ABORTED_SYNTAX_PARSE_SENTINEL;
    return false;
}

#undef ABORTED_SYNTAX_PARSE_SENTINEL

ParserBase::ParserBase(JSContext* cx, LifoAlloc& alloc,
                       const ReadOnlyCompileOptions& options,
                       const char16_t* chars, size_t length,
                       bool foldConstants,
                       UsedNameTracker& usedNames,
                       LazyScript* lazyOuterFunction)
  : context(cx),
    alloc(alloc),
    tokenStream(cx, options, chars, length, thisForCtor()),
    traceListHead(nullptr),
    pc(nullptr),
    usedNames(usedNames),
    ss(nullptr),
    keepAtoms(cx),
    foldConstants(foldConstants),
#ifdef DEBUG
    checkOptionsCalled(false),
#endif
    isUnexpectedEOF_(false),
    awaitHandling_(AwaitIsName)
{
    cx->frontendCollectionPool().addActiveCompilation();
    tempPoolMark = alloc.mark();
}

ParserBase::~ParserBase()
{
    alloc.release(tempPoolMark);

    /*
     * The parser can allocate enormous amounts of memory for large functions.
     * Eagerly free the memory now (which otherwise won't be freed until the
     * next GC) to avoid unnecessary OOMs.
     */
    alloc.freeAllIfHugeAndUnused();

    context->frontendCollectionPool().removeActiveCompilation();
}

template <class ParseHandler, typename CharT>
Parser<ParseHandler, CharT>::Parser(JSContext* cx, LifoAlloc& alloc,
                                    const ReadOnlyCompileOptions& options,
                                    const CharT* chars, size_t length,
                                    bool foldConstants,
                                    UsedNameTracker& usedNames,
                                    SyntaxParser* syntaxParser,
                                    LazyScript* lazyOuterFunction)
  : ParserBase(cx, alloc, options, chars, length, foldConstants, usedNames, lazyOuterFunction),
    AutoGCRooter(cx, PARSER),
    syntaxParser_(syntaxParser),
    handler(cx, alloc, lazyOuterFunction)
{
    // The Mozilla specific JSOPTION_EXTRA_WARNINGS option adds extra warnings
    // which are not generated if functions are parsed lazily. Note that the
    // standard "use strict" does not inhibit lazy parsing.
    if (options.extraWarningsOption)
        disableSyntaxParser();
}

template<class ParseHandler, typename CharT>
bool
Parser<ParseHandler, CharT>::checkOptions()
{
#ifdef DEBUG
    checkOptionsCalled = true;
#endif

    return tokenStream.checkOptions();
}

template <class ParseHandler, typename CharT>
Parser<ParseHandler, CharT>::~Parser()
{
    MOZ_ASSERT(checkOptionsCalled);
}

template <>
void
Parser<SyntaxParseHandler, char16_t>::setAwaitHandling(AwaitHandling awaitHandling)
{
    awaitHandling_ = awaitHandling;
}

template <>
void
Parser<FullParseHandler, char16_t>::setAwaitHandling(AwaitHandling awaitHandling)
{
    awaitHandling_ = awaitHandling;
    if (syntaxParser_)
        syntaxParser_->setAwaitHandling(awaitHandling);
}

ObjectBox*
ParserBase::newObjectBox(JSObject* obj)
{
    MOZ_ASSERT(obj);

    /*
     * We use JSContext.tempLifoAlloc to allocate parsed objects and place them
     * on a list in this Parser to ensure GC safety. Thus the tempLifoAlloc
     * arenas containing the entries must be alive until we are done with
     * scanning, parsing and code generation for the whole script or top-level
     * function.
     */

    ObjectBox* objbox = alloc.new_<ObjectBox>(obj, traceListHead);
    if (!objbox) {
        ReportOutOfMemory(context);
        return nullptr;
    }

    traceListHead = objbox;

    return objbox;
}

template <class ParseHandler, typename CharT>
FunctionBox*
Parser<ParseHandler, CharT>::newFunctionBox(Node fn, JSFunction* fun, uint32_t toStringStart,
                                            Directives inheritedDirectives,
                                            GeneratorKind generatorKind, FunctionAsyncKind asyncKind)
{
    MOZ_ASSERT(fun);

    /*
     * We use JSContext.tempLifoAlloc to allocate parsed objects and place them
     * on a list in this Parser to ensure GC safety. Thus the tempLifoAlloc
     * arenas containing the entries must be alive until we are done with
     * scanning, parsing and code generation for the whole script or top-level
     * function.
     */
    FunctionBox* funbox =
        alloc.new_<FunctionBox>(context, alloc, traceListHead, fun, toStringStart,
                                inheritedDirectives, options().extraWarningsOption,
                                generatorKind, asyncKind);
    if (!funbox) {
        ReportOutOfMemory(context);
        return nullptr;
    }

    traceListHead = funbox;
    if (fn)
        handler.setFunctionBox(fn, funbox);

    return funbox;
}

ModuleSharedContext::ModuleSharedContext(JSContext* cx, ModuleObject* module,
                                         Scope* enclosingScope, ModuleBuilder& builder)
  : SharedContext(cx, Kind::Module, Directives(true), false),
    module_(cx, module),
    enclosingScope_(cx, enclosingScope),
    bindings(cx),
    builder(builder)
{
    thisBinding_ = ThisBinding::Module;
}

template <class ParseHandler, typename CharT>
void
Parser<ParseHandler, CharT>::trace(JSTracer* trc)
{
    ObjectBox::TraceList(trc, traceListHead);
}

void
TraceParser(JSTracer* trc, AutoGCRooter* parser)
{
    static_cast<Parser<FullParseHandler, char16_t>*>(parser)->trace(trc);
}

/*
 * Parse a top-level JS script.
 */
template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::parse()
{
    MOZ_ASSERT(checkOptionsCalled);

    Directives directives(options().strictOption);
    GlobalSharedContext globalsc(context, ScopeKind::Global,
                                 directives, options().extraWarningsOption);
    SourceParseContext globalpc(this, &globalsc, /* newDirectives = */ nullptr);
    if (!globalpc.init())
        return null();

    ParseContext::VarScope varScope(this);
    if (!varScope.init(pc))
        return null();

    Node pn = statementList(YieldIsName);
    if (!pn)
        return null();

    TokenKind tt;
    if (!tokenStream.getToken(&tt, TokenStream::Operand))
        return null();
    if (tt != TOK_EOF) {
        error(JSMSG_GARBAGE_AFTER_INPUT, "script", TokenKindToDesc(tt));
        return null();
    }
    if (foldConstants) {
        if (!FoldConstants(context, &pn, this))
            return null();
    }

    return pn;
}

/*
 * Strict mode forbids introducing new definitions for 'eval', 'arguments',
 * 'let', 'static', 'yield', or for any strict mode reserved word.
 */
bool
ParserBase::isValidStrictBinding(PropertyName* name)
{
    TokenKind tt = ReservedWordTokenKind(name);
    if (tt == TOK_NAME) {
        return name != context->names().eval &&
               name != context->names().arguments;
    }
    return tt != TOK_LET &&
           tt != TOK_STATIC &&
           tt != TOK_YIELD &&
           !TokenKindIsStrictReservedWord(tt);
}

/*
 * Returns true if all parameter names are valid strict mode binding names and
 * no duplicate parameter names are present.
 */
bool
ParserBase::hasValidSimpleStrictParameterNames()
{
    MOZ_ASSERT(pc->isFunctionBox() && pc->functionBox()->hasSimpleParameterList());

    if (pc->functionBox()->hasDuplicateParameters)
        return false;

    for (auto* name : pc->positionalFormalParameterNames()) {
        MOZ_ASSERT(name);
        if (!isValidStrictBinding(name->asPropertyName()))
            return false;
    }
    return true;
}

template <class ParseHandler, typename CharT>
void
Parser<ParseHandler, CharT>::reportMissingClosing(unsigned errorNumber, unsigned noteNumber,
                                                  uint32_t openedPos)
{
    auto notes = MakeUnique<JSErrorNotes>();
    if (!notes) {
        ReportOutOfMemory(pc->sc()->context);
        return;
    }

    uint32_t line, column;
    tokenStream.srcCoords.lineNumAndColumnIndex(openedPos, &line, &column);

    const size_t MaxWidth = sizeof("4294967295");
    char columnNumber[MaxWidth];
    SprintfLiteral(columnNumber, "%" PRIu32, column);
    char lineNumber[MaxWidth];
    SprintfLiteral(lineNumber, "%" PRIu32, line);

    if (!notes->addNoteASCII(pc->sc()->context,
                             getFilename(), line, column,
                             GetErrorMessage, nullptr,
                             noteNumber, lineNumber, columnNumber))
    {
        return;
    }

    errorWithNotes(Move(notes), errorNumber);
}

template <class ParseHandler, typename CharT>
void
Parser<ParseHandler, CharT>::reportRedeclaration(HandlePropertyName name, DeclarationKind prevKind,
                                                 TokenPos pos, uint32_t prevPos)
{
    JSAutoByteString bytes;
    if (!AtomToPrintableString(context, name, &bytes))
        return;

    if (prevPos == DeclaredNameInfo::npos) {
        errorAt(pos.begin, JSMSG_REDECLARED_VAR, DeclarationKindString(prevKind), bytes.ptr());
        return;
    }

    auto notes = MakeUnique<JSErrorNotes>();
    if (!notes) {
        ReportOutOfMemory(pc->sc()->context);
        return;
    }

    uint32_t line, column;
    tokenStream.srcCoords.lineNumAndColumnIndex(prevPos, &line, &column);

    const size_t MaxWidth = sizeof("4294967295");
    char columnNumber[MaxWidth];
    SprintfLiteral(columnNumber, "%" PRIu32, column);
    char lineNumber[MaxWidth];
    SprintfLiteral(lineNumber, "%" PRIu32, line);

    if (!notes->addNoteASCII(pc->sc()->context,
                             getFilename(), line, column,
                             GetErrorMessage, nullptr,
                             JSMSG_REDECLARED_PREV,
                             lineNumber, columnNumber))
    {
        return;
    }

    errorWithNotesAt(Move(notes), pos.begin, JSMSG_REDECLARED_VAR,
                     DeclarationKindString(prevKind), bytes.ptr());
}

// notePositionalFormalParameter is called for both the arguments of a regular
// function definition and the arguments specified by the Function
// constructor.
//
// The 'disallowDuplicateParams' bool indicates whether the use of another
// feature (destructuring or default arguments) disables duplicate arguments.
// (ECMA-262 requires us to support duplicate parameter names, but, for newer
// features, we consider the code to have "opted in" to higher standards and
// forbid duplicates.)
template <class ParseHandler, typename CharT>
bool
Parser<ParseHandler, CharT>::notePositionalFormalParameter(Node fn, HandlePropertyName name,
                                                           uint32_t beginPos,
                                                           bool disallowDuplicateParams,
                                                           bool* duplicatedParam)
{
    if (AddDeclaredNamePtr p = pc->functionScope().lookupDeclaredNameForAdd(name)) {
        if (disallowDuplicateParams) {
            error(JSMSG_BAD_DUP_ARGS);
            return false;
        }

        // Strict-mode disallows duplicate args. We may not know whether we are
        // in strict mode or not (since the function body hasn't been parsed).
        // In such cases, report will queue up the potential error and return
        // 'true'.
        if (pc->sc()->needStrictChecks()) {
            JSAutoByteString bytes;
            if (!AtomToPrintableString(context, name, &bytes))
                return false;
            if (!strictModeError(JSMSG_DUPLICATE_FORMAL, bytes.ptr()))
                return false;
        }

        *duplicatedParam = true;
    } else {
        DeclarationKind kind = DeclarationKind::PositionalFormalParameter;
        if (!pc->functionScope().addDeclaredName(pc, p, name, kind, beginPos))
            return false;
    }

    if (!pc->positionalFormalParameterNames().append(name)) {
        ReportOutOfMemory(context);
        return false;
    }

    Node paramNode = newName(name);
    if (!paramNode)
        return false;

    handler.addFunctionFormalParameter(fn, paramNode);
    return true;
}

template <class ParseHandler, typename CharT>
bool
Parser<ParseHandler, CharT>::noteDestructuredPositionalFormalParameter(Node fn, Node destruct)
{
    // Append an empty name to the positional formals vector to keep track of
    // argument slots when making FunctionScope::Data.
    if (!pc->positionalFormalParameterNames().append(nullptr)) {
        ReportOutOfMemory(context);
        return false;
    }

    handler.addFunctionFormalParameter(fn, destruct);
    return true;
}

static bool
DeclarationKindIsVar(DeclarationKind kind)
{
    return kind == DeclarationKind::Var ||
           kind == DeclarationKind::BodyLevelFunction ||
           kind == DeclarationKind::VarForAnnexBLexicalFunction ||
           kind == DeclarationKind::ForOfVar;
}

Maybe<DeclarationKind>
ParseContext::isVarRedeclaredInEval(HandlePropertyName name, DeclarationKind kind)
{
    MOZ_ASSERT(DeclarationKindIsVar(kind));
    MOZ_ASSERT(sc()->isEvalContext());

    // In the case of eval, we also need to check enclosing VM scopes to see
    // if the var declaration is allowed in the context.
    //
    // This check is necessary in addition to
    // js::CheckEvalDeclarationConflicts because we only know during parsing
    // if a var is bound by for-of.
    js::Scope* enclosingScope = sc()->compilationEnclosingScope();
    js::Scope* varScope = EvalScope::nearestVarScopeForDirectEval(enclosingScope);
    MOZ_ASSERT(varScope);
    for (ScopeIter si(enclosingScope); si; si++) {
        for (js::BindingIter bi(si.scope()); bi; bi++) {
            if (bi.name() != name)
                continue;

            switch (bi.kind()) {
              case BindingKind::Let: {
                  // Annex B.3.5 allows redeclaring simple (non-destructured)
                  // catch parameters with var declarations, except when it
                  // appears in a for-of.
                  bool annexB35Allowance = si.kind() == ScopeKind::SimpleCatch &&
                                           kind != DeclarationKind::ForOfVar;
                  if (!annexB35Allowance) {
                      return Some(ScopeKindIsCatch(si.kind())
                                  ? DeclarationKind::CatchParameter
                                  : DeclarationKind::Let);
                  }
                  break;
              }

              case BindingKind::Const:
                return Some(DeclarationKind::Const);

              case BindingKind::Import:
              case BindingKind::FormalParameter:
              case BindingKind::Var:
              case BindingKind::NamedLambdaCallee:
                break;
            }
        }

        if (si.scope() == varScope)
            break;
    }

    return Nothing();
}

Maybe<DeclarationKind>
ParseContext::isVarRedeclaredInInnermostScope(HandlePropertyName name, DeclarationKind kind)
{
    Maybe<DeclarationKind> redeclaredKind;
    uint32_t unused;
    MOZ_ALWAYS_TRUE(tryDeclareVarHelper<DryRunInnermostScopeOnly>(name, kind,
                                                                  DeclaredNameInfo::npos,
                                                                  &redeclaredKind, &unused));
    return redeclaredKind;
}

bool
ParseContext::tryDeclareVar(HandlePropertyName name, DeclarationKind kind,
                            uint32_t beginPos, Maybe<DeclarationKind>* redeclaredKind,
                            uint32_t* prevPos)
{
    return tryDeclareVarHelper<NotDryRun>(name, kind, beginPos, redeclaredKind, prevPos);
}

static bool
DeclarationKindIsParameter(DeclarationKind kind)
{
    return kind == DeclarationKind::PositionalFormalParameter ||
           kind == DeclarationKind::FormalParameter;
}

template <ParseContext::DryRunOption dryRunOption>
bool
ParseContext::tryDeclareVarHelper(HandlePropertyName name, DeclarationKind kind,
                                  uint32_t beginPos, Maybe<DeclarationKind>* redeclaredKind,
                                  uint32_t* prevPos)
{
    MOZ_ASSERT(DeclarationKindIsVar(kind));

    // It is an early error if a 'var' declaration appears inside a
    // scope contour that has a lexical declaration of the same name. For
    // example, the following are early errors:
    //
    //   { let x; var x; }
    //   { { var x; } let x; }
    //
    // And the following are not:
    //
    //   { var x; var x; }
    //   { { let x; } var x; }

    for (ParseContext::Scope* scope = innermostScope();
         scope != varScope().enclosing();
         scope = scope->enclosing())
    {
        if (AddDeclaredNamePtr p = scope->lookupDeclaredNameForAdd(name)) {
            DeclarationKind declaredKind = p->value()->kind();
            if (DeclarationKindIsVar(declaredKind)) {
                // Any vars that are redeclared as body-level functions must
                // be recorded as body-level functions.
                //
                // In the case of global and eval scripts, GlobalDeclaration-
                // Instantiation [1] and EvalDeclarationInstantiation [2]
                // check for the declarability of global var and function
                // bindings via CanDeclareVar [3] and CanDeclareGlobal-
                // Function [4]. CanDeclareGlobalFunction is strictly more
                // restrictive than CanDeclareGlobalVar, so record the more
                // restrictive kind. These semantics are implemented in
                // CheckCanDeclareGlobalBinding.
                //
                // For a var previously declared as ForOfVar, this previous
                // DeclarationKind is used only to check for if the
                // 'arguments' binding should be declared. Since body-level
                // functions shadow 'arguments' [5], it is correct to alter
                // the kind to BodyLevelFunction. See
                // declareFunctionArgumentsObject.
                //
                // VarForAnnexBLexicalFunction declarations are declared when
                // the var scope exits. It is not possible for a var to be
                // previously declared as VarForAnnexBLexicalFunction and
                // checked for redeclaration.
                //
                // [1] ES 15.1.11
                // [2] ES 18.2.1.3
                // [3] ES 8.1.1.4.15
                // [4] ES 8.1.1.4.16
                // [5] ES 9.2.12
                if (dryRunOption == NotDryRun && kind == DeclarationKind::BodyLevelFunction) {
                    MOZ_ASSERT(declaredKind != DeclarationKind::VarForAnnexBLexicalFunction);
                    p->value()->alterKind(kind);
                }
            } else if (!DeclarationKindIsParameter(declaredKind)) {
                // Annex B.3.5 allows redeclaring simple (non-destructured)
                // catch parameters with var declarations, except when it
                // appears in a for-of.
                bool annexB35Allowance = declaredKind == DeclarationKind::SimpleCatchParameter &&
                                         kind != DeclarationKind::ForOfVar;

                // Annex B.3.3 allows redeclaring functions in the same block.
                bool annexB33Allowance = declaredKind == DeclarationKind::SloppyLexicalFunction &&
                                         kind == DeclarationKind::VarForAnnexBLexicalFunction &&
                                         scope == innermostScope();

                if (!annexB35Allowance && !annexB33Allowance) {
                    *redeclaredKind = Some(declaredKind);
                    *prevPos = p->value()->pos();
                    return true;
                }
            } else if (kind == DeclarationKind::VarForAnnexBLexicalFunction) {
                MOZ_ASSERT(DeclarationKindIsParameter(declaredKind));

                // Annex B.3.3.1 disallows redeclaring parameter names.
                // We don't need to set *prevPos here since this case is not
                // an error.
                *redeclaredKind = Some(declaredKind);
                return true;
            }
        } else if (dryRunOption == NotDryRun) {
            if (!scope->addDeclaredName(this, p, name, kind, beginPos))
                return false;
        }

        // DryRunOption is used for propagating Annex B functions: we don't
        // want to declare the synthesized Annex B vars until we exit the var
        // scope and know that no early errors would have occurred. In order
        // to avoid quadratic search, we only check for var redeclarations in
        // the innermost scope when doing a dry run.
        if (dryRunOption == DryRunInnermostScopeOnly)
            break;
    }

    if (!sc()->strict() && sc()->isEvalContext() &&
        (dryRunOption == NotDryRun || innermostScope() == &varScope()))
    {
        *redeclaredKind = isVarRedeclaredInEval(name, kind);
        // We don't have position information at runtime.
        *prevPos = DeclaredNameInfo::npos;
    }

    return true;
}

bool
ParseContext::annexBAppliesToLexicalFunctionInInnermostScope(FunctionBox* funbox)
{
    MOZ_ASSERT(!sc()->strict());

    RootedPropertyName name(sc()->context, funbox->function()->explicitName()->asPropertyName());
    Maybe<DeclarationKind> redeclaredKind =
        isVarRedeclaredInInnermostScope(name, DeclarationKind::VarForAnnexBLexicalFunction);

    if (!redeclaredKind && isFunctionBox()) {
        Scope& funScope = functionScope();
        if (&funScope != &varScope()) {
            // Annex B.3.3.1 disallows redeclaring parameter names. In the
            // presence of parameter expressions, parameter names are on the
            // function scope, which encloses the var scope. This means the
            // isVarRedeclaredInInnermostScope call above would not catch this
            // case, so test it manually.
            if (AddDeclaredNamePtr p = funScope.lookupDeclaredNameForAdd(name)) {
                DeclarationKind declaredKind = p->value()->kind();
                if (DeclarationKindIsParameter(declaredKind))
                    redeclaredKind = Some(declaredKind);
                else
                    MOZ_ASSERT(FunctionScope::isSpecialName(sc()->context, name));
            }
        }
    }

    // If an early error would have occurred already, this function should not
    // exhibit Annex B.3.3 semantics.
    return !redeclaredKind;
}

template <class ParseHandler, typename CharT>
bool
Parser<ParseHandler, CharT>::checkLexicalDeclarationDirectlyWithinBlock(ParseContext::Statement& stmt,
                                                                        DeclarationKind kind,
                                                                        TokenPos pos)
{
    MOZ_ASSERT(DeclarationKindIsLexical(kind));

    // It is an early error to declare a lexical binding not directly
    // within a block.
    if (!StatementKindIsBraced(stmt.kind()) &&
        stmt.kind() != StatementKind::ForLoopLexicalHead)
    {
        errorAt(pos.begin,
                stmt.kind() == StatementKind::Label
                ? JSMSG_LEXICAL_DECL_LABEL
                : JSMSG_LEXICAL_DECL_NOT_IN_BLOCK,
                DeclarationKindString(kind));
        return false;
    }

    return true;
}

template <class ParseHandler, typename CharT>
bool
Parser<ParseHandler, CharT>::noteDeclaredName(HandlePropertyName name, DeclarationKind kind,
                                              TokenPos pos)
{
    // The asm.js validator does all its own symbol-table management so, as an
    // optimization, avoid doing any work here.
    if (pc->useAsmOrInsideUseAsm())
        return true;

    switch (kind) {
      case DeclarationKind::Var:
      case DeclarationKind::BodyLevelFunction:
      case DeclarationKind::ForOfVar: {
        Maybe<DeclarationKind> redeclaredKind;
        uint32_t prevPos;
        if (!pc->tryDeclareVar(name, kind, pos.begin, &redeclaredKind, &prevPos))
            return false;

        if (redeclaredKind) {
            reportRedeclaration(name, *redeclaredKind, pos, prevPos);
            return false;
        }

        break;
      }

      case DeclarationKind::ModuleBodyLevelFunction: {
          MOZ_ASSERT(pc->atModuleLevel());

          AddDeclaredNamePtr p = pc->varScope().lookupDeclaredNameForAdd(name);
          if (p) {
              reportRedeclaration(name, p->value()->kind(), pos, p->value()->pos());
              return false;
          }

          if (!pc->varScope().addDeclaredName(pc, p, name, kind, pos.begin))
              return false;

          // Body-level functions in modules are always closed over.
          pc->varScope().lookupDeclaredName(name)->value()->setClosedOver();

          break;
      }

      case DeclarationKind::FormalParameter: {
        // It is an early error if any non-positional formal parameter name
        // (e.g., destructuring formal parameter) is duplicated.

        AddDeclaredNamePtr p = pc->functionScope().lookupDeclaredNameForAdd(name);
        if (p) {
            error(JSMSG_BAD_DUP_ARGS);
            return false;
        }

        if (!pc->functionScope().addDeclaredName(pc, p, name, kind, pos.begin))
            return false;

        break;
      }

      case DeclarationKind::LexicalFunction: {
        ParseContext::Scope* scope = pc->innermostScope();
        AddDeclaredNamePtr p = scope->lookupDeclaredNameForAdd(name);
        if (p) {
            reportRedeclaration(name, p->value()->kind(), pos, p->value()->pos());
            return false;
        }

        if (!scope->addDeclaredName(pc, p, name, kind, pos.begin))
            return false;

        break;
      }

      case DeclarationKind::SloppyLexicalFunction: {
        // Functions in block have complex allowances in sloppy mode for being
        // labelled that other lexical declarations do not have. Those checks
        // are more complex than calling checkLexicalDeclarationDirectlyWithin-
        // Block and are done in checkFunctionDefinition.

        ParseContext::Scope* scope = pc->innermostScope();
        if (AddDeclaredNamePtr p = scope->lookupDeclaredNameForAdd(name)) {
            // It is usually an early error if there is another declaration
            // with the same name in the same scope.
            //
            // Sloppy lexical functions may redeclare other sloppy lexical
            // functions for web compatibility reasons.
            if (p->value()->kind() != DeclarationKind::SloppyLexicalFunction) {
                reportRedeclaration(name, p->value()->kind(), pos, p->value()->pos());
                return false;
            }
        } else {
            if (!scope->addDeclaredName(pc, p, name, kind, pos.begin))
                return false;
        }

        break;
      }

      case DeclarationKind::Let:
      case DeclarationKind::Const:
      case DeclarationKind::Class:
        // The BoundNames of LexicalDeclaration and ForDeclaration must not
        // contain 'let'. (CatchParameter is the only lexical binding form
        // without this restriction.)
        if (name == context->names().let) {
            errorAt(pos.begin, JSMSG_LEXICAL_DECL_DEFINES_LET);
            return false;
        }

        MOZ_FALLTHROUGH;

      case DeclarationKind::Import:
        // Module code is always strict, so 'let' is always a keyword and never a name.
        MOZ_ASSERT(name != context->names().let);
        MOZ_FALLTHROUGH;

      case DeclarationKind::SimpleCatchParameter:
      case DeclarationKind::CatchParameter: {
        if (ParseContext::Statement* stmt = pc->innermostStatement()) {
            if (!checkLexicalDeclarationDirectlyWithinBlock(*stmt, kind, pos))
                return false;
        }

        ParseContext::Scope* scope = pc->innermostScope();

        // For body-level lexically declared names in a function, it is an
        // early error if there is a formal parameter of the same name. This
        // needs a special check if there is an extra var scope due to
        // parameter expressions.
        if (pc->isFunctionExtraBodyVarScopeInnermost()) {
            DeclaredNamePtr p = pc->functionScope().lookupDeclaredName(name);
            if (p && DeclarationKindIsParameter(p->value()->kind())) {
                reportRedeclaration(name, p->value()->kind(), pos, p->value()->pos());
                return false;
            }
        }

        // It is an early error if there is another declaration with the same
        // name in the same scope.
        AddDeclaredNamePtr p = scope->lookupDeclaredNameForAdd(name);
        if (p) {
            reportRedeclaration(name, p->value()->kind(), pos, p->value()->pos());
            return false;
        }

        if (!scope->addDeclaredName(pc, p, name, kind, pos.begin))
            return false;

        break;
      }

      case DeclarationKind::CoverArrowParameter:
        // CoverArrowParameter is only used as a placeholder declaration kind.
        break;

      case DeclarationKind::PositionalFormalParameter:
        MOZ_CRASH("Positional formal parameter names should use "
                  "notePositionalFormalParameter");
        break;

      case DeclarationKind::VarForAnnexBLexicalFunction:
        MOZ_CRASH("Synthesized Annex B vars should go through "
                  "tryDeclareVarForAnnexBLexicalFunction");
        break;
    }

    return true;
}

template <class ParseHandler, typename CharT>
bool
Parser<ParseHandler, CharT>::noteUsedName(HandlePropertyName name)
{
    // If the we are delazifying, the LazyScript already has all the
    // closed-over info for bindings and there's no need to track used names.
    if (handler.canSkipLazyClosedOverBindings())
        return true;

    // The asm.js validator does all its own symbol-table management so, as an
    // optimization, avoid doing any work here.
    if (pc->useAsmOrInsideUseAsm())
        return true;

    // Global bindings are properties and not actual bindings; we don't need
    // to know if they are closed over. So no need to track used name at the
    // global scope. It is not incorrect to track them, this is an
    // optimization.
    ParseContext::Scope* scope = pc->innermostScope();
    if (pc->sc()->isGlobalContext() && scope == &pc->varScope())
        return true;

    return usedNames.noteUse(context, name, pc->scriptId(), scope->id());
}

template <class ParseHandler, typename CharT>
bool
Parser<ParseHandler, CharT>::hasUsedName(HandlePropertyName name)
{
    if (UsedNamePtr p = usedNames.lookup(name))
        return p->value().isUsedInScript(pc->scriptId());
    return false;
}

template <class ParseHandler, typename CharT>
bool
Parser<ParseHandler, CharT>::propagateFreeNamesAndMarkClosedOverBindings(ParseContext::Scope& scope)
{
    // Now that we have all the declared names in the scope, check which
    // functions should exhibit Annex B semantics.
    if (!scope.propagateAndMarkAnnexBFunctionBoxes(pc))
        return false;

    if (handler.canSkipLazyClosedOverBindings()) {
        // Scopes are nullptr-delimited in the LazyScript closed over bindings
        // array.
        while (JSAtom* name = handler.nextLazyClosedOverBinding())
            scope.lookupDeclaredName(name)->value()->setClosedOver();
        return true;
    }

    bool isSyntaxParser = mozilla::IsSame<ParseHandler, SyntaxParseHandler>::value;
    uint32_t scriptId = pc->scriptId();
    uint32_t scopeId = scope.id();
    for (BindingIter bi = scope.bindings(pc); bi; bi++) {
        if (UsedNamePtr p = usedNames.lookup(bi.name())) {
            bool closedOver;
            p->value().noteBoundInScope(scriptId, scopeId, &closedOver);
            if (closedOver) {
                bi.setClosedOver();

                if (isSyntaxParser && !pc->closedOverBindingsForLazy().append(bi.name())) {
                    ReportOutOfMemory(context);
                    return false;
                }
            }
        }
    }

    // Append a nullptr to denote end-of-scope.
    if (isSyntaxParser && !pc->closedOverBindingsForLazy().append(nullptr)) {
        ReportOutOfMemory(context);
        return false;
    }

    return true;
}

template <>
bool
Parser<FullParseHandler, char16_t>::checkStatementsEOF()
{
    // This is designed to be paired with parsing a statement list at the top
    // level.
    //
    // The statementList() call breaks on TOK_RC, so make sure we've
    // reached EOF here.
    TokenKind tt;
    if (!tokenStream.peekToken(&tt, TokenStream::Operand))
        return false;
    if (tt != TOK_EOF) {
        error(JSMSG_UNEXPECTED_TOKEN, "expression", TokenKindToDesc(tt));
        return false;
    }
    return true;
}

template <typename Scope>
static typename Scope::Data*
NewEmptyBindingData(JSContext* cx, LifoAlloc& alloc, uint32_t numBindings)
{
    size_t allocSize = Scope::sizeOfData(numBindings);
    typename Scope::Data* bindings = static_cast<typename Scope::Data*>(alloc.alloc(allocSize));
    if (!bindings) {
        ReportOutOfMemory(cx);
        return nullptr;
    }
    PodZero(bindings);
    return bindings;
}

Maybe<GlobalScope::Data*>
ParserBase::newGlobalScopeData(ParseContext::Scope& scope)
{
    Vector<BindingName> funs(context);
    Vector<BindingName> vars(context);
    Vector<BindingName> lets(context);
    Vector<BindingName> consts(context);

    bool allBindingsClosedOver = pc->sc()->allBindingsClosedOver();
    for (BindingIter bi = scope.bindings(pc); bi; bi++) {
        BindingName binding(bi.name(), allBindingsClosedOver || bi.closedOver());
        switch (bi.kind()) {
          case BindingKind::Var:
            if (bi.declarationKind() == DeclarationKind::BodyLevelFunction) {
                if (!funs.append(binding))
                    return Nothing();
            } else {
                if (!vars.append(binding))
                    return Nothing();
            }
            break;
          case BindingKind::Let:
            if (!lets.append(binding))
                return Nothing();
            break;
          case BindingKind::Const:
            if (!consts.append(binding))
                return Nothing();
            break;
          default:
            MOZ_CRASH("Bad global scope BindingKind");
        }
    }

    GlobalScope::Data* bindings = nullptr;
    uint32_t numBindings = funs.length() + vars.length() + lets.length() + consts.length();

    if (numBindings > 0) {
        bindings = NewEmptyBindingData<GlobalScope>(context, alloc, numBindings);
        if (!bindings)
            return Nothing();

        // The ordering here is important. See comments in GlobalScope.
        BindingName* start = bindings->names;
        BindingName* cursor = start;

        PodCopy(cursor, funs.begin(), funs.length());
        cursor += funs.length();

        bindings->varStart = cursor - start;
        PodCopy(cursor, vars.begin(), vars.length());
        cursor += vars.length();

        bindings->letStart = cursor - start;
        PodCopy(cursor, lets.begin(), lets.length());
        cursor += lets.length();

        bindings->constStart = cursor - start;
        PodCopy(cursor, consts.begin(), consts.length());
        bindings->length = numBindings;
    }

    return Some(bindings);
}

Maybe<ModuleScope::Data*>
ParserBase::newModuleScopeData(ParseContext::Scope& scope)
{
    Vector<BindingName> imports(context);
    Vector<BindingName> vars(context);
    Vector<BindingName> lets(context);
    Vector<BindingName> consts(context);

    bool allBindingsClosedOver = pc->sc()->allBindingsClosedOver();
    for (BindingIter bi = scope.bindings(pc); bi; bi++) {
        // Imports are indirect bindings and must not be given known slots.
        BindingName binding(bi.name(), (allBindingsClosedOver || bi.closedOver()) &&
                                       bi.kind() != BindingKind::Import);
        switch (bi.kind()) {
          case BindingKind::Import:
            if (!imports.append(binding))
                return Nothing();
            break;
          case BindingKind::Var:
            if (!vars.append(binding))
                return Nothing();
            break;
          case BindingKind::Let:
            if (!lets.append(binding))
                return Nothing();
            break;
          case BindingKind::Const:
            if (!consts.append(binding))
                return Nothing();
            break;
          default:
            MOZ_CRASH("Bad module scope BindingKind");
        }
    }

    ModuleScope::Data* bindings = nullptr;
    uint32_t numBindings = imports.length() + vars.length() + lets.length() + consts.length();

    if (numBindings > 0) {
        bindings = NewEmptyBindingData<ModuleScope>(context, alloc, numBindings);
        if (!bindings)
            return Nothing();

        // The ordering here is important. See comments in ModuleScope.
        BindingName* start = bindings->names;
        BindingName* cursor = start;

        PodCopy(cursor, imports.begin(), imports.length());
        cursor += imports.length();

        bindings->varStart = cursor - start;
        PodCopy(cursor, vars.begin(), vars.length());
        cursor += vars.length();

        bindings->letStart = cursor - start;
        PodCopy(cursor, lets.begin(), lets.length());
        cursor += lets.length();

        bindings->constStart = cursor - start;
        PodCopy(cursor, consts.begin(), consts.length());
        bindings->length = numBindings;
    }

    return Some(bindings);
}

Maybe<EvalScope::Data*>
ParserBase::newEvalScopeData(ParseContext::Scope& scope)
{
    Vector<BindingName> funs(context);
    Vector<BindingName> vars(context);

    for (BindingIter bi = scope.bindings(pc); bi; bi++) {
        // Eval scopes only contain 'var' bindings. Make all bindings aliased
        // for now.
        MOZ_ASSERT(bi.kind() == BindingKind::Var);
        BindingName binding(bi.name(), true);
        if (bi.declarationKind() == DeclarationKind::BodyLevelFunction) {
            if (!funs.append(binding))
                return Nothing();
        } else {
            if (!vars.append(binding))
                return Nothing();
        }
    }

    EvalScope::Data* bindings = nullptr;
    uint32_t numBindings = funs.length() + vars.length();

    if (numBindings > 0) {
        bindings = NewEmptyBindingData<EvalScope>(context, alloc, numBindings);
        if (!bindings)
            return Nothing();

        BindingName* start = bindings->names;
        BindingName* cursor = start;

        // Keep track of what vars are functions. This is only used in BCE to omit
        // superfluous DEFVARs.
        PodCopy(cursor, funs.begin(), funs.length());
        cursor += funs.length();

        bindings->varStart = cursor - start;
        PodCopy(cursor, vars.begin(), vars.length());
        bindings->length = numBindings;
    }

    return Some(bindings);
}

Maybe<FunctionScope::Data*>
ParserBase::newFunctionScopeData(ParseContext::Scope& scope, bool hasParameterExprs)
{
    Vector<BindingName> positionalFormals(context);
    Vector<BindingName> formals(context);
    Vector<BindingName> vars(context);

    bool allBindingsClosedOver = pc->sc()->allBindingsClosedOver();
    bool hasDuplicateParams = pc->functionBox()->hasDuplicateParameters;

    // Positional parameter names must be added in order of appearance as they are
    // referenced using argument slots.
    for (size_t i = 0; i < pc->positionalFormalParameterNames().length(); i++) {
        JSAtom* name = pc->positionalFormalParameterNames()[i];

        BindingName bindName;
        if (name) {
            DeclaredNamePtr p = scope.lookupDeclaredName(name);

            // Do not consider any positional formal parameters closed over if
            // there are parameter defaults. It is the binding in the defaults
            // scope that is closed over instead.
            bool closedOver = allBindingsClosedOver ||
                              (p && p->value()->closedOver());

            // If the parameter name has duplicates, only the final parameter
            // name should be on the environment, as otherwise the environment
            // object would have multiple, same-named properties.
            if (hasDuplicateParams) {
                for (size_t j = pc->positionalFormalParameterNames().length() - 1; j > i; j--) {
                    if (pc->positionalFormalParameterNames()[j] == name) {
                        closedOver = false;
                        break;
                    }
                }
            }

            bindName = BindingName(name, closedOver);
        }

        if (!positionalFormals.append(bindName))
            return Nothing();
    }

    for (BindingIter bi = scope.bindings(pc); bi; bi++) {
        BindingName binding(bi.name(), allBindingsClosedOver || bi.closedOver());
        switch (bi.kind()) {
          case BindingKind::FormalParameter:
            // Positional parameter names are already handled above.
            if (bi.declarationKind() == DeclarationKind::FormalParameter) {
                if (!formals.append(binding))
                    return Nothing();
            }
            break;
          case BindingKind::Var:
            // The only vars in the function scope when there are parameter
            // exprs, which induces a separate var environment, should be the
            // special bindings.
            MOZ_ASSERT_IF(hasParameterExprs, FunctionScope::isSpecialName(context, bi.name()));
            if (!vars.append(binding))
                return Nothing();
            break;
          default:
            break;
        }
    }

    FunctionScope::Data* bindings = nullptr;
    uint32_t numBindings = positionalFormals.length() + formals.length() + vars.length();

    if (numBindings > 0) {
        bindings = NewEmptyBindingData<FunctionScope>(context, alloc, numBindings);
        if (!bindings)
            return Nothing();

        // The ordering here is important. See comments in FunctionScope.
        BindingName* start = bindings->names;
        BindingName* cursor = start;

        PodCopy(cursor, positionalFormals.begin(), positionalFormals.length());
        cursor += positionalFormals.length();

        bindings->nonPositionalFormalStart = cursor - start;
        PodCopy(cursor, formals.begin(), formals.length());
        cursor += formals.length();

        bindings->varStart = cursor - start;
        PodCopy(cursor, vars.begin(), vars.length());
        bindings->length = numBindings;
    }

    return Some(bindings);
}

Maybe<VarScope::Data*>
ParserBase::newVarScopeData(ParseContext::Scope& scope)
{
    Vector<BindingName> vars(context);

    bool allBindingsClosedOver = pc->sc()->allBindingsClosedOver();

    for (BindingIter bi = scope.bindings(pc); bi; bi++) {
        BindingName binding(bi.name(), allBindingsClosedOver || bi.closedOver());
        if (!vars.append(binding))
            return Nothing();
    }

    VarScope::Data* bindings = nullptr;
    uint32_t numBindings = vars.length();

    if (numBindings > 0) {
        bindings = NewEmptyBindingData<VarScope>(context, alloc, numBindings);
        if (!bindings)
            return Nothing();

        // The ordering here is important. See comments in FunctionScope.
        BindingName* start = bindings->names;
        BindingName* cursor = start;

        PodCopy(cursor, vars.begin(), vars.length());
        bindings->length = numBindings;
    }

    return Some(bindings);
}

Maybe<LexicalScope::Data*>
ParserBase::newLexicalScopeData(ParseContext::Scope& scope)
{
    Vector<BindingName> lets(context);
    Vector<BindingName> consts(context);

    // Unlike other scopes with bindings which are body-level, it is unknown
    // if pc->sc()->allBindingsClosedOver() is correct at the time of
    // finishing parsing a lexical scope.
    //
    // Instead, pc->sc()->allBindingsClosedOver() is checked in
    // EmitterScope::enterLexical. Also see comment there.
    for (BindingIter bi = scope.bindings(pc); bi; bi++) {
        BindingName binding(bi.name(), bi.closedOver());
        switch (bi.kind()) {
          case BindingKind::Let:
            if (!lets.append(binding))
                return Nothing();
            break;
          case BindingKind::Const:
            if (!consts.append(binding))
                return Nothing();
            break;
          default:
            break;
        }
    }

    LexicalScope::Data* bindings = nullptr;
    uint32_t numBindings = lets.length() + consts.length();

    if (numBindings > 0) {
        bindings = NewEmptyBindingData<LexicalScope>(context, alloc, numBindings);
        if (!bindings)
            return Nothing();

        // The ordering here is important. See comments in LexicalScope.
        BindingName* cursor = bindings->names;
        BindingName* start = cursor;

        PodCopy(cursor, lets.begin(), lets.length());
        cursor += lets.length();

        bindings->constStart = cursor - start;
        PodCopy(cursor, consts.begin(), consts.length());
        bindings->length = numBindings;
    }

    return Some(bindings);
}

template <>
SyntaxParseHandler::Node
Parser<SyntaxParseHandler, char16_t>::finishLexicalScope(ParseContext::Scope& scope, Node body)
{
    if (!propagateFreeNamesAndMarkClosedOverBindings(scope))
        return null();
    return body;
}

template <>
ParseNode*
Parser<FullParseHandler, char16_t>::finishLexicalScope(ParseContext::Scope& scope, ParseNode* body)
{
    if (!propagateFreeNamesAndMarkClosedOverBindings(scope))
        return nullptr;
    Maybe<LexicalScope::Data*> bindings = newLexicalScopeData(scope);
    if (!bindings)
        return nullptr;
    return handler.newLexicalScope(*bindings, body);
}

template <>
ParseNode*
Parser<FullParseHandler, char16_t>::evalBody(EvalSharedContext* evalsc)
{
    SourceParseContext evalpc(this, evalsc, /* newDirectives = */ nullptr);
    if (!evalpc.init())
        return nullptr;

    ParseContext::VarScope varScope(this);
    if (!varScope.init(pc))
        return nullptr;

    ParseNode* body;
    {
        // All evals have an implicit non-extensible lexical scope.
        ParseContext::Scope lexicalScope(this);
        if (!lexicalScope.init(pc))
            return nullptr;

        body = statementList(YieldIsName);
        if (!body)
            return nullptr;

        if (!checkStatementsEOF())
            return nullptr;

        body = finishLexicalScope(lexicalScope, body);
        if (!body)
            return nullptr;
    }

#ifdef DEBUG
    if (evalpc.superScopeNeedsHomeObject() && evalsc->compilationEnclosingScope()) {
        // If superScopeNeedsHomeObject_ is set and we are an entry-point
        // ParseContext, then we must be emitting an eval script, and the
        // outer function must already be marked as needing a home object
        // since it contains an eval.
        ScopeIter si(evalsc->compilationEnclosingScope());
        for (; si; si++) {
            if (si.kind() == ScopeKind::Function) {
                JSFunction* fun = si.scope()->as<FunctionScope>().canonicalFunction();
                if (fun->isArrow())
                    continue;
                MOZ_ASSERT(fun->allowSuperProperty());
                MOZ_ASSERT(fun->nonLazyScript()->needsHomeObject());
                break;
            }
        }
        MOZ_ASSERT(!si.done(),
                   "Eval must have found an enclosing function box scope that allows super.property");
    }
#endif

    if (!FoldConstants(context, &body, this))
        return nullptr;

    // For eval scripts, since all bindings are automatically considered
    // closed over, we don't need to call propagateFreeNamesAndMarkClosed-
    // OverBindings. However, Annex B.3.3 functions still need to be marked.
    if (!varScope.propagateAndMarkAnnexBFunctionBoxes(pc))
        return nullptr;

    Maybe<EvalScope::Data*> bindings = newEvalScopeData(pc->varScope());
    if (!bindings)
        return nullptr;
    evalsc->bindings = *bindings;

    return body;
}

template <>
ParseNode*
Parser<FullParseHandler, char16_t>::globalBody(GlobalSharedContext* globalsc)
{
    SourceParseContext globalpc(this, globalsc, /* newDirectives = */ nullptr);
    if (!globalpc.init())
        return nullptr;

    ParseContext::VarScope varScope(this);
    if (!varScope.init(pc))
        return nullptr;

    ParseNode* body = statementList(YieldIsName);
    if (!body)
        return nullptr;

    if (!checkStatementsEOF())
        return nullptr;

    if (!FoldConstants(context, &body, this))
        return nullptr;

    // For global scripts, whether bindings are closed over or not doesn't
    // matter, so no need to call propagateFreeNamesAndMarkClosedOver-
    // Bindings. However, Annex B.3.3 functions still need to be marked.
    if (!varScope.propagateAndMarkAnnexBFunctionBoxes(pc))
        return nullptr;

    Maybe<GlobalScope::Data*> bindings = newGlobalScopeData(pc->varScope());
    if (!bindings)
        return nullptr;
    globalsc->bindings = *bindings;

    return body;
}

template <>
ParseNode*
Parser<FullParseHandler, char16_t>::moduleBody(ModuleSharedContext* modulesc)
{
    MOZ_ASSERT(checkOptionsCalled);

    SourceParseContext modulepc(this, modulesc, nullptr);
    if (!modulepc.init())
        return null();

    ParseContext::VarScope varScope(this);
    if (!varScope.init(pc))
        return nullptr;

    Node mn = handler.newModule(pos());
    if (!mn)
        return null();

    AutoAwaitIsKeyword<Parser> awaitIsKeyword(this, AwaitIsModuleKeyword);
    ParseNode* pn = statementList(YieldIsName);
    if (!pn)
        return null();

    MOZ_ASSERT(pn->isKind(PNK_STATEMENTLIST));
    mn->pn_body = pn;

    TokenKind tt;
    if (!tokenStream.getToken(&tt, TokenStream::Operand))
        return null();
    if (tt != TOK_EOF) {
        error(JSMSG_GARBAGE_AFTER_INPUT, "module", TokenKindToDesc(tt));
        return null();
    }

    if (!modulesc->builder.buildTables())
        return null();

    // Check exported local bindings exist and mark them as closed over.
    for (auto entry : modulesc->builder.localExportEntries()) {
        JSAtom* name = entry->localName();
        MOZ_ASSERT(name);

        DeclaredNamePtr p = modulepc.varScope().lookupDeclaredName(name);
        if (!p) {
            JSAutoByteString str;
            if (!AtomToPrintableString(context, name, &str))
                return null();

            errorAt(TokenStream::NoOffset, JSMSG_MISSING_EXPORT, str.ptr());
            return null();
        }

        p->value()->setClosedOver();
    }

    if (!FoldConstants(context, &pn, this))
        return null();

    if (!propagateFreeNamesAndMarkClosedOverBindings(modulepc.varScope()))
        return null();

    Maybe<ModuleScope::Data*> bindings = newModuleScopeData(modulepc.varScope());
    if (!bindings)
        return nullptr;

    modulesc->bindings = *bindings;
    return mn;
}

template <>
SyntaxParseHandler::Node
Parser<SyntaxParseHandler, char16_t>::moduleBody(ModuleSharedContext* modulesc)
{
    MOZ_ALWAYS_FALSE(abortIfSyntaxParser());
    return SyntaxParseHandler::NodeFailure;
}

template <class ParseHandler, typename CharT>
bool
Parser<ParseHandler, CharT>::hasUsedFunctionSpecialName(HandlePropertyName name)
{
    MOZ_ASSERT(name == context->names().arguments || name == context->names().dotThis);
    return hasUsedName(name) || pc->functionBox()->bindingsAccessedDynamically();
}

template <class ParseHandler, typename CharT>
bool
Parser<ParseHandler, CharT>::declareFunctionThis()
{
    // The asm.js validator does all its own symbol-table management so, as an
    // optimization, avoid doing any work here.
    if (pc->useAsmOrInsideUseAsm())
        return true;

    // Derived class constructors emit JSOP_CHECKRETURN, which requires
    // '.this' to be bound.
    FunctionBox* funbox = pc->functionBox();
    HandlePropertyName dotThis = context->names().dotThis;

    bool declareThis;
    if (handler.canSkipLazyClosedOverBindings())
        declareThis = funbox->function()->lazyScript()->hasThisBinding();
    else
        declareThis = hasUsedFunctionSpecialName(dotThis) || funbox->isDerivedClassConstructor();

    if (declareThis) {
        ParseContext::Scope& funScope = pc->functionScope();
        AddDeclaredNamePtr p = funScope.lookupDeclaredNameForAdd(dotThis);
        MOZ_ASSERT(!p);
        if (!funScope.addDeclaredName(pc, p, dotThis, DeclarationKind::Var,
                                      DeclaredNameInfo::npos))
        {
            return false;
        }
        funbox->setHasThisBinding();
    }

    return true;
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::newInternalDotName(HandlePropertyName name)
{
    Node nameNode = newName(name);
    if (!nameNode)
        return null();
    if (!noteUsedName(name))
        return null();
    return nameNode;
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::newThisName()
{
    return newInternalDotName(context->names().dotThis);
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::newDotGeneratorName()
{
    return newInternalDotName(context->names().dotGenerator);
}

template <class ParseHandler, typename CharT>
bool
Parser<ParseHandler, CharT>::declareDotGeneratorName()
{
    // The special '.generator' binding must be on the function scope, as
    // generators expect to find it on the CallObject.
    ParseContext::Scope& funScope = pc->functionScope();
    HandlePropertyName dotGenerator = context->names().dotGenerator;
    AddDeclaredNamePtr p = funScope.lookupDeclaredNameForAdd(dotGenerator);
    if (!p && !funScope.addDeclaredName(pc, p, dotGenerator, DeclarationKind::Var,
                                        DeclaredNameInfo::npos))
    {
        return false;
    }
    return true;
}

template <class ParseHandler, typename CharT>
bool
Parser<ParseHandler, CharT>::finishFunctionScopes(bool isStandaloneFunction)
{
    FunctionBox* funbox = pc->functionBox();

    if (funbox->hasParameterExprs) {
        if (!propagateFreeNamesAndMarkClosedOverBindings(pc->functionScope()))
            return false;
    }

    if (funbox->function()->isNamedLambda() && !isStandaloneFunction) {
        if (!propagateFreeNamesAndMarkClosedOverBindings(pc->namedLambdaScope()))
            return false;
    }

    return true;
}

template <>
bool
Parser<FullParseHandler, char16_t>::finishFunction(bool isStandaloneFunction /* = false */)
{
    if (!finishFunctionScopes(isStandaloneFunction))
        return false;

    FunctionBox* funbox = pc->functionBox();
    bool hasParameterExprs = funbox->hasParameterExprs;

    if (hasParameterExprs) {
        Maybe<VarScope::Data*> bindings = newVarScopeData(pc->varScope());
        if (!bindings)
            return false;
        funbox->extraVarScopeBindings().set(*bindings);
    }

    {
        Maybe<FunctionScope::Data*> bindings = newFunctionScopeData(pc->functionScope(),
                                                                    hasParameterExprs);
        if (!bindings)
            return false;
        funbox->functionScopeBindings().set(*bindings);
    }

    if (funbox->function()->isNamedLambda() && !isStandaloneFunction) {
        Maybe<LexicalScope::Data*> bindings = newLexicalScopeData(pc->namedLambdaScope());
        if (!bindings)
            return false;
        funbox->namedLambdaBindings().set(*bindings);
    }

    return true;
}

template <>
bool
Parser<SyntaxParseHandler, char16_t>::finishFunction(bool isStandaloneFunction /* = false */)
{
    // The LazyScript for a lazily parsed function needs to know its set of
    // free variables and inner functions so that when it is fully parsed, we
    // can skip over any already syntax parsed inner functions and still
    // retain correct scope information.

    if (!finishFunctionScopes(isStandaloneFunction))
        return false;

    // There are too many bindings or inner functions to be saved into the
    // LazyScript. Do a full parse.
    if (pc->closedOverBindingsForLazy().length() >= LazyScript::NumClosedOverBindingsLimit ||
        pc->innerFunctionsForLazy.length() >= LazyScript::NumInnerFunctionsLimit)
    {
        MOZ_ALWAYS_FALSE(abortIfSyntaxParser());
        return false;
    }

    FunctionBox* funbox = pc->functionBox();
    RootedFunction fun(context, funbox->function());
    LazyScript* lazy = LazyScript::Create(context, fun, pc->closedOverBindingsForLazy(),
                                          pc->innerFunctionsForLazy, versionNumber(),
                                          funbox->bufStart, funbox->bufEnd,
                                          funbox->toStringStart,
                                          funbox->startLine, funbox->startColumn);
    if (!lazy)
        return false;

    // Flags that need to be copied into the JSScript when we do the full
    // parse.
    if (pc->sc()->strict())
        lazy->setStrict();
    lazy->setGeneratorKind(funbox->generatorKind());
    lazy->setAsyncKind(funbox->asyncKind());
    if (funbox->hasRest())
        lazy->setHasRest();
    if (funbox->isExprBody())
        lazy->setIsExprBody();
    if (funbox->isLikelyConstructorWrapper())
        lazy->setLikelyConstructorWrapper();
    if (funbox->isDerivedClassConstructor())
        lazy->setIsDerivedClassConstructor();
    if (funbox->needsHomeObject())
        lazy->setNeedsHomeObject();
    if (funbox->declaredArguments)
        lazy->setShouldDeclareArguments();
    if (funbox->hasThisBinding())
        lazy->setHasThisBinding();

    // Flags that need to copied back into the parser when we do the full
    // parse.
    PropagateTransitiveParseFlags(funbox, lazy);

    fun->initLazyScript(lazy);
    return true;
}

static YieldHandling
GetYieldHandling(GeneratorKind generatorKind)
{
    if (generatorKind == GeneratorKind::NotGenerator)
        return YieldIsName;
    return YieldIsKeyword;
}

static AwaitHandling
GetAwaitHandling(FunctionAsyncKind asyncKind)
{
    if (asyncKind == SyncFunction)
        return AwaitIsName;
    return AwaitIsKeyword;
}

template <>
ParseNode*
Parser<FullParseHandler, char16_t>::standaloneFunction(HandleFunction fun,
                                                       HandleScope enclosingScope,
                                                       const Maybe<uint32_t>& parameterListEnd,
                                                       GeneratorKind generatorKind,
                                                       FunctionAsyncKind asyncKind,
                                                       Directives inheritedDirectives,
                                                       Directives* newDirectives)
{
    MOZ_ASSERT(checkOptionsCalled);

    // Skip prelude.
    TokenKind tt;
    if (!tokenStream.getToken(&tt, TokenStream::Operand))
        return null();
    if (asyncKind == AsyncFunction) {
        MOZ_ASSERT(tt == TOK_ASYNC);
        if (!tokenStream.getToken(&tt, TokenStream::Operand))
            return null();
    }
    MOZ_ASSERT(tt == TOK_FUNCTION);

    if (!tokenStream.getToken(&tt))
        return null();
    if (generatorKind == GeneratorKind::Generator) {
        MOZ_ASSERT(tt == TOK_MUL);
        if (!tokenStream.getToken(&tt))
            return null();
    }

    // Skip function name, if present.
    if (TokenKindIsPossibleIdentifierName(tt)) {
        MOZ_ASSERT(tokenStream.currentName() == fun->explicitName());
    } else {
        MOZ_ASSERT(fun->explicitName() == nullptr);
        tokenStream.ungetToken();
    }

    Node fn = handler.newFunctionStatement(pos());
    if (!fn)
        return null();

    ParseNode* argsbody = handler.newList(PNK_PARAMSBODY, pos());
    if (!argsbody)
        return null();
    fn->pn_body = argsbody;

    FunctionBox* funbox = newFunctionBox(fn, fun, /* toStringStart = */ 0, inheritedDirectives,
                                         generatorKind, asyncKind);
    if (!funbox)
        return null();
    funbox->initStandaloneFunction(enclosingScope);

    SourceParseContext funpc(this, funbox, newDirectives);
    if (!funpc.init())
        return null();
    funpc.setIsStandaloneFunctionBody();

    YieldHandling yieldHandling = GetYieldHandling(generatorKind);
    AwaitHandling awaitHandling = GetAwaitHandling(asyncKind);
    AutoAwaitIsKeyword<Parser> awaitIsKeyword(this, awaitHandling);
    if (!functionFormalParametersAndBody(InAllowed, yieldHandling, fn, Statement,
                                         parameterListEnd, /* isStandaloneFunction = */ true))
    {
        return null();
    }

    if (!tokenStream.getToken(&tt, TokenStream::Operand))
        return null();
    if (tt != TOK_EOF) {
        error(JSMSG_GARBAGE_AFTER_INPUT, "function body", TokenKindToDesc(tt));
        return null();
    }

    if (!FoldConstants(context, &fn, this))
        return null();

    return fn;
}

template <class ParseHandler, typename CharT>
bool
Parser<ParseHandler, CharT>::declareFunctionArgumentsObject()
{
    FunctionBox* funbox = pc->functionBox();
    ParseContext::Scope& funScope = pc->functionScope();
    ParseContext::Scope& varScope = pc->varScope();

    bool hasExtraBodyVarScope = &funScope != &varScope;

    // Time to implement the odd semantics of 'arguments'.
    HandlePropertyName argumentsName = context->names().arguments;

    bool tryDeclareArguments;
    if (handler.canSkipLazyClosedOverBindings())
        tryDeclareArguments = funbox->function()->lazyScript()->shouldDeclareArguments();
    else
        tryDeclareArguments = hasUsedFunctionSpecialName(argumentsName);

    // ES 9.2.12 steps 19 and 20 say formal parameters, lexical bindings,
    // and body-level functions named 'arguments' shadow the arguments
    // object.
    //
    // So even if there wasn't a free use of 'arguments' but there is a var
    // binding of 'arguments', we still might need the arguments object.
    //
    // If we have an extra var scope due to parameter expressions and the body
    // declared 'var arguments', we still need to declare 'arguments' in the
    // function scope.
    DeclaredNamePtr p = varScope.lookupDeclaredName(argumentsName);
    if (p && (p->value()->kind() == DeclarationKind::Var ||
              p->value()->kind() == DeclarationKind::ForOfVar))
    {
        if (hasExtraBodyVarScope)
            tryDeclareArguments = true;
        else
            funbox->usesArguments = true;
    }

    if (tryDeclareArguments) {
        AddDeclaredNamePtr p = funScope.lookupDeclaredNameForAdd(argumentsName);
        if (!p) {
            if (!funScope.addDeclaredName(pc, p, argumentsName, DeclarationKind::Var,
                                          DeclaredNameInfo::npos))
            {
                return false;
            }
            funbox->declaredArguments = true;
            funbox->usesArguments = true;
        } else if (hasExtraBodyVarScope) {
            // Formal parameters shadow the arguments object.
            return true;
        }
    }

    // Compute if we need an arguments object.
    if (funbox->usesArguments) {
        // There is an 'arguments' binding. Is the arguments object definitely
        // needed?
        //
        // Also see the flags' comments in ContextFlags.
        funbox->setArgumentsHasLocalBinding();

        // Dynamic scope access destroys all hope of optimization.
        if (pc->sc()->bindingsAccessedDynamically())
            funbox->setDefinitelyNeedsArgsObj();

        // If a script contains the debugger statement either directly or
        // within an inner function, the arguments object should be created
        // eagerly so the Debugger API may observe bindings.
        if (pc->sc()->hasDebuggerStatement())
            funbox->setDefinitelyNeedsArgsObj();
    }

    return true;
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::functionBody(InHandling inHandling, YieldHandling yieldHandling,
                                          FunctionSyntaxKind kind, FunctionBodyType type)
{
    MOZ_ASSERT(pc->isFunctionBox());
    MOZ_ASSERT(!pc->funHasReturnExpr && !pc->funHasReturnVoid);

#ifdef DEBUG
    uint32_t startYieldOffset = pc->lastYieldOffset;
#endif

    Node pn;
    if (type == StatementListBody) {
        bool inheritedStrict = pc->sc()->strict();
        pn = statementList(yieldHandling);
        if (!pn)
            return null();

        // When we transitioned from non-strict to strict mode, we need to
        // validate that all parameter names are valid strict mode names.
        if (!inheritedStrict && pc->sc()->strict()) {
            MOZ_ASSERT(pc->sc()->hasExplicitUseStrict(),
                       "strict mode should only change when a 'use strict' directive is present");
            if (!hasValidSimpleStrictParameterNames()) {
                // Request that this function be reparsed as strict to report
                // the invalid parameter name at the correct source location.
                pc->newDirectives->setStrict();
                return null();
            }
        }
    } else {
        MOZ_ASSERT(type == ExpressionBody);

        // Async functions are implemented as generators, and generators are
        // assumed to be statement lists, to prepend initial `yield`.
        Node stmtList = null();
        if (pc->isAsync()) {
            stmtList = handler.newStatementList(pos());
            if (!stmtList)
                return null();
        }

        Node kid = assignExpr(inHandling, yieldHandling, TripledotProhibited);
        if (!kid)
            return null();

        pn = handler.newExpressionBody(kid);
        if (!pn)
            return null();

        if (pc->isAsync()) {
            handler.addStatementToList(stmtList, pn);
            pn = stmtList;
        }
    }

    switch (pc->generatorKind()) {
      case GeneratorKind::NotGenerator:
        MOZ_ASSERT_IF(!pc->isAsync(), pc->lastYieldOffset == startYieldOffset);
        break;

      case GeneratorKind::Generator:
        MOZ_ASSERT(kind != Arrow);
        MOZ_ASSERT(type == StatementListBody);
        break;
    }

    if (pc->needsDotGeneratorName()) {
        MOZ_ASSERT_IF(!pc->isAsync(), type == StatementListBody);
        if (!declareDotGeneratorName())
            return null();
        Node generator = newDotGeneratorName();
        if (!generator)
            return null();
        if (!handler.prependInitialYield(pn, generator))
            return null();
    }

    // Declare the 'arguments' and 'this' bindings if necessary before
    // finishing up the scope so these special bindings get marked as closed
    // over if necessary. Arrow functions don't have these bindings.
    if (kind != Arrow) {
        if (!declareFunctionArgumentsObject())
            return null();
        if (!declareFunctionThis())
            return null();
    }

    return finishLexicalScope(pc->varScope(), pn);
}

JSFunction*
ParserBase::newFunction(HandleAtom atom, FunctionSyntaxKind kind,
                        GeneratorKind generatorKind, FunctionAsyncKind asyncKind,
                        HandleObject proto)
{
    MOZ_ASSERT_IF(kind == Statement, atom != nullptr);

    RootedFunction fun(context);

    gc::AllocKind allocKind = gc::AllocKind::FUNCTION;
    JSFunction::Flags flags;
#ifdef DEBUG
    bool isGlobalSelfHostedBuiltin = false;
#endif
    switch (kind) {
      case Expression:
        flags = (generatorKind == GeneratorKind::NotGenerator && asyncKind == SyncFunction
                 ? JSFunction::INTERPRETED_LAMBDA
                 : JSFunction::INTERPRETED_LAMBDA_GENERATOR_OR_ASYNC);
        break;
      case Arrow:
        flags = JSFunction::INTERPRETED_LAMBDA_ARROW;
        allocKind = gc::AllocKind::FUNCTION_EXTENDED;
        break;
      case Method:
        flags = (generatorKind == GeneratorKind::NotGenerator && asyncKind == SyncFunction
                 ? JSFunction::INTERPRETED_METHOD
                 : JSFunction::INTERPRETED_METHOD_GENERATOR_OR_ASYNC);
        allocKind = gc::AllocKind::FUNCTION_EXTENDED;
        break;
      case ClassConstructor:
      case DerivedClassConstructor:
        flags = JSFunction::INTERPRETED_CLASS_CONSTRUCTOR;
        allocKind = gc::AllocKind::FUNCTION_EXTENDED;
        break;
      case Getter:
      case GetterNoExpressionClosure:
        flags = JSFunction::INTERPRETED_GETTER;
        allocKind = gc::AllocKind::FUNCTION_EXTENDED;
        break;
      case Setter:
      case SetterNoExpressionClosure:
        flags = JSFunction::INTERPRETED_SETTER;
        allocKind = gc::AllocKind::FUNCTION_EXTENDED;
        break;
      default:
        MOZ_ASSERT(kind == Statement);
#ifdef DEBUG
        if (options().selfHostingMode && !pc->isFunctionBox()) {
            isGlobalSelfHostedBuiltin = true;
            allocKind = gc::AllocKind::FUNCTION_EXTENDED;
        }
#endif
        flags = (generatorKind == GeneratorKind::NotGenerator && asyncKind == SyncFunction
                 ? JSFunction::INTERPRETED_NORMAL
                 : JSFunction::INTERPRETED_GENERATOR_OR_ASYNC);
    }

    // We store the async wrapper in a slot for later access.
    if (asyncKind == AsyncFunction)
        allocKind = gc::AllocKind::FUNCTION_EXTENDED;

    fun = NewFunctionWithProto(context, nullptr, 0, flags, nullptr, atom, proto,
                               allocKind, TenuredObject);
    if (!fun)
        return nullptr;
    if (options().selfHostingMode) {
        fun->setIsSelfHostedBuiltin();
#ifdef DEBUG
        if (isGlobalSelfHostedBuiltin)
            fun->setExtendedSlot(HAS_SELFHOSTED_CANONICAL_NAME_SLOT, BooleanValue(false));
#endif
    }
    return fun;
}

template <class ParseHandler, typename CharT>
bool
Parser<ParseHandler, CharT>::matchOrInsertSemicolon()
{
    TokenKind tt = TOK_EOF;
    if (!tokenStream.peekTokenSameLine(&tt, TokenStream::Operand))
        return false;
    if (tt != TOK_EOF && tt != TOK_EOL && tt != TOK_SEMI && tt != TOK_RC) {
        /*
         * When current token is `await` and it's outside of async function,
         * it's possibly intended to be an await expression.
         *
         *   await f();
         *        ^
         *        |
         *        tried to insert semicolon here
         *
         * Detect this situation and throw an understandable error.  Otherwise
         * we'd throw a confusing "unexpected token: (unexpected token)" error.
         */
        if (!pc->isAsync() && tokenStream.currentToken().type == TOK_AWAIT) {
            error(JSMSG_AWAIT_OUTSIDE_ASYNC);
            return false;
        }
        if (!yieldExpressionsSupported() && tokenStream.currentToken().type == TOK_YIELD) {
            error(JSMSG_YIELD_OUTSIDE_GENERATOR);
            return false;
        }

        /* Advance the scanner for proper error location reporting. */
        tokenStream.consumeKnownToken(tt, TokenStream::Operand);
        error(JSMSG_UNEXPECTED_TOKEN_NO_EXPECT, TokenKindToDesc(tt));
        return false;
    }
    bool matched;
    return tokenStream.matchToken(&matched, TOK_SEMI, TokenStream::Operand);
}

template <class ParseHandler, typename CharT>
bool
Parser<ParseHandler, CharT>::leaveInnerFunction(ParseContext* outerpc)
{
    MOZ_ASSERT(pc != outerpc);

    // If the current function allows super.property but cannot have a home
    // object, i.e., it is an arrow function, we need to propagate the flag to
    // the outer ParseContext.
    if (pc->superScopeNeedsHomeObject()) {
        if (!pc->isArrowFunction())
            MOZ_ASSERT(pc->functionBox()->needsHomeObject());
        else
            outerpc->setSuperScopeNeedsHomeObject();
    }

    // Lazy functions inner to another lazy function need to be remembered by
    // the inner function so that if the outer function is eventually parsed
    // we do not need any further parsing or processing of the inner function.
    //
    // Append the inner function here unconditionally; the vector is only used
    // if the Parser using outerpc is a syntax parsing. See
    // Parser<SyntaxParseHandler>::finishFunction.
    if (!outerpc->innerFunctionsForLazy.append(pc->functionBox()->function()))
        return false;

    PropagateTransitiveParseFlags(pc->functionBox(), outerpc->sc());

    return true;
}

template <class ParseHandler, typename CharT>
JSAtom*
Parser<ParseHandler, CharT>::prefixAccessorName(PropertyType propType, HandleAtom propAtom)
{
    RootedAtom prefix(context);
    if (propType == PropertyType::Setter || propType == PropertyType::SetterNoExpressionClosure) {
        prefix = context->names().setPrefix;
    } else {
        MOZ_ASSERT(propType == PropertyType::Getter || propType == PropertyType::GetterNoExpressionClosure);
        prefix = context->names().getPrefix;
    }

    RootedString str(context, ConcatStrings<CanGC>(context, prefix, propAtom));
    if (!str)
        return nullptr;

    return AtomizeString(context, str);
}

template <class ParseHandler, typename CharT>
bool
Parser<ParseHandler, CharT>::functionArguments(YieldHandling yieldHandling,
                                               FunctionSyntaxKind kind,
                                               Node funcpn)
{
    FunctionBox* funbox = pc->functionBox();

    bool parenFreeArrow = false;
    // Modifier for the following tokens.
    // TokenStream::None for the following cases:
    //   async a => 1
    //         ^
    //
    //   (a) => 1
    //   ^
    //
    //   async (a) => 1
    //         ^
    //
    //   function f(a) {}
    //             ^
    //
    // TokenStream::Operand for the following case:
    //   a => 1
    //   ^
    TokenStream::Modifier firstTokenModifier = TokenStream::None;

    // Modifier for the the first token in each argument.
    // can be changed to TokenStream::None for the following case:
    //   async a => 1
    //         ^
    TokenStream::Modifier argModifier = TokenStream::Operand;
    if (kind == Arrow) {
        TokenKind tt;
        // In async function, the first token after `async` is already gotten
        // with TokenStream::None.
        // In sync function, the first token is already gotten with
        // TokenStream::Operand.
        firstTokenModifier = funbox->isAsync() ? TokenStream::None : TokenStream::Operand;
        if (!tokenStream.peekToken(&tt, firstTokenModifier))
            return false;
        if (TokenKindIsPossibleIdentifier(tt)) {
            parenFreeArrow = true;
            argModifier = firstTokenModifier;
        }
    }

    TokenPos firstTokenPos;
    if (!parenFreeArrow) {
        TokenKind tt;
        if (!tokenStream.getToken(&tt, firstTokenModifier))
            return false;
        if (tt != TOK_LP) {
            error(kind == Arrow ? JSMSG_BAD_ARROW_ARGS : JSMSG_PAREN_BEFORE_FORMAL);
            return false;
        }

        firstTokenPos = pos();

        // Record the start of function source (for FunctionToString). If we
        // are parenFreeArrow, we will set this below, after consuming the NAME.
        funbox->setStart(tokenStream);
    } else {
        // When delazifying, we may not have a current token and pos() is
        // garbage. In that case, substitute the first token's position.
        if (!tokenStream.peekTokenPos(&firstTokenPos, firstTokenModifier))
            return false;
    }

    Node argsbody = handler.newList(PNK_PARAMSBODY, firstTokenPos);
    if (!argsbody)
        return false;
    handler.setFunctionFormalParametersAndBody(funcpn, argsbody);

    bool hasArguments = false;
    if (parenFreeArrow) {
        hasArguments = true;
    } else {
        bool matched;
        if (!tokenStream.matchToken(&matched, TOK_RP, TokenStream::Operand))
            return false;
        if (!matched)
            hasArguments = true;
    }
    if (hasArguments) {
        bool hasRest = false;
        bool hasDefault = false;
        bool duplicatedParam = false;
        bool disallowDuplicateParams = kind == Arrow || kind == Method || kind == ClassConstructor;
        AtomVector& positionalFormals = pc->positionalFormalParameterNames();

        if (IsGetterKind(kind)) {
            error(JSMSG_ACCESSOR_WRONG_ARGS, "getter", "no", "s");
            return false;
        }

        while (true) {
            if (hasRest) {
                error(JSMSG_PARAMETER_AFTER_REST);
                return false;
            }

            TokenKind tt;
            if (!tokenStream.getToken(&tt, argModifier))
                return false;
            argModifier = TokenStream::Operand;
            MOZ_ASSERT_IF(parenFreeArrow, TokenKindIsPossibleIdentifier(tt));

            if (tt == TOK_TRIPLEDOT) {
                if (IsSetterKind(kind)) {
                    error(JSMSG_ACCESSOR_WRONG_ARGS, "setter", "one", "");
                    return false;
                }

                disallowDuplicateParams = true;
                if (duplicatedParam) {
                    // Has duplicated args before the rest parameter.
                    error(JSMSG_BAD_DUP_ARGS);
                    return false;
                }

                hasRest = true;
                funbox->setHasRest();

                if (!tokenStream.getToken(&tt))
                    return false;

                if (!TokenKindIsPossibleIdentifier(tt) && tt != TOK_LB && tt != TOK_LC) {
                    error(JSMSG_NO_REST_NAME);
                    return false;
                }
            }

            switch (tt) {
              case TOK_LB:
              case TOK_LC: {
                disallowDuplicateParams = true;
                if (duplicatedParam) {
                    // Has duplicated args before the destructuring parameter.
                    error(JSMSG_BAD_DUP_ARGS);
                    return false;
                }

                funbox->hasDestructuringArgs = true;

                Node destruct = destructuringDeclarationWithoutYieldOrAwait(
                    DeclarationKind::FormalParameter,
                    yieldHandling, tt);
                if (!destruct)
                    return false;

                if (!noteDestructuredPositionalFormalParameter(funcpn, destruct))
                    return false;

                break;
              }

              default: {
                if (!TokenKindIsPossibleIdentifier(tt)) {
                    error(JSMSG_MISSING_FORMAL);
                    return false;
                }

                if (parenFreeArrow)
                    funbox->setStart(tokenStream);

                RootedPropertyName name(context, bindingIdentifier(yieldHandling));
                if (!name)
                    return false;

                if (!notePositionalFormalParameter(funcpn, name, pos().begin,
                                                   disallowDuplicateParams, &duplicatedParam))
                {
                    return false;
                }
                if (duplicatedParam)
                    funbox->hasDuplicateParameters = true;

                break;
              }
            }

            if (positionalFormals.length() >= ARGNO_LIMIT) {
                error(JSMSG_TOO_MANY_FUN_ARGS);
                return false;
            }

            // The next step is to detect arguments with default expressions,
            // e.g. |function parseInt(str, radix = 10) {}|.  But if we have a
            // parentheses-free arrow function, |a => ...|, the '=' necessary
            // for a default expression would really be an assignment operator:
            // that is, |a = b => 42;| would parse as |a = (b => 42);|.  So we
            // should stop parsing arguments here.
            if (parenFreeArrow)
                break;

            bool matched;
            if (!tokenStream.matchToken(&matched, TOK_ASSIGN, TokenStream::Operand))
                return false;
            if (matched) {
                // A default argument without parentheses would look like:
                // a = expr => body, but both operators are right-associative, so
                // that would have been parsed as a = (expr => body) instead.
                // Therefore it's impossible to get here with parenFreeArrow.
                MOZ_ASSERT(!parenFreeArrow);

                if (hasRest) {
                    error(JSMSG_REST_WITH_DEFAULT);
                    return false;
                }
                disallowDuplicateParams = true;
                if (duplicatedParam) {
                    error(JSMSG_BAD_DUP_ARGS);
                    return false;
                }

                if (!hasDefault) {
                    hasDefault = true;

                    // The Function.length property is the number of formals
                    // before the first default argument.
                    funbox->length = positionalFormals.length() - 1;
                }
                funbox->hasParameterExprs = true;

                Node def_expr = assignExprWithoutYieldOrAwait(yieldHandling);
                if (!def_expr)
                    return false;
                if (!handler.setLastFunctionFormalParameterDefault(funcpn, def_expr))
                    return false;
            }

            // Setter syntax uniquely requires exactly one argument.
            if (IsSetterKind(kind))
                break;

            if (!tokenStream.matchToken(&matched, TOK_COMMA, TokenStream::Operand))
                return false;
            if (!matched)
                break;

            if (!hasRest) {
                if (!tokenStream.peekToken(&tt, TokenStream::Operand))
                    return null();
                if (tt == TOK_RP)
                    break;
            }
        }

        if (!parenFreeArrow) {
            TokenKind tt;
            if (!tokenStream.getToken(&tt, TokenStream::Operand))
                return false;
            if (tt != TOK_RP) {
                if (IsSetterKind(kind)) {
                    error(JSMSG_ACCESSOR_WRONG_ARGS, "setter", "one", "");
                    return false;
                }

                error(JSMSG_PAREN_AFTER_FORMAL);
                return false;
            }
        }

        if (!hasDefault)
            funbox->length = positionalFormals.length() - hasRest;

        if (funbox->hasParameterExprs && funbox->hasDirectEval())
            funbox->hasDirectEvalInParameterExpr = true;

        funbox->function()->setArgCount(positionalFormals.length());
    } else if (IsSetterKind(kind)) {
        error(JSMSG_ACCESSOR_WRONG_ARGS, "setter", "one", "");
        return false;
    }

    return true;
}

template <>
bool
Parser<FullParseHandler, char16_t>::skipLazyInnerFunction(ParseNode* pn, uint32_t toStringStart,
                                                          FunctionSyntaxKind kind, bool tryAnnexB)
{
    // When a lazily-parsed function is called, we only fully parse (and emit)
    // that function, not any of its nested children. The initial syntax-only
    // parse recorded the free variables of nested functions and their extents,
    // so we can skip over them after accounting for their free variables.

    RootedFunction fun(context, handler.nextLazyInnerFunction());
    FunctionBox* funbox = newFunctionBox(pn, fun, toStringStart, Directives(/* strict = */ false),
                                         fun->generatorKind(), fun->asyncKind());
    if (!funbox)
        return false;

    LazyScript* lazy = fun->lazyScript();
    if (lazy->needsHomeObject())
        funbox->setNeedsHomeObject();
    if (lazy->isExprBody())
        funbox->setIsExprBody();

    PropagateTransitiveParseFlags(lazy, pc->sc());

    if (!tokenStream.advance(fun->lazyScript()->end()))
        return false;

#if JS_HAS_EXPR_CLOSURES
    // Only expression closure can be Statement kind.
    // If we remove expression closure, we can remove isExprBody flag from
    // LazyScript and JSScript.
    if (kind == Statement && funbox->isExprBody()) {
        if (!matchOrInsertSemicolon())
            return false;
    }
#endif

    // Append possible Annex B function box only upon successfully parsing.
    if (tryAnnexB && !pc->innermostScope()->addPossibleAnnexBFunctionBox(pc, funbox))
        return false;

    return true;
}

template <>
bool
Parser<SyntaxParseHandler, char16_t>::skipLazyInnerFunction(Node pn, uint32_t toStringStart,
                                                            FunctionSyntaxKind kind,
                                                            bool tryAnnexB)
{
    MOZ_CRASH("Cannot skip lazy inner functions when syntax parsing");
}

template <class ParseHandler, typename CharT>
bool
Parser<ParseHandler, CharT>::addExprAndGetNextTemplStrToken(YieldHandling yieldHandling,
                                                            Node nodeList,
                                                            TokenKind* ttp)
{
    Node pn = expr(InAllowed, yieldHandling, TripledotProhibited);
    if (!pn)
        return false;
    handler.addList(nodeList, pn);

    TokenKind tt;
    if (!tokenStream.getToken(&tt, TokenStream::Operand))
        return false;
    if (tt != TOK_RC) {
        error(JSMSG_TEMPLSTR_UNTERM_EXPR);
        return false;
    }

    return tokenStream.getToken(ttp, TokenStream::TemplateTail);
}

template <class ParseHandler, typename CharT>
bool
Parser<ParseHandler, CharT>::taggedTemplate(YieldHandling yieldHandling, Node nodeList,
                                            TokenKind tt)
{
    Node callSiteObjNode = handler.newCallSiteObject(pos().begin);
    if (!callSiteObjNode)
        return false;
    handler.addList(nodeList, callSiteObjNode);

    while (true) {
        if (!appendToCallSiteObj(callSiteObjNode))
            return false;
        if (tt != TOK_TEMPLATE_HEAD)
            break;

        if (!addExprAndGetNextTemplStrToken(yieldHandling, nodeList, &tt))
            return false;
    }
    handler.setEndPosition(nodeList, callSiteObjNode);
    return true;
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::templateLiteral(YieldHandling yieldHandling)
{
    Node pn = noSubstitutionUntaggedTemplate();
    if (!pn)
        return null();

    Node nodeList = handler.newList(PNK_TEMPLATE_STRING_LIST, pn);
    if (!nodeList)
        return null();

    TokenKind tt;
    do {
        if (!addExprAndGetNextTemplStrToken(yieldHandling, nodeList, &tt))
            return null();

        pn = noSubstitutionUntaggedTemplate();
        if (!pn)
            return null();

        handler.addList(nodeList, pn);
    } while (tt == TOK_TEMPLATE_HEAD);
    return nodeList;
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::functionDefinition(Node pn, uint32_t toStringStart,
                                                InHandling inHandling,
                                                YieldHandling yieldHandling, HandleAtom funName,
                                                FunctionSyntaxKind kind,
                                                GeneratorKind generatorKind,
                                                FunctionAsyncKind asyncKind,
                                                bool tryAnnexB /* = false */)
{
    MOZ_ASSERT_IF(kind == Statement, funName);

    // When fully parsing a LazyScript, we do not fully reparse its inner
    // functions, which are also lazy. Instead, their free variables and
    // source extents are recorded and may be skipped.
    if (handler.canSkipLazyInnerFunctions()) {
        if (!skipLazyInnerFunction(pn, toStringStart, kind, tryAnnexB))
            return null();
        return pn;
    }

    RootedObject proto(context);
    if (generatorKind == GeneratorKind::Generator || asyncKind == AsyncFunction) {
        // If we are off thread, the generator meta-objects have
        // already been created by js::StartOffThreadParseTask, so cx will not
        // be necessary.
        JSContext* cx = context->helperThread() ? nullptr : context;
        proto = GlobalObject::getOrCreateGeneratorFunctionPrototype(cx, context->global());
        if (!proto)
            return null();
    }
    RootedFunction fun(context, newFunction(funName, kind, generatorKind, asyncKind, proto));
    if (!fun)
        return null();

    // Speculatively parse using the directives of the parent parsing context.
    // If a directive is encountered (e.g., "use strict") that changes how the
    // function should have been parsed, we backup and reparse with the new set
    // of directives.
    Directives directives(pc);
    Directives newDirectives = directives;

    TokenStream::Position start(keepAtoms);
    tokenStream.tell(&start);

    // Parse the inner function. The following is a loop as we may attempt to
    // reparse a function due to failed syntax parsing and encountering new
    // "use foo" directives.
    while (true) {
        if (trySyntaxParseInnerFunction(pn, fun, toStringStart, inHandling, yieldHandling, kind,
                                        generatorKind, asyncKind, tryAnnexB, directives,
                                        &newDirectives))
        {
            break;
        }

        // Return on error.
        if (tokenStream.hadError() || directives == newDirectives)
            return null();

        // Assignment must be monotonic to prevent infinitely attempting to
        // reparse.
        MOZ_ASSERT_IF(directives.strict(), newDirectives.strict());
        MOZ_ASSERT_IF(directives.asmJS(), newDirectives.asmJS());
        directives = newDirectives;

        tokenStream.seek(start);

        // functionFormalParametersAndBody may have already set pn->pn_body before failing.
        handler.setFunctionFormalParametersAndBody(pn, null());
    }

    return pn;
}

template <>
bool
Parser<FullParseHandler, char16_t>::trySyntaxParseInnerFunction(ParseNode* pn, HandleFunction fun,
                                                                uint32_t toStringStart,
                                                                InHandling inHandling,
                                                                YieldHandling yieldHandling,
                                                                FunctionSyntaxKind kind,
                                                                GeneratorKind generatorKind,
                                                                FunctionAsyncKind asyncKind,
                                                                bool tryAnnexB,
                                                                Directives inheritedDirectives,
                                                                Directives* newDirectives)
{
    // Try a syntax parse for this inner function.
    do {
        // If we're assuming this function is an IIFE, always perform a full
        // parse to avoid the overhead of a lazy syntax-only parse. Although
        // the prediction may be incorrect, IIFEs are common enough that it
        // pays off for lots of code.
        if (pn->isLikelyIIFE() &&
            generatorKind == GeneratorKind::NotGenerator &&
            asyncKind == SyncFunction)
        {
            break;
        }

        if (!syntaxParser_)
            break;

        UsedNameTracker::RewindToken token = usedNames.getRewindToken();

        // Move the syntax parser to the current position in the stream.
        TokenStream::Position position(keepAtoms);
        tokenStream.tell(&position);
        if (!syntaxParser_->tokenStream.seek(position, tokenStream))
            return false;

        // Make a FunctionBox before we enter the syntax parser, because |pn|
        // still expects a FunctionBox to be attached to it during BCE, and
        // the syntax parser cannot attach one to it.
        FunctionBox* funbox = newFunctionBox(pn, fun, toStringStart, inheritedDirectives,
                                             generatorKind, asyncKind);
        if (!funbox)
            return false;
        funbox->initWithEnclosingParseContext(pc, kind);

        if (!syntaxParser_->innerFunction(SyntaxParseHandler::NodeGeneric,
                                          pc, funbox, toStringStart,
                                          inHandling, yieldHandling, kind,
                                          inheritedDirectives, newDirectives))
        {
            if (syntaxParser_->hadAbortedSyntaxParse()) {
                // Try again with a full parse. UsedNameTracker needs to be
                // rewound to just before we tried the syntax parse for
                // correctness.
                syntaxParser_->clearAbortedSyntaxParse();
                usedNames.rewind(token);
                MOZ_ASSERT_IF(!syntaxParser_->context->helperThread(),
                              !syntaxParser_->context->isExceptionPending());
                break;
            }
            return false;
        }

        // Advance this parser over tokens processed by the syntax parser.
        syntaxParser_->tokenStream.tell(&position);
        if (!tokenStream.seek(position, syntaxParser_->tokenStream))
            return false;

        // Update the end position of the parse node.
        pn->pn_pos.end = tokenStream.currentToken().pos.end;

        // Append possible Annex B function box only upon successfully parsing.
        if (tryAnnexB && !pc->innermostScope()->addPossibleAnnexBFunctionBox(pc, funbox))
            return false;

        return true;
    } while (false);

    // We failed to do a syntax parse above, so do the full parse.
    return innerFunction(pn, pc, fun, toStringStart, inHandling, yieldHandling, kind,
                         generatorKind, asyncKind, tryAnnexB, inheritedDirectives, newDirectives);
}

template <>
bool
Parser<SyntaxParseHandler, char16_t>::trySyntaxParseInnerFunction(Node pn, HandleFunction fun,
                                                                  uint32_t toStringStart,
                                                                  InHandling inHandling,
                                                                  YieldHandling yieldHandling,
                                                                  FunctionSyntaxKind kind,
                                                                  GeneratorKind generatorKind,
                                                                  FunctionAsyncKind asyncKind,
                                                                  bool tryAnnexB,
                                                                  Directives inheritedDirectives,
                                                                  Directives* newDirectives)
{
    // This is already a syntax parser, so just parse the inner function.
    return innerFunction(pn, pc, fun, toStringStart, inHandling, yieldHandling, kind,
                         generatorKind, asyncKind, tryAnnexB, inheritedDirectives, newDirectives);
}

template <class ParseHandler, typename CharT>
bool
Parser<ParseHandler, CharT>::innerFunction(Node pn, ParseContext* outerpc, FunctionBox* funbox,
                                           uint32_t toStringStart,
                                           InHandling inHandling, YieldHandling yieldHandling,
                                           FunctionSyntaxKind kind, Directives inheritedDirectives,
                                           Directives* newDirectives)
{
    // Note that it is possible for outerpc != this->pc, as we may be
    // attempting to syntax parse an inner function from an outer full
    // parser. In that case, outerpc is a SourceParseContext from the full parser
    // instead of the current top of the stack of the syntax parser.

    // Push a new ParseContext.
    SourceParseContext funpc(this, funbox, newDirectives);
    if (!funpc.init())
        return false;

    if (!functionFormalParametersAndBody(inHandling, yieldHandling, pn, kind))
        return false;

    return leaveInnerFunction(outerpc);
}

template <class ParseHandler, typename CharT>
bool
Parser<ParseHandler, CharT>::innerFunction(Node pn, ParseContext* outerpc, HandleFunction fun,
                                           uint32_t toStringStart,
                                           InHandling inHandling, YieldHandling yieldHandling,
                                           FunctionSyntaxKind kind,
                                           GeneratorKind generatorKind,
                                           FunctionAsyncKind asyncKind,
                                           bool tryAnnexB,
                                           Directives inheritedDirectives,
                                           Directives* newDirectives)
{
    // Note that it is possible for outerpc != this->pc, as we may be
    // attempting to syntax parse an inner function from an outer full
    // parser. In that case, outerpc is a SourceParseContext from the full parser
    // instead of the current top of the stack of the syntax parser.

    FunctionBox* funbox = newFunctionBox(pn, fun, toStringStart, inheritedDirectives,
                                         generatorKind, asyncKind);
    if (!funbox)
        return false;
    funbox->initWithEnclosingParseContext(outerpc, kind);

    if (!innerFunction(pn, outerpc, funbox, toStringStart, inHandling, yieldHandling, kind,
                       inheritedDirectives, newDirectives))
    {
        return false;
    }

    // Append possible Annex B function box only upon successfully parsing.
    if (tryAnnexB && !pc->innermostScope()->addPossibleAnnexBFunctionBox(pc, funbox))
        return false;

    return true;
}

template <class ParseHandler, typename CharT>
bool
Parser<ParseHandler, CharT>::appendToCallSiteObj(Node callSiteObj)
{
    Node cookedNode = noSubstitutionTaggedTemplate();
    if (!cookedNode)
        return false;

    JSAtom* atom = tokenStream.getRawTemplateStringAtom();
    if (!atom)
        return false;
    Node rawNode = handler.newTemplateStringLiteral(atom, pos());
    if (!rawNode)
        return false;

    handler.addToCallSiteObject(callSiteObj, rawNode, cookedNode);
    return true;
}

template <>
ParseNode*
Parser<FullParseHandler, char16_t>::standaloneLazyFunction(HandleFunction fun,
                                                           uint32_t toStringStart,
                                                           bool strict,
                                                           GeneratorKind generatorKind,
                                                           FunctionAsyncKind asyncKind)
{
    MOZ_ASSERT(checkOptionsCalled);

    Node pn = handler.newFunctionStatement(pos());
    if (!pn)
        return null();

    Directives directives(strict);
    FunctionBox* funbox = newFunctionBox(pn, fun, toStringStart, directives, generatorKind,
                                         asyncKind);
    if (!funbox)
        return null();
    funbox->initFromLazyFunction();

    Directives newDirectives = directives;
    SourceParseContext funpc(this, funbox, &newDirectives);
    if (!funpc.init())
        return null();

    // Our tokenStream has no current token, so pn's position is garbage.
    // Substitute the position of the first token in our source. If the function
    // is a not-async arrow, use TokenStream::Operand to keep
    // verifyConsistentModifier from complaining (we will use
    // TokenStream::Operand in functionArguments).
    TokenStream::Modifier modifier = (fun->isArrow() && asyncKind == SyncFunction)
                                     ? TokenStream::Operand : TokenStream::None;
    if (!tokenStream.peekTokenPos(&pn->pn_pos, modifier))
        return null();

    YieldHandling yieldHandling = GetYieldHandling(generatorKind);
    FunctionSyntaxKind syntaxKind = Statement;
    if (fun->isClassConstructor())
        syntaxKind = ClassConstructor;
    else if (fun->isMethod())
        syntaxKind = Method;
    else if (fun->isGetter())
        syntaxKind = Getter;
    else if (fun->isSetter())
        syntaxKind = Setter;
    else if (fun->isArrow())
        syntaxKind = Arrow;

    if (!functionFormalParametersAndBody(InAllowed, yieldHandling, pn, syntaxKind)) {
        MOZ_ASSERT(directives == newDirectives);
        return null();
    }

    if (!FoldConstants(context, &pn, this))
        return null();

    return pn;
}

template <class ParseHandler, typename CharT>
bool
Parser<ParseHandler, CharT>::functionFormalParametersAndBody(InHandling inHandling,
                                                             YieldHandling yieldHandling,
                                                             Node pn, FunctionSyntaxKind kind,
                                                             const Maybe<uint32_t>& parameterListEnd /* = Nothing() */,
                                                             bool isStandaloneFunction /* = false */)
{
    // Given a properly initialized parse context, try to parse an actual
    // function without concern for conversion to strict mode, use of lazy
    // parsing and such.

    FunctionBox* funbox = pc->functionBox();
    RootedFunction fun(context, funbox->function());

    // See below for an explanation why arrow function parameters and arrow
    // function bodies are parsed with different yield/await settings.
    {
        AwaitHandling awaitHandling = funbox->isAsync() || (kind == Arrow && awaitIsKeyword())
                                      ? AwaitIsKeyword
                                      : AwaitIsName;
        AutoAwaitIsKeyword<Parser> awaitIsKeyword(this, awaitHandling);
        if (!functionArguments(yieldHandling, kind, pn))
            return false;
    }

    Maybe<ParseContext::VarScope> varScope;
    if (funbox->hasParameterExprs) {
        varScope.emplace(this);
        if (!varScope->init(pc))
            return false;
    } else {
        pc->functionScope().useAsVarScope(pc);
    }

    if (kind == Arrow) {
        bool matched;
        if (!tokenStream.matchToken(&matched, TOK_ARROW))
            return false;
        if (!matched) {
            error(JSMSG_BAD_ARROW_ARGS);
            return false;
        }
    }

    // When parsing something for new Function() we have to make sure to
    // only treat a certain part of the source as a parameter list.
    if (parameterListEnd.isSome() && parameterListEnd.value() != pos().begin) {
        error(JSMSG_UNEXPECTED_PARAMLIST_END);
        return false;
    }

    // Parse the function body.
    FunctionBodyType bodyType = StatementListBody;
    TokenKind tt;
    if (!tokenStream.getToken(&tt, TokenStream::Operand))
        return false;
    uint32_t openedPos = 0;
    if (tt != TOK_LC) {
        if (kind != Arrow) {
            if (funbox->isGenerator() || funbox->isAsync() || kind == Method ||
                kind == GetterNoExpressionClosure || kind == SetterNoExpressionClosure ||
                IsConstructorKind(kind))
            {
                error(JSMSG_CURLY_BEFORE_BODY);
                return false;
            }

#if JS_HAS_EXPR_CLOSURES
            addTelemetry(DeprecatedLanguageExtension::ExpressionClosure);
            if (!warnOnceAboutExprClosure())
                return false;
#else
            error(JSMSG_CURLY_BEFORE_BODY);
            return false;
#endif
        }

        tokenStream.ungetToken();
        bodyType = ExpressionBody;
        funbox->setIsExprBody();
    } else {
        openedPos = pos().begin;
    }

    // Arrow function parameters inherit yieldHandling from the enclosing
    // context, but the arrow body doesn't. E.g. in |(a = yield) => yield|,
    // |yield| in the parameters is either a name or keyword, depending on
    // whether the arrow function is enclosed in a generator function or not.
    // Whereas the |yield| in the function body is always parsed as a name.
    // The same goes when parsing |await| in arrow functions.
    YieldHandling bodyYieldHandling = GetYieldHandling(pc->generatorKind());
    AwaitHandling bodyAwaitHandling = GetAwaitHandling(pc->asyncKind());
    bool inheritedStrict = pc->sc()->strict();
    Node body;
    {
        AutoAwaitIsKeyword<Parser> awaitIsKeyword(this, bodyAwaitHandling);
        body = functionBody(inHandling, bodyYieldHandling, kind, bodyType);
        if (!body)
            return false;
    }

    // Revalidate the function name when we transitioned to strict mode.
    if ((kind == Statement || kind == Expression) && fun->explicitName()
        && !inheritedStrict && pc->sc()->strict())
    {
        MOZ_ASSERT(pc->sc()->hasExplicitUseStrict(),
                   "strict mode should only change when a 'use strict' directive is present");

        PropertyName* propertyName = fun->explicitName()->asPropertyName();
        YieldHandling nameYieldHandling;
        if (kind == Expression) {
            // Named lambda has binding inside it.
            nameYieldHandling = bodyYieldHandling;
        } else {
            // Otherwise YieldHandling cannot be checked at this point
            // because of different context.
            // It should already be checked before this point.
            nameYieldHandling = YieldIsName;
        }

        // We already use the correct await-handling at this point, therefore
        // we don't need call AutoAwaitIsKeyword here.

        uint32_t nameOffset = handler.getFunctionNameOffset(pn, tokenStream);
        if (!checkBindingIdentifier(propertyName, nameOffset, nameYieldHandling))
            return false;
    }

    if (bodyType == StatementListBody) {
        MUST_MATCH_TOKEN_MOD_WITH_REPORT(TOK_RC, TokenStream::Operand,
                                         reportMissingClosing(JSMSG_CURLY_AFTER_BODY,
                                                              JSMSG_CURLY_OPENED, openedPos));
        funbox->setEnd(tokenStream);
    } else {
#if !JS_HAS_EXPR_CLOSURES
        MOZ_ASSERT(kind == Arrow);
#endif
        if (tokenStream.hadError())
            return false;
        funbox->setEnd(tokenStream);
        if (kind == Statement && !matchOrInsertSemicolon())
            return false;
    }

    if (IsMethodDefinitionKind(kind) && pc->superScopeNeedsHomeObject())
        funbox->setNeedsHomeObject();

    if (!finishFunction(isStandaloneFunction))
        return false;

    handler.setEndPosition(body, pos().begin);
    handler.setEndPosition(pn, pos().end);
    handler.setFunctionBody(pn, body);

    return true;
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::functionStmt(uint32_t toStringStart, YieldHandling yieldHandling,
                                          DefaultHandling defaultHandling,
                                          FunctionAsyncKind asyncKind)
{
    MOZ_ASSERT(tokenStream.isCurrentTokenType(TOK_FUNCTION));

    // In sloppy mode, Annex B.3.2 allows labelled function declarations.
    // Otherwise it's a parse error.
    ParseContext::Statement* declaredInStmt = pc->innermostStatement();
    if (declaredInStmt && declaredInStmt->kind() == StatementKind::Label) {
        MOZ_ASSERT(!pc->sc()->strict(),
                   "labeled functions shouldn't be parsed in strict mode");

        // Find the innermost non-label statement.  Report an error if it's
        // unbraced: functions can't appear in it.  Otherwise the statement
        // (or its absence) determines the scope the function's bound in.
        while (declaredInStmt && declaredInStmt->kind() == StatementKind::Label)
            declaredInStmt = declaredInStmt->enclosing();

        if (declaredInStmt && !StatementKindIsBraced(declaredInStmt->kind())) {
            error(JSMSG_SLOPPY_FUNCTION_LABEL);
            return null();
        }
    }

    TokenKind tt;
    if (!tokenStream.getToken(&tt))
        return null();

    GeneratorKind generatorKind = GeneratorKind::NotGenerator;
    if (tt == TOK_MUL) {
        generatorKind = GeneratorKind::Generator;
        if (!tokenStream.getToken(&tt))
            return null();
    }

    RootedPropertyName name(context);
    if (TokenKindIsPossibleIdentifier(tt)) {
        name = bindingIdentifier(yieldHandling);
        if (!name)
            return null();
    } else if (defaultHandling == AllowDefaultName) {
        name = context->names().starDefaultStar;
        tokenStream.ungetToken();
    } else {
        /* Unnamed function expressions are forbidden in statement context. */
        error(JSMSG_UNNAMED_FUNCTION_STMT);
        return null();
    }

    // Note the declared name and check for early errors.
    DeclarationKind kind;
    if (declaredInStmt) {
        MOZ_ASSERT(declaredInStmt->kind() != StatementKind::Label);
        MOZ_ASSERT(StatementKindIsBraced(declaredInStmt->kind()));

        kind = (!pc->sc()->strict() &&
                generatorKind == GeneratorKind::NotGenerator &&
                asyncKind == SyncFunction)
                ? DeclarationKind::SloppyLexicalFunction
                : DeclarationKind::LexicalFunction;
    } else {
        kind = pc->atModuleLevel()
               ? DeclarationKind::ModuleBodyLevelFunction
               : DeclarationKind::BodyLevelFunction;
    }

    if (!noteDeclaredName(name, kind, pos()))
        return null();

    Node pn = handler.newFunctionStatement(pos());
    if (!pn)
        return null();

    // Under sloppy mode, try Annex B.3.3 semantics. If making an additional
    // 'var' binding of the same name does not throw an early error, do so.
    // This 'var' binding would be assigned the function object when its
    // declaration is reached, not at the start of the block.
    //
    // This semantics is implemented upon Scope exit in
    // Scope::propagateAndMarkAnnexBFunctionBoxes.
    bool tryAnnexB = kind == DeclarationKind::SloppyLexicalFunction;

    YieldHandling newYieldHandling = GetYieldHandling(generatorKind);
    return functionDefinition(pn, toStringStart, InAllowed, newYieldHandling, name, Statement,
                              generatorKind, asyncKind, tryAnnexB);
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::functionExpr(uint32_t toStringStart, InvokedPrediction invoked,
                                          FunctionAsyncKind asyncKind)
{
    MOZ_ASSERT(tokenStream.isCurrentTokenType(TOK_FUNCTION));

    AutoAwaitIsKeyword<Parser> awaitIsKeyword(this, GetAwaitHandling(asyncKind));
    GeneratorKind generatorKind = GeneratorKind::NotGenerator;
    TokenKind tt;
    if (!tokenStream.getToken(&tt))
        return null();

    if (tt == TOK_MUL) {
        generatorKind = GeneratorKind::Generator;
        if (!tokenStream.getToken(&tt))
            return null();
    }

    YieldHandling yieldHandling = GetYieldHandling(generatorKind);

    RootedPropertyName name(context);
    if (TokenKindIsPossibleIdentifier(tt)) {
        name = bindingIdentifier(yieldHandling);
        if (!name)
            return null();
    } else {
        tokenStream.ungetToken();
    }

    Node pn = handler.newFunctionExpression(pos());
    if (!pn)
        return null();

    if (invoked)
        pn = handler.setLikelyIIFE(pn);

    return functionDefinition(pn, toStringStart, InAllowed, yieldHandling, name, Expression,
                              generatorKind, asyncKind);
}

/*
 * Return true if this node, known to be an unparenthesized string literal,
 * could be the string of a directive in a Directive Prologue. Directive
 * strings never contain escape sequences or line continuations.
 * isEscapeFreeStringLiteral, below, checks whether the node itself could be
 * a directive.
 */
static inline bool
IsEscapeFreeStringLiteral(const TokenPos& pos, JSAtom* str)
{
    /*
     * If the string's length in the source code is its length as a value,
     * accounting for the quotes, then it must not contain any escape
     * sequences or line continuations.
     */
    return pos.begin + str->length() + 2 == pos.end;
}

template <>
bool
Parser<SyntaxParseHandler, char16_t>::asmJS(Node list)
{
    // While asm.js could technically be validated and compiled during syntax
    // parsing, we have no guarantee that some later JS wouldn't abort the
    // syntax parse and cause us to re-parse (and re-compile) the asm.js module.
    // For simplicity, unconditionally abort the syntax parse when "use asm" is
    // encountered so that asm.js is always validated/compiled exactly once
    // during a full parse.
    JS_ALWAYS_FALSE(abortIfSyntaxParser());

    // Record that the current script source constains some AsmJS, to disable
    // any incremental encoder, as AsmJS cannot be encoded with XDR at the
    // moment.
    if (ss)
        ss->setContainsAsmJS();
    return false;
}

template <>
bool
Parser<FullParseHandler, char16_t>::asmJS(Node list)
{
    // Disable syntax parsing in anything nested inside the asm.js module.
    disableSyntaxParser();

    // We should be encountering the "use asm" directive for the first time; if
    // the directive is already, we must have failed asm.js validation and we're
    // reparsing. In that case, don't try to validate again. A non-null
    // newDirectives means we're not in a normal function.
    if (!pc->newDirectives || pc->newDirectives->asmJS())
        return true;

    // If there is no ScriptSource, then we are doing a non-compiling parse and
    // so we shouldn't (and can't, without a ScriptSource) compile.
    if (ss == nullptr)
        return true;

    ss->setContainsAsmJS();
    pc->functionBox()->useAsm = true;

    // Attempt to validate and compile this asm.js module. On success, the
    // tokenStream has been advanced to the closing }. On failure, the
    // tokenStream is in an indeterminate state and we must reparse the
    // function from the beginning. Reparsing is triggered by marking that a
    // new directive has been encountered and returning 'false'.
    bool validated;
    if (!CompileAsmJS(context, *this, list, &validated))
        return false;
    if (!validated) {
        pc->newDirectives->setAsmJS();
        return false;
    }

    return true;
}

/*
 * Recognize Directive Prologue members and directives. Assuming |pn| is a
 * candidate for membership in a directive prologue, recognize directives and
 * set |pc|'s flags accordingly. If |pn| is indeed part of a prologue, set its
 * |pn_prologue| flag.
 *
 * Note that the following is a strict mode function:
 *
 * function foo() {
 *   "blah" // inserted semi colon
 *        "blurgh"
 *   "use\x20loose"
 *   "use strict"
 * }
 *
 * That is, even though "use\x20loose" can never be a directive, now or in the
 * future (because of the hex escape), the Directive Prologue extends through it
 * to the "use strict" statement, which is indeed a directive.
 */
template <class ParseHandler, typename CharT>
bool
Parser<ParseHandler, CharT>::maybeParseDirective(Node list, Node possibleDirective, bool* cont)
{
    TokenPos directivePos;
    JSAtom* directive = handler.isStringExprStatement(possibleDirective, &directivePos);

    *cont = !!directive;
    if (!*cont)
        return true;

    if (IsEscapeFreeStringLiteral(directivePos, directive)) {
        // Mark this statement as being a possibly legitimate part of a
        // directive prologue, so the bytecode emitter won't warn about it being
        // useless code. (We mustn't just omit the statement entirely yet, as it
        // could be producing the value of an eval or JSScript execution.)
        //
        // Note that even if the string isn't one we recognize as a directive,
        // the emitter still shouldn't flag it as useless, as it could become a
        // directive in the future. We don't want to interfere with people
        // taking advantage of directive-prologue-enabled features that appear
        // in other browsers first.
        handler.setInDirectivePrologue(possibleDirective);

        if (directive == context->names().useStrict) {
            // Functions with non-simple parameter lists (destructuring,
            // default or rest parameters) must not contain a "use strict"
            // directive.
            if (pc->isFunctionBox()) {
                FunctionBox* funbox = pc->functionBox();
                if (!funbox->hasSimpleParameterList()) {
                    const char* parameterKind = funbox->hasDestructuringArgs
                                                ? "destructuring"
                                                : funbox->hasParameterExprs
                                                ? "default"
                                                : "rest";
                    errorAt(directivePos.begin, JSMSG_STRICT_NON_SIMPLE_PARAMS, parameterKind);
                    return false;
                }
            }

            // We're going to be in strict mode. Note that this scope explicitly
            // had "use strict";
            pc->sc()->setExplicitUseStrict();
            if (!pc->sc()->strict()) {
                // We keep track of the one possible strict violation that could
                // occur in the directive prologue -- octal escapes -- and
                // complain now.
                if (tokenStream.sawOctalEscape()) {
                    error(JSMSG_DEPRECATED_OCTAL);
                    return false;
                }
                pc->sc()->strictScript = true;
            }
        } else if (directive == context->names().useAsm) {
            if (pc->isFunctionBox())
                return asmJS(list);
            return warningAt(directivePos.begin, JSMSG_USE_ASM_DIRECTIVE_FAIL);
        }
    }
    return true;
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::statementList(YieldHandling yieldHandling)
{
    if (!CheckRecursionLimit(context))
        return null();

    Node pn = handler.newStatementList(pos());
    if (!pn)
        return null();

    bool canHaveDirectives = pc->atBodyLevel();
    if (canHaveDirectives)
        tokenStream.clearSawOctalEscape();
    bool afterReturn = false;
    bool warnedAboutStatementsAfterReturn = false;
    uint32_t statementBegin = 0;
    for (;;) {
        TokenKind tt = TOK_EOF;
        if (!tokenStream.peekToken(&tt, TokenStream::Operand)) {
            if (tokenStream.isEOF())
                isUnexpectedEOF_ = true;
            return null();
        }
        if (tt == TOK_EOF || tt == TOK_RC) {
            TokenPos pos;
            if (!tokenStream.peekTokenPos(&pos, TokenStream::Operand)) {
                return null();
            }
            handler.setListEndPosition(pn, pos);
            break;
        }
        if (afterReturn) {
            if (!tokenStream.peekOffset(&statementBegin, TokenStream::Operand))
                return null();
        }
        Node next = statementListItem(yieldHandling, canHaveDirectives);
        if (!next) {
            if (tokenStream.isEOF())
                isUnexpectedEOF_ = true;
            return null();
        }
        if (!warnedAboutStatementsAfterReturn) {
            if (afterReturn) {
                if (!handler.isStatementPermittedAfterReturnStatement(next)) {
                    if (!warningAt(statementBegin, JSMSG_STMT_AFTER_RETURN))
                        return null();

                    warnedAboutStatementsAfterReturn = true;
                }
            } else if (handler.isReturnStatement(next)) {
                afterReturn = true;
            }
        }

        if (canHaveDirectives) {
            if (!maybeParseDirective(pn, next, &canHaveDirectives))
                return null();
        }

        handler.addStatementToList(pn, next);
    }

    return pn;
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::condition(InHandling inHandling, YieldHandling yieldHandling)
{
    MUST_MATCH_TOKEN(TOK_LP, JSMSG_PAREN_BEFORE_COND);

    Node pn = exprInParens(inHandling, yieldHandling, TripledotProhibited);
    if (!pn)
        return null();

    MUST_MATCH_TOKEN_MOD(TOK_RP, TokenStream::Operand, JSMSG_PAREN_AFTER_COND);

    /* Check for (a = b) and warn about possible (a == b) mistype. */
    if (handler.isUnparenthesizedAssignment(pn)) {
        if (!extraWarning(JSMSG_EQUAL_AS_ASSIGN))
            return null();
    }
    return pn;
}

template <class ParseHandler, typename CharT>
bool
Parser<ParseHandler, CharT>::matchLabel(YieldHandling yieldHandling,
                                        MutableHandle<PropertyName*> label)
{
    TokenKind tt = TOK_EOF;
    if (!tokenStream.peekTokenSameLine(&tt, TokenStream::Operand))
        return false;

    if (TokenKindIsPossibleIdentifier(tt)) {
        tokenStream.consumeKnownToken(tt, TokenStream::Operand);

        label.set(labelIdentifier(yieldHandling));
        if (!label)
            return false;
    } else {
        label.set(nullptr);
    }
    return true;
}

template <class ParseHandler, typename CharT>
Parser<ParseHandler, CharT>::PossibleError::PossibleError(Parser<ParseHandler, CharT>& parser)
  : parser_(parser)
{}

template <class ParseHandler, typename CharT>
typename Parser<ParseHandler, CharT>::PossibleError::Error&
Parser<ParseHandler, CharT>::PossibleError::error(ErrorKind kind)
{
    if (kind == ErrorKind::Expression)
        return exprError_;
    if (kind == ErrorKind::Destructuring)
        return destructuringError_;
    MOZ_ASSERT(kind == ErrorKind::DestructuringWarning);
    return destructuringWarning_;
}

template <class ParseHandler, typename CharT>
void
Parser<ParseHandler, CharT>::PossibleError::setResolved(ErrorKind kind)
{
    error(kind).state_ = ErrorState::None;
}

template <class ParseHandler, typename CharT>
bool
Parser<ParseHandler, CharT>::PossibleError::hasError(ErrorKind kind)
{
    return error(kind).state_ == ErrorState::Pending;
}

template <class ParseHandler, typename CharT>
bool
Parser<ParseHandler, CharT>::PossibleError::hasPendingDestructuringError()
{
    return hasError(ErrorKind::Destructuring);
}

template <class ParseHandler, typename CharT>
void
Parser<ParseHandler, CharT>::PossibleError::setPending(ErrorKind kind, const TokenPos& pos,
                                                       unsigned errorNumber)
{
    // Don't overwrite a previously recorded error.
    if (hasError(kind))
        return;

    // If we report an error later, we'll do it from the position where we set
    // the state to pending.
    Error& err = error(kind);
    err.offset_ = pos.begin;
    err.errorNumber_ = errorNumber;
    err.state_ = ErrorState::Pending;
}

template <class ParseHandler, typename CharT>
void
Parser<ParseHandler, CharT>::PossibleError::setPendingDestructuringErrorAt(const TokenPos& pos,
                                                                           unsigned errorNumber)
{
    setPending(ErrorKind::Destructuring, pos, errorNumber);
}

template <class ParseHandler, typename CharT>
void
Parser<ParseHandler, CharT>::PossibleError::setPendingDestructuringWarningAt(const TokenPos& pos,
                                                                             unsigned errorNumber)
{
    setPending(ErrorKind::DestructuringWarning, pos, errorNumber);
}

template <class ParseHandler, typename CharT>
void
Parser<ParseHandler, CharT>::PossibleError::setPendingExpressionErrorAt(const TokenPos& pos,
                                                                        unsigned errorNumber)
{
    setPending(ErrorKind::Expression, pos, errorNumber);
}

template <class ParseHandler, typename CharT>
bool
Parser<ParseHandler, CharT>::PossibleError::checkForError(ErrorKind kind)
{
    if (!hasError(kind))
        return true;

    Error& err = error(kind);
    parser_.errorAt(err.offset_, err.errorNumber_);
    return false;
}

template <class ParseHandler, typename CharT>
bool
Parser<ParseHandler, CharT>::PossibleError::checkForWarning(ErrorKind kind)
{
    if (!hasError(kind))
        return true;

    Error& err = error(kind);
    return parser_.extraWarningAt(err.offset_, err.errorNumber_);
}

template <class ParseHandler, typename CharT>
bool
Parser<ParseHandler, CharT>::PossibleError::checkForDestructuringErrorOrWarning()
{
    // Clear pending expression error, because we're definitely not in an
    // expression context.
    setResolved(ErrorKind::Expression);

    // Report any pending destructuring error or warning.
    return checkForError(ErrorKind::Destructuring) &&
           checkForWarning(ErrorKind::DestructuringWarning);
}

template <class ParseHandler, typename CharT>
bool
Parser<ParseHandler, CharT>::PossibleError::checkForExpressionError()
{
    // Clear pending destructuring error or warning, because we're definitely
    // not in a destructuring context.
    setResolved(ErrorKind::Destructuring);
    setResolved(ErrorKind::DestructuringWarning);

    // Report any pending expression error.
    return checkForError(ErrorKind::Expression);
}

template <class ParseHandler, typename CharT>
void
Parser<ParseHandler, CharT>::PossibleError::transferErrorTo(ErrorKind kind, PossibleError* other)
{
    if (hasError(kind) && !other->hasError(kind)) {
        Error& err = error(kind);
        Error& otherErr = other->error(kind);
        otherErr.offset_ = err.offset_;
        otherErr.errorNumber_ = err.errorNumber_;
        otherErr.state_ = err.state_;
    }
}

template <class ParseHandler, typename CharT>
void
Parser<ParseHandler, CharT>::PossibleError::transferErrorsTo(PossibleError* other)
{
    MOZ_ASSERT(other);
    MOZ_ASSERT(this != other);
    MOZ_ASSERT(&parser_ == &other->parser_,
               "Can't transfer fields to an instance which belongs to a different parser");

    transferErrorTo(ErrorKind::Destructuring, other);
    transferErrorTo(ErrorKind::Expression, other);
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::bindingInitializer(Node lhs, DeclarationKind kind,
                                                YieldHandling yieldHandling)
{
    MOZ_ASSERT(tokenStream.isCurrentTokenType(TOK_ASSIGN));

    if (kind == DeclarationKind::FormalParameter)
        pc->functionBox()->hasParameterExprs = true;

    Node rhs = assignExpr(InAllowed, yieldHandling, TripledotProhibited);
    if (!rhs)
        return null();

    handler.checkAndSetIsDirectRHSAnonFunction(rhs);

    Node assign = handler.newAssignment(PNK_ASSIGN, lhs, rhs);
    if (!assign)
        return null();

    if (foldConstants && !FoldConstants(context, &assign, this))
        return null();

    return assign;
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::bindingIdentifier(DeclarationKind kind, YieldHandling yieldHandling)
{
    RootedPropertyName name(context, bindingIdentifier(yieldHandling));
    if (!name)
        return null();

    Node binding = newName(name);
    if (!binding || !noteDeclaredName(name, kind, pos()))
        return null();

    return binding;
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::bindingIdentifierOrPattern(DeclarationKind kind,
                                                        YieldHandling yieldHandling, TokenKind tt)
{
    if (tt == TOK_LB)
        return arrayBindingPattern(kind, yieldHandling);

    if (tt == TOK_LC)
        return objectBindingPattern(kind, yieldHandling);

    if (!TokenKindIsPossibleIdentifierName(tt)) {
        error(JSMSG_NO_VARIABLE_NAME);
        return null();
    }

    return bindingIdentifier(kind, yieldHandling);
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::objectBindingPattern(DeclarationKind kind,
                                                  YieldHandling yieldHandling)
{
    MOZ_ASSERT(tokenStream.isCurrentTokenType(TOK_LC));

    if (!CheckRecursionLimit(context))
        return null();

    uint32_t begin = pos().begin;
    Node literal = handler.newObjectLiteral(begin);
    if (!literal)
        return null();

    Maybe<DeclarationKind> declKind = Some(kind);
    RootedAtom propAtom(context);
    for (;;) {
        TokenKind tt;
        if (!tokenStream.peekToken(&tt))
            return null();
        if (tt == TOK_RC) {
            tokenStream.addModifierException(TokenStream::OperandIsNone);
            break;
        }

        if (tt == TOK_TRIPLEDOT) {
            tokenStream.consumeKnownToken(TOK_TRIPLEDOT);
            uint32_t begin = pos().begin;

            TokenKind tt;
            if (!tokenStream.getToken(&tt))
                return null();

            if (!TokenKindIsPossibleIdentifierName(tt)) {
                error(JSMSG_NO_VARIABLE_NAME);
                return null();
            }

            Node inner = bindingIdentifier(kind, yieldHandling);
            if (!inner)
                return null();

            if (!handler.addSpreadProperty(literal, begin, inner))
                return null();
        } else {
            TokenPos namePos = tokenStream.nextToken().pos;

            PropertyType propType;
            Node propName = propertyName(yieldHandling, declKind, literal, &propType, &propAtom);
            if (!propName)
                return null();

            if (propType == PropertyType::Normal) {
                // Handle e.g., |var {p: x} = o| and |var {p: x=0} = o|.

                if (!tokenStream.getToken(&tt, TokenStream::Operand))
                    return null();

                Node binding = bindingIdentifierOrPattern(kind, yieldHandling, tt);
                if (!binding)
                    return null();

                bool hasInitializer;
                if (!tokenStream.matchToken(&hasInitializer, TOK_ASSIGN, TokenStream::Operand))
                    return null();

                Node bindingExpr = hasInitializer
                                   ? bindingInitializer(binding, kind, yieldHandling)
                                   : binding;
                if (!bindingExpr)
                    return null();

                if (!handler.addPropertyDefinition(literal, propName, bindingExpr))
                    return null();
            } else if (propType == PropertyType::Shorthand) {
                // Handle e.g., |var {x, y} = o| as destructuring shorthand
                // for |var {x: x, y: y} = o|.
                MOZ_ASSERT(TokenKindIsPossibleIdentifierName(tt));

                Node binding = bindingIdentifier(kind, yieldHandling);
                if (!binding)
                    return null();

                if (!handler.addShorthand(literal, propName, binding))
                    return null();
            } else if (propType == PropertyType::CoverInitializedName) {
                // Handle e.g., |var {x=1, y=2} = o| as destructuring
                // shorthand with default values.
                MOZ_ASSERT(TokenKindIsPossibleIdentifierName(tt));

                Node binding = bindingIdentifier(kind, yieldHandling);
                if (!binding)
                    return null();

                tokenStream.consumeKnownToken(TOK_ASSIGN);

                Node bindingExpr = bindingInitializer(binding, kind, yieldHandling);
                if (!bindingExpr)
                    return null();

                if (!handler.addPropertyDefinition(literal, propName, bindingExpr))
                    return null();
            } else {
                errorAt(namePos.begin, JSMSG_NO_VARIABLE_NAME);
                return null();
            }
        }

        bool matched;
        if (!tokenStream.matchToken(&matched, TOK_COMMA, TokenStream::Operand))
            return null();
        if (!matched)
            break;
        if (tt == TOK_TRIPLEDOT) {
            error(JSMSG_REST_WITH_COMMA);
            return null();
        }
    }

    MUST_MATCH_TOKEN_MOD_WITH_REPORT(TOK_RC, TokenStream::Operand,
                                     reportMissingClosing(JSMSG_CURLY_AFTER_LIST,
                                                          JSMSG_CURLY_OPENED, begin));

    handler.setEndPosition(literal, pos().end);
    return literal;
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::arrayBindingPattern(DeclarationKind kind, YieldHandling yieldHandling)
{
    MOZ_ASSERT(tokenStream.isCurrentTokenType(TOK_LB));

    if (!CheckRecursionLimit(context))
        return null();

    uint32_t begin = pos().begin;
    Node literal = handler.newArrayLiteral(begin);
    if (!literal)
        return null();

     uint32_t index = 0;
     for (; ; index++) {
         if (index >= NativeObject::MAX_DENSE_ELEMENTS_COUNT) {
             error(JSMSG_ARRAY_INIT_TOO_BIG);
             return null();
         }

         TokenKind tt;
         if (!tokenStream.getToken(&tt))
             return null();

         if (tt == TOK_RB) {
             tokenStream.ungetToken();
             tokenStream.addModifierException(TokenStream::OperandIsNone);
             break;
         }

         if (tt == TOK_COMMA) {
             if (!handler.addElision(literal, pos()))
                 return null();
         } else if (tt == TOK_TRIPLEDOT) {
             uint32_t begin = pos().begin;

             TokenKind tt;
             if (!tokenStream.getToken(&tt))
                 return null();

             Node inner = bindingIdentifierOrPattern(kind, yieldHandling, tt);
             if (!inner)
                 return null();

             if (!handler.addSpreadElement(literal, begin, inner))
                 return null();
         } else {
             Node binding = bindingIdentifierOrPattern(kind, yieldHandling, tt);
             if (!binding)
                 return null();

             bool hasInitializer;
             if (!tokenStream.matchToken(&hasInitializer, TOK_ASSIGN, TokenStream::Operand))
                 return null();

             Node element = hasInitializer
                            ? bindingInitializer(binding, kind, yieldHandling)
                            : binding;
             if (!element)
                 return null();

             handler.addArrayElement(literal, element);
         }

         if (tt != TOK_COMMA) {
             // If we didn't already match TOK_COMMA in above case.
             bool matched;
             if (!tokenStream.matchToken(&matched, TOK_COMMA, TokenStream::Operand))
                 return null();
             if (!matched)
                 break;

             if (tt == TOK_TRIPLEDOT) {
                 error(JSMSG_REST_WITH_COMMA);
                 return null();
             }
         }
     }

     MUST_MATCH_TOKEN_MOD_WITH_REPORT(TOK_RB, TokenStream::Operand,
                                      reportMissingClosing(JSMSG_BRACKET_AFTER_LIST,
                                                           JSMSG_BRACKET_OPENED, begin));

    handler.setEndPosition(literal, pos().end);
    return literal;
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::destructuringDeclaration(DeclarationKind kind,
                                                      YieldHandling yieldHandling,
                                                      TokenKind tt)
{
    MOZ_ASSERT(tokenStream.isCurrentTokenType(tt));
    MOZ_ASSERT(tt == TOK_LB || tt == TOK_LC);

    return tt == TOK_LB
           ? arrayBindingPattern(kind, yieldHandling)
           : objectBindingPattern(kind, yieldHandling);
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::destructuringDeclarationWithoutYieldOrAwait(DeclarationKind kind,
                                                                         YieldHandling yieldHandling,
                                                                         TokenKind tt)
{
    uint32_t startYieldOffset = pc->lastYieldOffset;
    uint32_t startAwaitOffset = pc->lastAwaitOffset;
    Node res = destructuringDeclaration(kind, yieldHandling, tt);
    if (res) {
        if (pc->lastYieldOffset != startYieldOffset) {
            errorAt(pc->lastYieldOffset, JSMSG_YIELD_IN_DEFAULT);
            return null();
        }
        if (pc->lastAwaitOffset != startAwaitOffset) {
            errorAt(pc->lastAwaitOffset, JSMSG_AWAIT_IN_DEFAULT);
            return null();
        }
    }
    return res;
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::blockStatement(YieldHandling yieldHandling, unsigned errorNumber)
{
    MOZ_ASSERT(tokenStream.isCurrentTokenType(TOK_LC));
    uint32_t openedPos = pos().begin;

    ParseContext::Statement stmt(pc, StatementKind::Block);
    ParseContext::Scope scope(this);
    if (!scope.init(pc))
        return null();

    Node list = statementList(yieldHandling);
    if (!list)
        return null();

    MUST_MATCH_TOKEN_MOD_WITH_REPORT(TOK_RC, TokenStream::Operand,
                                     reportMissingClosing(errorNumber, JSMSG_CURLY_OPENED,
                                                          openedPos));

    return finishLexicalScope(scope, list);
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::expressionAfterForInOrOf(ParseNodeKind forHeadKind,
                                                      YieldHandling yieldHandling)
{
    MOZ_ASSERT(forHeadKind == PNK_FORIN || forHeadKind == PNK_FOROF);
    Node pn = forHeadKind == PNK_FOROF
           ? assignExpr(InAllowed, yieldHandling, TripledotProhibited)
           : expr(InAllowed, yieldHandling, TripledotProhibited);
    return pn;
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::declarationPattern(Node decl, DeclarationKind declKind, TokenKind tt,
                                                bool initialDeclaration,
                                                YieldHandling yieldHandling,
                                                ParseNodeKind* forHeadKind,
                                                Node* forInOrOfExpression)
{
    MOZ_ASSERT(tokenStream.isCurrentTokenType(TOK_LB) ||
               tokenStream.isCurrentTokenType(TOK_LC));

    Node pattern = destructuringDeclaration(declKind, yieldHandling, tt);
    if (!pattern)
        return null();

    if (initialDeclaration && forHeadKind) {
        bool isForIn, isForOf;
        if (!matchInOrOf(&isForIn, &isForOf))
            return null();

        if (isForIn) {
            *forHeadKind = PNK_FORIN;
        } else if (isForOf) {
            *forHeadKind = PNK_FOROF;

            // Annex B.3.5 has different early errors for vars in for-of loops.
            if (declKind == DeclarationKind::Var)
                declKind = DeclarationKind::ForOfVar;
        } else {
            *forHeadKind = PNK_FORHEAD;
        }

        if (*forHeadKind != PNK_FORHEAD) {
            *forInOrOfExpression = expressionAfterForInOrOf(*forHeadKind, yieldHandling);
            if (!*forInOrOfExpression)
                return null();

            return pattern;
        }
    }

    MUST_MATCH_TOKEN_MOD(TOK_ASSIGN, TokenStream::Operand, JSMSG_BAD_DESTRUCT_DECL);

    Node init = assignExpr(forHeadKind ? InProhibited : InAllowed,
                           yieldHandling, TripledotProhibited);
    if (!init)
        return null();

    handler.checkAndSetIsDirectRHSAnonFunction(init);

    return handler.newAssignment(PNK_ASSIGN, pattern, init);
}

template <class ParseHandler, typename CharT>
bool
Parser<ParseHandler, CharT>::initializerInNameDeclaration(Node decl, Node binding,
                                                          Handle<PropertyName*> name,
                                                          DeclarationKind declKind,
                                                          bool initialDeclaration,
                                                          YieldHandling yieldHandling,
                                                          ParseNodeKind* forHeadKind,
                                                          Node* forInOrOfExpression)
{
    MOZ_ASSERT(tokenStream.isCurrentTokenType(TOK_ASSIGN));

    uint32_t initializerOffset;
    if (!tokenStream.peekOffset(&initializerOffset, TokenStream::Operand))
        return false;

    Node initializer = assignExpr(forHeadKind ? InProhibited : InAllowed,
                                  yieldHandling, TripledotProhibited);
    if (!initializer)
        return false;

    handler.checkAndSetIsDirectRHSAnonFunction(initializer);

    if (forHeadKind && initialDeclaration) {
        bool isForIn, isForOf;
        if (!matchInOrOf(&isForIn, &isForOf))
            return false;

        // An initialized declaration can't appear in a for-of:
        //
        //   for (var/let/const x = ... of ...); // BAD
        if (isForOf) {
            errorAt(initializerOffset, JSMSG_OF_AFTER_FOR_LOOP_DECL);
            return false;
        }

        if (isForIn) {
            // Lexical declarations in for-in loops can't be initialized:
            //
            //   for (let/const x = ... in ...); // BAD
            if (DeclarationKindIsLexical(declKind)) {
                errorAt(initializerOffset, JSMSG_IN_AFTER_LEXICAL_FOR_DECL);
                return false;
            }

            // This leaves only initialized for-in |var| declarations.  ES6
            // forbids these; later ES un-forbids in non-strict mode code.
            *forHeadKind = PNK_FORIN;
            if (!strictModeErrorAt(initializerOffset, JSMSG_INVALID_FOR_IN_DECL_WITH_INIT))
                return false;

            *forInOrOfExpression = expressionAfterForInOrOf(PNK_FORIN, yieldHandling);
            if (!*forInOrOfExpression)
                return false;
        } else {
            *forHeadKind = PNK_FORHEAD;
        }
    }

    return handler.finishInitializerAssignment(binding, initializer);
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::declarationName(Node decl, DeclarationKind declKind, TokenKind tt,
                                             bool initialDeclaration, YieldHandling yieldHandling,
                                             ParseNodeKind* forHeadKind, Node* forInOrOfExpression)
{
    // Anything other than possible identifier is an error.
    if (!TokenKindIsPossibleIdentifier(tt)) {
        error(JSMSG_NO_VARIABLE_NAME);
        return null();
    }

    RootedPropertyName name(context, bindingIdentifier(yieldHandling));
    if (!name)
        return null();

    Node binding = newName(name);
    if (!binding)
        return null();

    TokenPos namePos = pos();

    // The '=' context after a variable name in a declaration is an opportunity
    // for ASI, and thus for the next token to start an ExpressionStatement:
    //
    //  var foo   // VariableDeclaration
    //  /bar/g;   // ExpressionStatement
    //
    // Therefore get the token here as Operand.
    bool matched;
    if (!tokenStream.matchToken(&matched, TOK_ASSIGN, TokenStream::Operand))
        return null();

    if (matched) {
        if (!initializerInNameDeclaration(decl, binding, name, declKind, initialDeclaration,
                                          yieldHandling, forHeadKind, forInOrOfExpression))
        {
            return null();
        }
    } else {
        if (initialDeclaration && forHeadKind) {
            bool isForIn, isForOf;
            if (!matchInOrOf(&isForIn, &isForOf))
                return null();

            if (isForIn) {
                *forHeadKind = PNK_FORIN;
            } else if (isForOf) {
                *forHeadKind = PNK_FOROF;

                // Annex B.3.5 has different early errors for vars in for-of loops.
                if (declKind == DeclarationKind::Var)
                    declKind = DeclarationKind::ForOfVar;
            } else {
                *forHeadKind = PNK_FORHEAD;
            }
        }

        if (forHeadKind && *forHeadKind != PNK_FORHEAD) {
            *forInOrOfExpression = expressionAfterForInOrOf(*forHeadKind, yieldHandling);
            if (!*forInOrOfExpression)
                return null();
        } else {
            // Normal const declarations, and const declarations in for(;;)
            // heads, must be initialized.
            if (declKind == DeclarationKind::Const) {
                errorAt(namePos.begin, JSMSG_BAD_CONST_DECL);
                return null();
            }
        }
    }

    // Note the declared name after knowing whether or not we are in a for-of
    // loop, due to special early error semantics in Annex B.3.5.
    if (!noteDeclaredName(name, declKind, namePos))
        return null();

    return binding;
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::declarationList(YieldHandling yieldHandling,
                                             ParseNodeKind kind,
                                             ParseNodeKind* forHeadKind /* = nullptr */,
                                             Node* forInOrOfExpression /* = nullptr */)
{
    MOZ_ASSERT(kind == PNK_VAR || kind == PNK_LET || kind == PNK_CONST);

    DeclarationKind declKind;
    switch (kind) {
      case PNK_VAR:
        declKind = DeclarationKind::Var;
        break;
      case PNK_CONST:
        declKind = DeclarationKind::Const;
        break;
      case PNK_LET:
        declKind = DeclarationKind::Let;
        break;
      default:
        MOZ_CRASH("Unknown declaration kind");
    }

    Node decl = handler.newDeclarationList(kind, pos());
    if (!decl)
        return null();

    bool moreDeclarations;
    bool initialDeclaration = true;
    do {
        MOZ_ASSERT_IF(!initialDeclaration && forHeadKind,
                      *forHeadKind == PNK_FORHEAD);

        TokenKind tt;
        if (!tokenStream.getToken(&tt))
            return null();

        Node binding = (tt == TOK_LB || tt == TOK_LC)
                       ? declarationPattern(decl, declKind, tt, initialDeclaration, yieldHandling,
                                            forHeadKind, forInOrOfExpression)
                       : declarationName(decl, declKind, tt, initialDeclaration, yieldHandling,
                                         forHeadKind, forInOrOfExpression);
        if (!binding)
            return null();

        handler.addList(decl, binding);

        // If we have a for-in/of loop, the above call matches the entirety
        // of the loop head (up to the closing parenthesis).
        if (forHeadKind && *forHeadKind != PNK_FORHEAD)
            break;

        initialDeclaration = false;

        if (!tokenStream.matchToken(&moreDeclarations, TOK_COMMA, TokenStream::Operand))
            return null();
    } while (moreDeclarations);

    return decl;
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::lexicalDeclaration(YieldHandling yieldHandling, DeclarationKind kind)
{
    MOZ_ASSERT(kind == DeclarationKind::Const || kind == DeclarationKind::Let);

    /*
     * Parse body-level lets without a new block object. ES6 specs
     * that an execution environment's initial lexical environment
     * is the VariableEnvironment, i.e., body-level lets are in
     * the same environment record as vars.
     *
     * However, they cannot be parsed exactly as vars, as ES6
     * requires that uninitialized lets throw ReferenceError on use.
     *
     * See 8.1.1.1.6 and the note in 13.2.1.
     */
    Node decl = declarationList(yieldHandling,
                                kind == DeclarationKind::Const ? PNK_CONST : PNK_LET);
    if (!decl || !matchOrInsertSemicolon())
        return null();

    return decl;
}

template <>
bool
Parser<FullParseHandler, char16_t>::namedImportsOrNamespaceImport(TokenKind tt, Node importSpecSet)
{
    if (tt == TOK_LC) {
        while (true) {
            // Handle the forms |import {} from 'a'| and
            // |import { ..., } from 'a'| (where ... is non empty), by
            // escaping the loop early if the next token is }.
            if (!tokenStream.getToken(&tt))
                return false;

            if (tt == TOK_RC)
                break;

            if (!TokenKindIsPossibleIdentifierName(tt)) {
                error(JSMSG_NO_IMPORT_NAME);
                return false;
            }

            Rooted<PropertyName*> importName(context, tokenStream.currentName());
            TokenPos importNamePos = pos();

            bool matched;
            if (!tokenStream.matchToken(&matched, TOK_AS))
                return null();

            if (matched) {
                TokenKind afterAs;
                if (!tokenStream.getToken(&afterAs))
                    return false;

                if (!TokenKindIsPossibleIdentifierName(afterAs)) {
                    error(JSMSG_NO_BINDING_NAME);
                    return false;
                }
            } else {
                // Keywords cannot be bound to themselves, so an import name
                // that is a keyword is a syntax error if it is not followed
                // by the keyword 'as'.
                // See the ImportSpecifier production in ES6 section 15.2.2.
                if (IsKeyword(importName)) {
                    error(JSMSG_AS_AFTER_RESERVED_WORD, ReservedWordToCharZ(importName));
                    return false;
                }
            }

            RootedPropertyName bindingAtom(context, importedBinding());
            if (!bindingAtom)
                return false;

            Node bindingName = newName(bindingAtom);
            if (!bindingName)
                return false;
            if (!noteDeclaredName(bindingAtom, DeclarationKind::Import, pos()))
                return false;

            Node importNameNode = newName(importName, importNamePos);
            if (!importNameNode)
                return false;

            Node importSpec = handler.newImportSpec(importNameNode, bindingName);
            if (!importSpec)
                return false;

            handler.addList(importSpecSet, importSpec);

            TokenKind next;
            if (!tokenStream.getToken(&next))
                return false;

            if (next == TOK_RC)
                break;

            if (next != TOK_COMMA) {
                error(JSMSG_RC_AFTER_IMPORT_SPEC_LIST);
                return false;
            }
        }
    } else {
        MOZ_ASSERT(tt == TOK_MUL);

        MUST_MATCH_TOKEN(TOK_AS, JSMSG_AS_AFTER_IMPORT_STAR);

        MUST_MATCH_TOKEN_FUNC(TokenKindIsPossibleIdentifierName, JSMSG_NO_BINDING_NAME);

        Node importName = newName(context->names().star);
        if (!importName)
            return false;

        // Namespace imports are are not indirect bindings but lexical
        // definitions that hold a module namespace object. They are treated
        // as const variables which are initialized during the
        // ModuleInstantiate step.
        RootedPropertyName bindingName(context, importedBinding());
        if (!bindingName)
            return false;
        Node bindingNameNode = newName(bindingName);
        if (!bindingNameNode)
            return false;
        if (!noteDeclaredName(bindingName, DeclarationKind::Const, pos()))
            return false;

        // The namespace import name is currently required to live on the
        // environment.
        pc->varScope().lookupDeclaredName(bindingName)->value()->setClosedOver();

        Node importSpec = handler.newImportSpec(importName, bindingNameNode);
        if (!importSpec)
            return false;

        handler.addList(importSpecSet, importSpec);
    }

    return true;
}

template<>
bool
Parser<SyntaxParseHandler, char16_t>::namedImportsOrNamespaceImport(TokenKind tt,
                                                                    Node importSpecSet)
{
    MOZ_ALWAYS_FALSE(abortIfSyntaxParser());
    return false;
}

template<>
ParseNode*
Parser<FullParseHandler, char16_t>::importDeclaration()
{
    MOZ_ASSERT(tokenStream.currentToken().type == TOK_IMPORT);

    if (!pc->atModuleLevel()) {
        error(JSMSG_IMPORT_DECL_AT_TOP_LEVEL);
        return null();
    }

    uint32_t begin = pos().begin;
    TokenKind tt;
    if (!tokenStream.getToken(&tt))
        return null();

    Node importSpecSet = handler.newList(PNK_IMPORT_SPEC_LIST, pos());
    if (!importSpecSet)
        return null();

    if (tt == TOK_STRING) {
        // Handle the form |import 'a'| by leaving the list empty. This is
        // equivalent to |import {} from 'a'|.
        importSpecSet->pn_pos.end = importSpecSet->pn_pos.begin;
    } else {
        if (tt == TOK_LC || tt == TOK_MUL) {
            if (!namedImportsOrNamespaceImport(tt, importSpecSet))
                return null();
        } else if (TokenKindIsPossibleIdentifierName(tt)) {
            // Handle the form |import a from 'b'|, by adding a single import
            // specifier to the list, with 'default' as the import name and
            // 'a' as the binding name. This is equivalent to
            // |import { default as a } from 'b'|.
            Node importName = newName(context->names().default_);
            if (!importName)
                return null();

            RootedPropertyName bindingAtom(context, importedBinding());
            if (!bindingAtom)
                return null();

            Node bindingName = newName(bindingAtom);
            if (!bindingName)
                return null();

            if (!noteDeclaredName(bindingAtom, DeclarationKind::Import, pos()))
                return null();

            Node importSpec = handler.newImportSpec(importName, bindingName);
            if (!importSpec)
                return null();

            handler.addList(importSpecSet, importSpec);

            if (!tokenStream.peekToken(&tt))
                return null();

            if (tt == TOK_COMMA) {
                tokenStream.consumeKnownToken(tt);
                if (!tokenStream.getToken(&tt))
                    return null();

                if (tt != TOK_LC && tt != TOK_MUL) {
                    error(JSMSG_NAMED_IMPORTS_OR_NAMESPACE_IMPORT);
                    return null();
                }

                if (!namedImportsOrNamespaceImport(tt, importSpecSet))
                    return null();
            }
        } else {
            error(JSMSG_DECLARATION_AFTER_IMPORT);
            return null();
        }

        MUST_MATCH_TOKEN(TOK_FROM, JSMSG_FROM_AFTER_IMPORT_CLAUSE);

        MUST_MATCH_TOKEN(TOK_STRING, JSMSG_MODULE_SPEC_AFTER_FROM);
    }

    Node moduleSpec = stringLiteral();
    if (!moduleSpec)
        return null();

    if (!matchOrInsertSemicolon())
        return null();

    ParseNode* node =
        handler.newImportDeclaration(importSpecSet, moduleSpec, TokenPos(begin, pos().end));
    if (!node || !pc->sc()->asModuleContext()->builder.processImport(node))
        return null();

    return node;
}

template<>
SyntaxParseHandler::Node
Parser<SyntaxParseHandler, char16_t>::importDeclaration()
{
    MOZ_ALWAYS_FALSE(abortIfSyntaxParser());
    return SyntaxParseHandler::NodeFailure;
}

template<>
bool
Parser<FullParseHandler, char16_t>::checkExportedName(JSAtom* exportName)
{
    if (!pc->sc()->asModuleContext()->builder.hasExportedName(exportName))
        return true;

    JSAutoByteString str;
    if (!AtomToPrintableString(context, exportName, &str))
        return false;

    error(JSMSG_DUPLICATE_EXPORT_NAME, str.ptr());
    return false;
}

template<>
bool
Parser<SyntaxParseHandler, char16_t>::checkExportedName(JSAtom* exportName)
{
    MOZ_ALWAYS_FALSE(abortIfSyntaxParser());
    return false;
}

template<>
bool
Parser<FullParseHandler, char16_t>::checkExportedNamesForDeclaration(ParseNode* node)
{
    MOZ_ASSERT(node->isArity(PN_LIST));
    for (ParseNode* binding = node->pn_head; binding; binding = binding->pn_next) {
        if (binding->isKind(PNK_ASSIGN))
            binding = binding->pn_left;
        MOZ_ASSERT(binding->isKind(PNK_NAME));
        if (!checkExportedName(binding->pn_atom))
            return false;
    }

    return true;
}

template<>
bool
Parser<SyntaxParseHandler, char16_t>::checkExportedNamesForDeclaration(Node node)
{
    MOZ_ALWAYS_FALSE(abortIfSyntaxParser());
    return false;
}

template<>
bool
Parser<FullParseHandler, char16_t>::checkExportedNameForClause(ParseNode* node)
{
    return checkExportedName(node->pn_atom);
}

template<>
bool
Parser<SyntaxParseHandler, char16_t>::checkExportedNameForClause(Node node)
{
    MOZ_ALWAYS_FALSE(abortIfSyntaxParser());
    return false;
}

template<>
bool
Parser<FullParseHandler, char16_t>::checkExportedNameForFunction(ParseNode* node)
{
    return checkExportedName(node->pn_funbox->function()->explicitName());
}

template<>
bool
Parser<SyntaxParseHandler, char16_t>::checkExportedNameForFunction(Node node)
{
    MOZ_ALWAYS_FALSE(abortIfSyntaxParser());
    return false;
}

template<>
bool
Parser<FullParseHandler, char16_t>::checkExportedNameForClass(ParseNode* node)
{
    const ClassNode& cls = node->as<ClassNode>();
    MOZ_ASSERT(cls.names());
    return checkExportedName(cls.names()->innerBinding()->pn_atom);
}

template<>
bool
Parser<SyntaxParseHandler, char16_t>::checkExportedNameForClass(Node node)
{
    MOZ_ALWAYS_FALSE(abortIfSyntaxParser());
    return false;
}

template<>
bool
Parser<FullParseHandler, char16_t>::processExport(ParseNode* node)
{
    return pc->sc()->asModuleContext()->builder.processExport(node);
}

template<>
bool
Parser<SyntaxParseHandler, char16_t>::processExport(Node node)
{
    MOZ_ALWAYS_FALSE(abortIfSyntaxParser());
    return false;
}

template<>
bool
Parser<FullParseHandler, char16_t>::processExportFrom(ParseNode* node)
{
    return pc->sc()->asModuleContext()->builder.processExportFrom(node);
}

template<>
bool
Parser<SyntaxParseHandler, char16_t>::processExportFrom(Node node)
{
    MOZ_ALWAYS_FALSE(abortIfSyntaxParser());
    return false;
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::exportFrom(uint32_t begin, Node specList)
{
    if (!abortIfSyntaxParser())
        return null();

    MOZ_ASSERT(tokenStream.isCurrentTokenType(TOK_FROM));

    if (!abortIfSyntaxParser())
        return null();

    MUST_MATCH_TOKEN(TOK_STRING, JSMSG_MODULE_SPEC_AFTER_FROM);

    Node moduleSpec = stringLiteral();
    if (!moduleSpec)
        return null();

    if (!matchOrInsertSemicolon())
        return null();

    Node node = handler.newExportFromDeclaration(begin, specList, moduleSpec);
    if (!node)
        return null();

    if (!processExportFrom(node))
        return null();

    return node;
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::exportBatch(uint32_t begin)
{
    if (!abortIfSyntaxParser())
        return null();

    MOZ_ASSERT(tokenStream.isCurrentTokenType(TOK_MUL));

    Node kid = handler.newList(PNK_EXPORT_SPEC_LIST, pos());
    if (!kid)
        return null();

    // Handle the form |export *| by adding a special export batch
    // specifier to the list.
    Node exportSpec = handler.newExportBatchSpec(pos());
    if (!exportSpec)
        return null();

    handler.addList(kid, exportSpec);

    MUST_MATCH_TOKEN(TOK_FROM, JSMSG_FROM_AFTER_EXPORT_STAR);

    return exportFrom(begin, kid);
}

template<>
bool
Parser<FullParseHandler, char16_t>::checkLocalExportNames(ParseNode* node)
{
    // ES 2017 draft 15.2.3.1.
    for (ParseNode* next = node->pn_head; next; next = next->pn_next) {
        ParseNode* name = next->pn_left;
        MOZ_ASSERT(name->isKind(PNK_NAME));

        RootedPropertyName ident(context, name->pn_atom->asPropertyName());
        if (!checkLocalExportName(ident, name->pn_pos.begin))
            return false;
    }

    return true;
}

template<>
bool
Parser<SyntaxParseHandler, char16_t>::checkLocalExportNames(Node node)
{
    MOZ_ALWAYS_FALSE(abortIfSyntaxParser());
    return false;
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::exportClause(uint32_t begin)
{
    if (!abortIfSyntaxParser())
        return null();

    MOZ_ASSERT(tokenStream.isCurrentTokenType(TOK_LC));

    Node kid = handler.newList(PNK_EXPORT_SPEC_LIST, pos());
    if (!kid)
        return null();

    TokenKind tt;
    while (true) {
        // Handle the forms |export {}| and |export { ..., }| (where ... is non
        // empty), by escaping the loop early if the next token is }.
        if (!tokenStream.getToken(&tt))
            return null();

        if (tt == TOK_RC)
            break;

        if (!TokenKindIsPossibleIdentifierName(tt)) {
            error(JSMSG_NO_BINDING_NAME);
            return null();
        }

        Node bindingName = newName(tokenStream.currentName());
        if (!bindingName)
            return null();

        bool foundAs;
        if (!tokenStream.matchToken(&foundAs, TOK_AS))
            return null();
        if (foundAs)
            MUST_MATCH_TOKEN_FUNC(TokenKindIsPossibleIdentifierName, JSMSG_NO_EXPORT_NAME);

        Node exportName = newName(tokenStream.currentName());
        if (!exportName)
            return null();

        if (!checkExportedNameForClause(exportName))
            return null();

        Node exportSpec = handler.newExportSpec(bindingName, exportName);
        if (!exportSpec)
            return null();

        handler.addList(kid, exportSpec);

        TokenKind next;
        if (!tokenStream.getToken(&next))
            return null();

        if (next == TOK_RC)
            break;

        if (next != TOK_COMMA) {
            error(JSMSG_RC_AFTER_EXPORT_SPEC_LIST);
            return null();
        }
    }

    // Careful!  If |from| follows, even on a new line, it must start a
    // FromClause:
    //
    //   export { x }
    //   from "foo"; // a single ExportDeclaration
    //
    // But if it doesn't, we might have an ASI opportunity in Operand context:
    //
    //   export { x }   // ExportDeclaration, terminated by ASI
    //   fro\u006D      // ExpressionStatement, the name "from"
    //
    // In that case let matchOrInsertSemicolon sort out ASI or any necessary
    // error.
    bool matched;
    if (!tokenStream.matchToken(&matched, TOK_FROM, TokenStream::Operand))
        return null();

    if (matched)
        return exportFrom(begin, kid);

    if (!matchOrInsertSemicolon())
        return null();

    if (!checkLocalExportNames(kid))
        return null();

    Node node = handler.newExportDeclaration(kid, TokenPos(begin, pos().end));
    if (!node)
        return null();

    if (!processExport(node))
        return null();

    return node;
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::exportVariableStatement(uint32_t begin)
{
    if (!abortIfSyntaxParser())
        return null();

    MOZ_ASSERT(tokenStream.isCurrentTokenType(TOK_VAR));

    Node kid = declarationList(YieldIsName, PNK_VAR);
    if (!kid)
        return null();
    if (!matchOrInsertSemicolon())
        return null();
    if (!checkExportedNamesForDeclaration(kid))
        return null();

    Node node = handler.newExportDeclaration(kid, TokenPos(begin, pos().end));
    if (!node)
        return null();

    if (!processExport(node))
        return null();

    return node;
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::exportFunctionDeclaration(uint32_t begin, uint32_t toStringStart,
                                                       FunctionAsyncKind asyncKind /* = SyncFunction */)
{
    if (!abortIfSyntaxParser())
        return null();

    MOZ_ASSERT(tokenStream.isCurrentTokenType(TOK_FUNCTION));

    Node kid = functionStmt(toStringStart, YieldIsName, NameRequired, asyncKind);
    if (!kid)
        return null();

    if (!checkExportedNameForFunction(kid))
        return null();

    Node node = handler.newExportDeclaration(kid, TokenPos(begin, pos().end));
    if (!node)
        return null();

    if (!processExport(node))
        return null();

    return node;
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::exportClassDeclaration(uint32_t begin)
{
    if (!abortIfSyntaxParser())
        return null();

    MOZ_ASSERT(tokenStream.isCurrentTokenType(TOK_CLASS));

    Node kid = classDefinition(YieldIsName, ClassStatement, NameRequired);
    if (!kid)
        return null();

    if (!checkExportedNameForClass(kid))
        return null();

    Node node = handler.newExportDeclaration(kid, TokenPos(begin, pos().end));
    if (!node)
        return null();

    if (!processExport(node))
        return null();

    return node;
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::exportLexicalDeclaration(uint32_t begin, DeclarationKind kind)
{
    if (!abortIfSyntaxParser())
        return null();

    MOZ_ASSERT(kind == DeclarationKind::Const || kind == DeclarationKind::Let);
    MOZ_ASSERT_IF(kind == DeclarationKind::Const, tokenStream.isCurrentTokenType(TOK_CONST));
    MOZ_ASSERT_IF(kind == DeclarationKind::Let, tokenStream.isCurrentTokenType(TOK_LET));

    Node kid = lexicalDeclaration(YieldIsName, kind);
    if (!kid)
        return null();
    if (!checkExportedNamesForDeclaration(kid))
        return null();

    Node node = handler.newExportDeclaration(kid, TokenPos(begin, pos().end));
    if (!node)
        return null();

    if (!processExport(node))
        return null();

    return node;
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::exportDefaultFunctionDeclaration(uint32_t begin,
                                                              uint32_t toStringStart,
                                                              FunctionAsyncKind asyncKind /* = SyncFunction */)
{
    if (!abortIfSyntaxParser())
        return null();

    MOZ_ASSERT(tokenStream.isCurrentTokenType(TOK_FUNCTION));

    Node kid = functionStmt(toStringStart, YieldIsName, AllowDefaultName, asyncKind);
    if (!kid)
        return null();

    Node node = handler.newExportDefaultDeclaration(kid, null(), TokenPos(begin, pos().end));
    if (!node)
        return null();

    if (!processExport(node))
        return null();

    return node;
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::exportDefaultClassDeclaration(uint32_t begin)
{
    if (!abortIfSyntaxParser())
        return null();

    MOZ_ASSERT(tokenStream.isCurrentTokenType(TOK_CLASS));

    Node kid = classDefinition(YieldIsName, ClassStatement, AllowDefaultName);
    if (!kid)
        return null();

    Node node = handler.newExportDefaultDeclaration(kid, null(), TokenPos(begin, pos().end));
    if (!node)
        return null();

    if (!processExport(node))
        return null();

    return node;
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::exportDefaultAssignExpr(uint32_t begin)
{
    if (!abortIfSyntaxParser())
        return null();

    RootedPropertyName name(context, context->names().starDefaultStar);
    Node nameNode = newName(name);
    if (!nameNode)
        return null();
    if (!noteDeclaredName(name, DeclarationKind::Const, pos()))
        return null();

    Node kid = assignExpr(InAllowed, YieldIsName, TripledotProhibited);
    if (!kid)
        return null();
    if (!matchOrInsertSemicolon())
        return null();

    Node node = handler.newExportDefaultDeclaration(kid, nameNode, TokenPos(begin, pos().end));
    if (!node)
        return null();

    if (!processExport(node))
        return null();

    return node;
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::exportDefault(uint32_t begin)
{
    if (!abortIfSyntaxParser())
        return null();

    MOZ_ASSERT(tokenStream.isCurrentTokenType(TOK_DEFAULT));

    TokenKind tt;
    if (!tokenStream.getToken(&tt, TokenStream::Operand))
        return null();

    if (!checkExportedName(context->names().default_))
        return null();

    switch (tt) {
      case TOK_FUNCTION:
        return exportDefaultFunctionDeclaration(begin, pos().begin);

      case TOK_ASYNC: {
        TokenKind nextSameLine = TOK_EOF;
        if (!tokenStream.peekTokenSameLine(&nextSameLine))
            return null();

        if (nextSameLine == TOK_FUNCTION) {
            uint32_t toStringStart = pos().begin;
            tokenStream.consumeKnownToken(TOK_FUNCTION);
            return exportDefaultFunctionDeclaration(begin, toStringStart, AsyncFunction);
        }

        tokenStream.ungetToken();
        return exportDefaultAssignExpr(begin);
      }

      case TOK_CLASS:
        return exportDefaultClassDeclaration(begin);

      default:
        tokenStream.ungetToken();
        return exportDefaultAssignExpr(begin);
    }
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::exportDeclaration()
{
    if (!abortIfSyntaxParser())
        return null();

    MOZ_ASSERT(tokenStream.currentToken().type == TOK_EXPORT);

    if (!pc->atModuleLevel()) {
        error(JSMSG_EXPORT_DECL_AT_TOP_LEVEL);
        return null();
    }

    uint32_t begin = pos().begin;

    TokenKind tt;
    if (!tokenStream.getToken(&tt))
        return null();
    switch (tt) {
      case TOK_MUL:
        return exportBatch(begin);

      case TOK_LC:
        return exportClause(begin);

      case TOK_VAR:
        return exportVariableStatement(begin);

      case TOK_FUNCTION:
        return exportFunctionDeclaration(begin, pos().begin);

      case TOK_ASYNC: {
        TokenKind nextSameLine = TOK_EOF;
        if (!tokenStream.peekTokenSameLine(&nextSameLine))
            return null();

        if (nextSameLine == TOK_FUNCTION) {
            uint32_t toStringStart = pos().begin;
            tokenStream.consumeKnownToken(TOK_FUNCTION);
            return exportFunctionDeclaration(begin, toStringStart, AsyncFunction);
        }

        error(JSMSG_DECLARATION_AFTER_EXPORT);
        return null();
      }

      case TOK_CLASS:
        return exportClassDeclaration(begin);

      case TOK_CONST:
        return exportLexicalDeclaration(begin, DeclarationKind::Const);

      case TOK_LET:
        return exportLexicalDeclaration(begin, DeclarationKind::Let);

      case TOK_DEFAULT:
        return exportDefault(begin);

      default:
        error(JSMSG_DECLARATION_AFTER_EXPORT);
        return null();
    }
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::expressionStatement(YieldHandling yieldHandling,
                                                 InvokedPrediction invoked)
{
    tokenStream.ungetToken();
    Node pnexpr = expr(InAllowed, yieldHandling, TripledotProhibited,
                       /* possibleError = */ nullptr, invoked);
    if (!pnexpr)
        return null();
    if (!matchOrInsertSemicolon())
        return null();
    return handler.newExprStatement(pnexpr, pos().end);
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::consequentOrAlternative(YieldHandling yieldHandling)
{
    TokenKind next;
    if (!tokenStream.peekToken(&next, TokenStream::Operand))
        return null();

    // Annex B.3.4 says that unbraced FunctionDeclarations under if/else in
    // non-strict code act as if they were braced: |if (x) function f() {}|
    // parses as |if (x) { function f() {} }|.
    //
    // Careful!  FunctionDeclaration doesn't include generators or async
    // functions.
    if (next == TOK_FUNCTION) {
        tokenStream.consumeKnownToken(next, TokenStream::Operand);

        // Parser::statement would handle this, but as this function handles
        // every other error case, it seems best to handle this.
        if (pc->sc()->strict()) {
            error(JSMSG_FORBIDDEN_AS_STATEMENT, "function declarations");
            return null();
        }

        TokenKind maybeStar;
        if (!tokenStream.peekToken(&maybeStar))
            return null();

        if (maybeStar == TOK_MUL) {
            error(JSMSG_FORBIDDEN_AS_STATEMENT, "generator declarations");
            return null();
        }

        ParseContext::Statement stmt(pc, StatementKind::Block);
        ParseContext::Scope scope(this);
        if (!scope.init(pc))
            return null();

        TokenPos funcPos = pos();
        Node fun = functionStmt(pos().begin, yieldHandling, NameRequired);
        if (!fun)
            return null();

        Node block = handler.newStatementList(funcPos);
        if (!block)
            return null();

        handler.addStatementToList(block, fun);
        return finishLexicalScope(scope, block);
    }

    return statement(yieldHandling);
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::ifStatement(YieldHandling yieldHandling)
{
    Vector<Node, 4> condList(context), thenList(context);
    Vector<uint32_t, 4> posList(context);
    Node elseBranch;

    ParseContext::Statement stmt(pc, StatementKind::If);

    while (true) {
        uint32_t begin = pos().begin;

        /* An IF node has three kids: condition, then, and optional else. */
        Node cond = condition(InAllowed, yieldHandling);
        if (!cond)
            return null();

        TokenKind tt;
        if (!tokenStream.peekToken(&tt, TokenStream::Operand))
            return null();
        if (tt == TOK_SEMI) {
            if (!extraWarning(JSMSG_EMPTY_CONSEQUENT))
                return null();
        }

        Node thenBranch = consequentOrAlternative(yieldHandling);
        if (!thenBranch)
            return null();

        if (!condList.append(cond) || !thenList.append(thenBranch) || !posList.append(begin))
            return null();

        bool matched;
        if (!tokenStream.matchToken(&matched, TOK_ELSE, TokenStream::Operand))
            return null();
        if (matched) {
            if (!tokenStream.matchToken(&matched, TOK_IF, TokenStream::Operand))
                return null();
            if (matched)
                continue;
            elseBranch = consequentOrAlternative(yieldHandling);
            if (!elseBranch)
                return null();
        } else {
            elseBranch = null();
        }
        break;
    }

    for (int i = condList.length() - 1; i >= 0; i--) {
        elseBranch = handler.newIfStatement(posList[i], condList[i], thenList[i], elseBranch);
        if (!elseBranch)
            return null();
    }

    return elseBranch;
}

template <class ParseHandler, typename CharT>
typename ParseHandler::Node
Parser<ParseHandler, CharT>::doWhileStatement(YieldHandling yieldHandling)
{
    uint32_t begin = pos().begin;
    ParseContext::Statement stmt(pc, StatementKind::DoLoop);
    Node body = statement(yieldHandling);
    if (!body)
        return null();
    MUST_MATCH_TOKEN_MOD(TOK_WHILE, TokenStream::Operand, JSMSG_WHILE_AFTER_DO);
    Node cond = condition(InAllowed, yieldHandling);
    if (!cond)
        return null();

    // The semicolon after do-while is even more optional than most
    // semicolons in JS.  Web compat required this by 2004:
    //   http://bugzilla.mozilla.org/show_bug.cgi?id=238945
    // ES3 and ES5 disagreed, but ES6 conforms to Web reality:
    //   https://bugs.ecmascript.org/show_bug.cgi?id=157
    // To parse |do {} while (true) false| correctly, use Operand.
    bool ignored;
    if (!tokenStream.