DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (b6d82b1a6b02)

VCS Links

Line Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 * vim: set ts=8 sts=2 et sw=2 tw=80:
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "frontend/FunctionEmitter.h"

#include "mozilla/Assertions.h"  // MOZ_ASSERT

#include "builtin/ModuleObject.h"          // ModuleObject
#include "frontend/BytecodeEmitter.h"      // BytecodeEmitter
#include "frontend/ModuleSharedContext.h"  // ModuleSharedContext
#include "frontend/NameAnalysisTypes.h"    // NameLocation
#include "frontend/NameOpEmitter.h"        // NameOpEmitter
#include "frontend/ParseContext.h"         // BindingIter
#include "frontend/PropOpEmitter.h"        // PropOpEmitter
#include "frontend/SharedContext.h"        // SharedContext
#include "vm/AsyncFunction.h"              // AsyncFunctionResolveKind
#include "vm/JSScript.h"                   // JSScript
#include "vm/Opcodes.h"                    // JSOP_*
#include "vm/Scope.h"                      // BindingKind
#include "wasm/AsmJS.h"                    // IsAsmJSModule

using namespace js;
using namespace js::frontend;

using mozilla::Maybe;
using mozilla::Some;

FunctionEmitter::FunctionEmitter(BytecodeEmitter* bce, FunctionBox* funbox,
                                 FunctionSyntaxKind syntaxKind,
                                 IsHoisted isHoisted)
    : bce_(bce),
      funbox_(funbox),
      fun_(bce_->cx, funbox_->function()),
      name_(bce_->cx, fun_->explicitName()),
      syntaxKind_(syntaxKind),
      isHoisted_(isHoisted) {
  MOZ_ASSERT_IF(fun_->isInterpretedLazy(), fun_->lazyScript());
}

bool FunctionEmitter::interpretedCommon() {
  // Mark as singletons any function which will only be executed once, or
  // which is inner to a lambda we only expect to run once. In the latter
  // case, if the lambda runs multiple times then CloneFunctionObject will
  // make a deep clone of its contents.
  bool singleton = bce_->checkRunOnceContext();
  if (!JSFunction::setTypeForScriptedFunction(bce_->cx, fun_, singleton)) {
    return false;
  }

  SharedContext* outersc = bce_->sc;
  if (outersc->isFunctionBox()) {
    outersc->asFunctionBox()->setHasInnerFunctions();
  }

  return true;
}

bool FunctionEmitter::prepareForNonLazy() {
  MOZ_ASSERT(state_ == State::Start);

  MOZ_ASSERT(fun_->isInterpreted());
  MOZ_ASSERT(!fun_->isInterpretedLazy());
  MOZ_ASSERT(!funbox_->wasEmitted);

  //                [stack]

  funbox_->wasEmitted = true;

  if (!interpretedCommon()) {
    return false;
  }

  MOZ_ASSERT_IF(bce_->sc->strict(), funbox_->strictScript);

#ifdef DEBUG
  state_ = State::NonLazy;
#endif
  return true;
}

bool FunctionEmitter::emitNonLazyEnd() {
  MOZ_ASSERT(state_ == State::NonLazy);

  //                [stack]

  if (!emitFunction()) {
    //              [stack] FUN?
    return false;
  }

#ifdef DEBUG
  state_ = State::End;
#endif
  return true;
}

bool FunctionEmitter::emitLazy() {
  MOZ_ASSERT(state_ == State::Start);

  MOZ_ASSERT(fun_->isInterpreted());
  MOZ_ASSERT(fun_->isInterpretedLazy());
  MOZ_ASSERT(!funbox_->wasEmitted);

  //                [stack]

  funbox_->wasEmitted = true;

  if (!interpretedCommon()) {
    return false;
  }

  funbox_->setEnclosingScopeForInnerLazyFunction(bce_->innermostScope());
  if (bce_->emittingRunOnceLambda) {
    // NOTE: The 'funbox' is only partially initialized so we defer checking
    // the shouldSuppressRunOnce condition until delazification.
    fun_->lazyScript()->setTreatAsRunOnce();
  }

  if (!emitFunction()) {
    //              [stack] FUN?
    return false;
  }

#ifdef DEBUG
  state_ = State::End;
#endif
  return true;
}

bool FunctionEmitter::emitAgain() {
  MOZ_ASSERT(state_ == State::Start);
  MOZ_ASSERT(funbox_->wasEmitted);
  MOZ_ASSERT_IF(fun_->hasScript(), fun_->nonLazyScript());

  //                [stack]

  // Annex B block-scoped functions are hoisted like any other assignment
  // that assigns the function to the outer 'var' binding.
  if (!funbox_->isAnnexB) {
#ifdef DEBUG
    state_ = State::End;
#endif
    return true;
  }

  // Get the location of the 'var' binding in the body scope. The
  // name must be found, else there is a bug in the Annex B handling
  // in Parser.
  //
  // In sloppy eval contexts, this location is dynamic.
  Maybe<NameLocation> lhsLoc =
      bce_->locationOfNameBoundInScope(name_, bce_->varEmitterScope);

  // If there are parameter expressions, the var name could be a
  // parameter.
  if (!lhsLoc && bce_->sc->isFunctionBox() &&
      bce_->sc->asFunctionBox()->hasExtraBodyVarScope()) {
    lhsLoc = bce_->locationOfNameBoundInScope(
        name_, bce_->varEmitterScope->enclosingInFrame());
  }

  if (!lhsLoc) {
    lhsLoc = Some(NameLocation::DynamicAnnexBVar());
  } else {
    MOZ_ASSERT(lhsLoc->bindingKind() == BindingKind::Var ||
               lhsLoc->bindingKind() == BindingKind::FormalParameter ||
               (lhsLoc->bindingKind() == BindingKind::Let &&
                bce_->sc->asFunctionBox()->hasParameterExprs));
  }

  NameOpEmitter noe(bce_, name_, *lhsLoc,
                    NameOpEmitter::Kind::SimpleAssignment);
  if (!noe.prepareForRhs()) {
    //              [stack]
    return false;
  }

  if (!bce_->emitGetName(name_)) {
    //              [stack] FUN
    return false;
  }

  if (!noe.emitAssignment()) {
    //              [stack] FUN
    return false;
  }

  if (!bce_->emit1(JSOP_POP)) {
    //              [stack]
    return false;
  }

#ifdef DEBUG
  state_ = State::End;
#endif
  return true;
}

bool FunctionEmitter::emitAsmJSModule() {
  MOZ_ASSERT(state_ == State::Start);

  MOZ_ASSERT(!funbox_->wasEmitted);
  MOZ_ASSERT(IsAsmJSModule(fun_));

  //                [stack]

  funbox_->wasEmitted = true;

  if (!emitFunction()) {
    //              [stack]
    return false;
  }

#ifdef DEBUG
  state_ = State::End;
#endif
  return true;
}

bool FunctionEmitter::emitFunction() {
  // Make the function object a literal in the outer script's pool.
  uint32_t index;
  if (!bce_->perScriptData().gcThingList().append(funbox_, &index)) {
    return false;
  }

  //                [stack]

  if (isHoisted_ == IsHoisted::No) {
    return emitNonHoisted(index);
    //              [stack] FUN?
  }

  bool topLevelFunction;
  if (bce_->sc->isFunctionBox() ||
      (bce_->sc->isEvalContext() && bce_->sc->strict())) {
    // No nested functions inside other functions are top-level.
    topLevelFunction = false;
  } else {
    // In sloppy eval scripts, top-level functions are accessed dynamically.
    // In global and module scripts, top-level functions are those bound in
    // the var scope.
    NameLocation loc = bce_->lookupName(name_);
    topLevelFunction = loc.kind() == NameLocation::Kind::Dynamic ||
                       loc.bindingKind() == BindingKind::Var;
  }

  if (topLevelFunction) {
    return emitTopLevelFunction(index);
    //              [stack]
  }

  return emitHoisted(index);
  //                [stack]
}

bool FunctionEmitter::emitNonHoisted(unsigned index) {
  // Non-hoisted functions simply emit their respective op.

  //                [stack]

  // JSOP_LAMBDA_ARROW is always preceded by a opcode that pushes new.target.
  // See below.
  MOZ_ASSERT(fun_->isArrow() == (syntaxKind_ == FunctionSyntaxKind::Arrow));

  if (fun_->isArrow()) {
    if (!emitNewTargetForArrow()) {
      //            [stack] NEW.TARGET/NULL
      return false;
    }
  }

  if (syntaxKind_ == FunctionSyntaxKind::DerivedClassConstructor) {
    //              [stack] PROTO
    if (!bce_->emitIndex32(JSOP_FUNWITHPROTO, index)) {
      //            [stack] FUN
      return false;
    }
    return true;
  }

  // This is a FunctionExpression, ArrowFunctionExpression, or class
  // constructor. Emit the single instruction (without location info).
  JSOp op = syntaxKind_ == FunctionSyntaxKind::Arrow ? JSOP_LAMBDA_ARROW
                                                     : JSOP_LAMBDA;
  if (!bce_->emitIndex32(op, index)) {
    //              [stack] FUN
    return false;
  }

  return true;
}

bool FunctionEmitter::emitHoisted(unsigned index) {
  MOZ_ASSERT(syntaxKind_ == FunctionSyntaxKind::Statement);

  //                [stack]

  // For functions nested within functions and blocks, make a lambda and
  // initialize the binding name of the function in the current scope.

  NameOpEmitter noe(bce_, name_, NameOpEmitter::Kind::Initialize);
  if (!noe.prepareForRhs()) {
    //              [stack]
    return false;
  }

  if (!bce_->emitIndexOp(JSOP_LAMBDA, index)) {
    //              [stack] FUN
    return false;
  }

  if (!noe.emitAssignment()) {
    //              [stack] FUN
    return false;
  }

  if (!bce_->emit1(JSOP_POP)) {
    //              [stack]
    return false;
  }

  return true;
}

bool FunctionEmitter::emitTopLevelFunction(unsigned index) {
  //                [stack]

  if (bce_->sc->isModuleContext()) {
    // For modules, we record the function and instantiate the binding
    // during ModuleInstantiate(), before the script is run.

    JS::Rooted<ModuleObject*> module(bce_->cx,
                                     bce_->sc->asModuleContext()->module());
    if (!module->noteFunctionDeclaration(bce_->cx, name_, fun_)) {
      return false;
    }
    return true;
  }

  MOZ_ASSERT(bce_->sc->isGlobalContext() || bce_->sc->isEvalContext());
  MOZ_ASSERT(syntaxKind_ == FunctionSyntaxKind::Statement);
  MOZ_ASSERT(bce_->inPrologue());

  if (!bce_->emitIndex32(JSOP_LAMBDA, index)) {
    //              [stack] FUN
    return false;
  }
  if (!bce_->emit1(JSOP_DEFFUN)) {
    //              [stack]
    return false;
  }
  return true;
}

bool FunctionEmitter::emitNewTargetForArrow() {
  //                [stack]

  if (bce_->sc->allowNewTarget()) {
    if (!bce_->emit1(JSOP_NEWTARGET)) {
      //            [stack] NEW.TARGET
      return false;
    }
  } else {
    if (!bce_->emit1(JSOP_NULL)) {
      //            [stack] NULL
      return false;
    }
  }

  return true;
}

bool FunctionScriptEmitter::prepareForParameters() {
  MOZ_ASSERT(state_ == State::Start);
  MOZ_ASSERT(bce_->inPrologue());

  //                [stack]

  if (paramStart_) {
    bce_->setScriptStartOffsetIfUnset(*paramStart_);
  }

  // The ordering of these EmitterScopes is important. The named lambda
  // scope needs to enclose the function scope needs to enclose the extra
  // var scope.

  if (funbox_->namedLambdaBindings()) {
    namedLambdaEmitterScope_.emplace(bce_);
    if (!namedLambdaEmitterScope_->enterNamedLambda(bce_, funbox_)) {
      return false;
    }
  }

  /*
   * Mark the script so that initializers created within it may be given more
   * precise types.
   */
  if (bce_->isRunOnceLambda()) {
    bce_->script->setTreatAsRunOnce();
    MOZ_ASSERT(!bce_->script->hasRunOnce());
  }

  if (bodyEnd_) {
    bce_->setFunctionBodyEndPos(*bodyEnd_);
  }

  if (paramStart_) {
    if (!bce_->updateLineNumberNotes(*paramStart_)) {
      return false;
    }
  }

  tdzCache_.emplace(bce_);
  functionEmitterScope_.emplace(bce_);

  if (funbox_->hasParameterExprs) {
    // There's parameter exprs, emit them in the main section.
    //
    // One caveat is that Debugger considers ops in the prologue to be
    // unreachable (i.e. cannot set a breakpoint on it). If there are no
    // parameter exprs, any unobservable environment ops (like pushing the
    // call object, setting '.this', etc) need to go in the prologue, else it
    // messes up breakpoint tests.
    if (!bce_->switchToMain()) {
      return false;
    }
  }

  if (!functionEmitterScope_->enterFunction(bce_, funbox_)) {
    return false;
  }

  if (!bce_->emitInitializeFunctionSpecialNames()) {
    //              [stack]
    return false;
  }

  if (!funbox_->hasParameterExprs) {
    if (!bce_->switchToMain()) {
      return false;
    }
  }

  // Parameters can't reuse the reject try-catch block from the function body,
  // because the body may have pushed an additional var-environment. This
  // messes up scope resolution for the |.generator| variable, because we'd
  // need different hops to reach |.generator| depending on whether the error
  // was thrown from the parameters or the function body.
  if (funbox_->hasParameterExprs && funbox_->needsPromiseResult()) {
    if (!emitAsyncFunctionRejectPrologue()) {
      return false;
    }
  }

#ifdef DEBUG
  state_ = State::Parameters;
#endif
  return true;
}

bool FunctionScriptEmitter::prepareForBody() {
  MOZ_ASSERT(state_ == State::Parameters);

  //                [stack]

  if (rejectTryCatch_) {
    if (!emitAsyncFunctionRejectEpilogue()) {
      return false;
    }
  }

  if (!emitExtraBodyVarScope()) {
    //              [stack]
    return false;
  }

  if (funbox_->needsPromiseResult()) {
    if (!emitAsyncFunctionRejectPrologue()) {
      return false;
    }
  }

  if (funbox_->kind() == FunctionFlags::FunctionKind::ClassConstructor) {
    if (!funbox_->isDerivedClassConstructor()) {
      if (!bce_->emitInitializeInstanceFields()) {
        //          [stack]
        return false;
      }
    }
  }

#ifdef DEBUG
  state_ = State::Body;
#endif
  return true;
}

bool FunctionScriptEmitter::emitAsyncFunctionRejectPrologue() {
  rejectTryCatch_.emplace(bce_, TryEmitter::Kind::TryCatch,
                          TryEmitter::ControlKind::NonSyntactic);
  return rejectTryCatch_->emitTry();
}

bool FunctionScriptEmitter::emitAsyncFunctionRejectEpilogue() {
  if (!rejectTryCatch_->emitCatch()) {
    //              [stack] EXC
    return false;
  }

  if (!bce_->emitGetDotGeneratorInInnermostScope()) {
    //              [stack] EXC GEN
    return false;
  }
  if (!bce_->emit2(JSOP_ASYNCRESOLVE,
                   uint8_t(AsyncFunctionResolveKind::Reject))) {
    //              [stack] PROMISE
    return false;
  }
  if (!bce_->emit1(JSOP_SETRVAL)) {
    //              [stack]
    return false;
  }
  if (!bce_->emitGetDotGeneratorInInnermostScope()) {
    //              [stack] GEN
    return false;
  }
  if (!bce_->emitYieldOp(JSOP_FINALYIELDRVAL)) {
    //              [stack]
    return false;
  }

  if (!rejectTryCatch_->emitEnd()) {
    return false;
  }
  rejectTryCatch_.reset();
  return true;
}

bool FunctionScriptEmitter::emitExtraBodyVarScope() {
  //                [stack]

  if (!funbox_->hasExtraBodyVarScope()) {
    return true;
  }

  extraBodyVarEmitterScope_.emplace(bce_);
  if (!extraBodyVarEmitterScope_->enterFunctionExtraBodyVar(bce_, funbox_)) {
    return false;
  }

  if (!funbox_->extraVarScopeBindings() || !funbox_->functionScopeBindings()) {
    return true;
  }

  // After emitting expressions for all parameters, copy over any formal
  // parameters which have been redeclared as vars. For example, in the
  // following, the var y in the body scope is 42:
  //
  //   function f(x, y = 42) { var y; }
  //
  JS::Rooted<JSAtom*> name(bce_->cx);
  for (BindingIter bi(*funbox_->functionScopeBindings(), true); bi; bi++) {
    name = bi.name();

    // There may not be a var binding of the same name.
    if (!bce_->locationOfNameBoundInScope(name,
                                          extraBodyVarEmitterScope_.ptr())) {
      continue;
    }

    // The '.this' and '.generator' function special
    // bindings should never appear in the extra var
    // scope. 'arguments', however, may.
    MOZ_ASSERT(name != bce_->cx->names().dotThis &&
               name != bce_->cx->names().dotGenerator);

    NameOpEmitter noe(bce_, name, NameOpEmitter::Kind::Initialize);
    if (!noe.prepareForRhs()) {
      //            [stack]
      return false;
    }

    NameLocation paramLoc =
        *bce_->locationOfNameBoundInScope(name, functionEmitterScope_.ptr());
    if (!bce_->emitGetNameAtLocation(name, paramLoc)) {
      //            [stack] VAL
      return false;
    }

    if (!noe.emitAssignment()) {
      //            [stack] VAL
      return false;
    }

    if (!bce_->emit1(JSOP_POP)) {
      //            [stack]
      return false;
    }
  }

  return true;
}

bool FunctionScriptEmitter::emitEndBody() {
  MOZ_ASSERT(state_ == State::Body);

  //                [stack]

  if (funbox_->needsFinalYield()) {
    // If we fall off the end of a generator, do a final yield.
    bool needsIteratorResult = funbox_->needsIteratorResult();
    if (needsIteratorResult) {
      if (!bce_->emitPrepareIteratorResult()) {
        //          [stack] RESULT
        return false;
      }
    }

    if (!bce_->emit1(JSOP_UNDEFINED)) {
      //            [stack] RESULT? UNDEF
      return false;
    }

    if (needsIteratorResult) {
      if (!bce_->emitFinishIteratorResult(true)) {
        //          [stack] RESULT
        return false;
      }
    }

    if (funbox_->needsPromiseResult()) {
      if (!bce_->emitGetDotGeneratorInInnermostScope()) {
        //          [stack] RVAL GEN
        return false;
      }

      if (!bce_->emit2(JSOP_ASYNCRESOLVE,
                       uint8_t(AsyncFunctionResolveKind::Fulfill))) {
        //          [stack] PROMISE
        return false;
      }
    }

    if (!bce_->emit1(JSOP_SETRVAL)) {
      //            [stack]
      return false;
    }

    if (!bce_->emitGetDotGeneratorInInnermostScope()) {
      //            [stack] GEN
      return false;
    }

    // No need to check for finally blocks, etc as in EmitReturn.
    if (!bce_->emitYieldOp(JSOP_FINALYIELDRVAL)) {
      //            [stack]
      return false;
    }
  } else {
    // Non-generator functions just return |undefined|. The
    // JSOP_RETRVAL emitted below will do that, except if the
    // script has a finally block: there can be a non-undefined
    // value in the return value slot. Make sure the return value
    // is |undefined|.
    if (bce_->hasTryFinally) {
      if (!bce_->emit1(JSOP_UNDEFINED)) {
        //          [stack] UNDEF
        return false;
      }
      if (!bce_->emit1(JSOP_SETRVAL)) {
        //          [stack]
        return false;
      }
    }
  }

  if (funbox_->isDerivedClassConstructor()) {
    if (!bce_->emitCheckDerivedClassConstructorReturn()) {
      //            [stack]
      return false;
    }
  }

  if (rejectTryCatch_) {
    if (!emitAsyncFunctionRejectEpilogue()) {
      return false;
    }
  }

  if (extraBodyVarEmitterScope_) {
    if (!extraBodyVarEmitterScope_->leave(bce_)) {
      return false;
    }

    extraBodyVarEmitterScope_.reset();
  }

  if (!functionEmitterScope_->leave(bce_)) {
    return false;
  }
  functionEmitterScope_.reset();
  tdzCache_.reset();

  if (bodyEnd_) {
    if (!bce_->updateSourceCoordNotes(*bodyEnd_)) {
      return false;
    }
  }

  // We only want to mark the end of a function as a breakable position if
  // there is token there that the user can easily associate with the function
  // as a whole. Since arrow function single-expression bodies have no closing
  // curly bracket, we do not place a breakpoint at their end position.
  if (!funbox_->hasExprBody()) {
    if (!bce_->markSimpleBreakpoint()) {
      return false;
    }
  }

  // Always end the script with a JSOP_RETRVAL. Some other parts of the
  // codebase depend on this opcode,
  // e.g. InterpreterRegs::setToEndOfScript.
  if (!bce_->emitReturnRval()) {
    //              [stack]
    return false;
  }

  if (namedLambdaEmitterScope_) {
    if (!namedLambdaEmitterScope_->leave(bce_)) {
      return false;
    }
    namedLambdaEmitterScope_.reset();
  }

#ifdef DEBUG
  state_ = State::EndBody;
#endif
  return true;
}

bool FunctionScriptEmitter::initScript() {
  MOZ_ASSERT(state_ == State::EndBody);

  if (!JSScript::fullyInitFromEmitter(bce_->cx, bce_->script, bce_)) {
    return false;
  }

  bce_->tellDebuggerAboutCompiledScript(bce_->cx);

#ifdef DEBUG
  state_ = State::End;
#endif
  return true;
}

FunctionParamsEmitter::FunctionParamsEmitter(BytecodeEmitter* bce,
                                             FunctionBox* funbox)
    : bce_(bce),
      funbox_(funbox),
      functionEmitterScope_(bce_->innermostEmitterScope()) {}

bool FunctionParamsEmitter::emitSimple(JS::Handle<JSAtom*> paramName) {
  MOZ_ASSERT(state_ == State::Start);

  //                [stack]

  if (funbox_->hasParameterExprs) {
    if (!bce_->emitArgOp(JSOP_GETARG, argSlot_)) {
      //            [stack] ARG
      return false;
    }

    if (!emitAssignment(paramName)) {
      //            [stack]
      return false;
    }
  }

  argSlot_++;
  return true;
}

bool FunctionParamsEmitter::prepareForDefault() {
  MOZ_ASSERT(state_ == State::Start);

  //                [stack]

  if (!enterParameterExpressionVarScope()) {
    return false;
  }

  if (!prepareForInitializer()) {
    //              [stack]
    return false;
  }

#ifdef DEBUG
  state_ = State::Default;
#endif
  return true;
}

bool FunctionParamsEmitter::emitDefaultEnd(JS::Handle<JSAtom*> paramName) {
  MOZ_ASSERT(state_ == State::Default);

  //                [stack] DEFAULT

  if (!emitInitializerEnd()) {
    //              [stack] ARG/DEFAULT
    return false;
  }
  if (!emitAssignment(paramName)) {
    //              [stack]
    return false;
  }
  if (!leaveParameterExpressionVarScope()) {
    return false;
  }

  argSlot_++;

#ifdef DEBUG
  state_ = State::Start;
#endif
  return true;
}

bool FunctionParamsEmitter::prepareForDestructuring() {
  MOZ_ASSERT(state_ == State::Start);

  //                [stack]

  if (!enterParameterExpressionVarScope()) {
    return false;
  }

  if (!bce_->emitArgOp(JSOP_GETARG, argSlot_)) {
    //              [stack] ARG
    return false;
  }

#ifdef DEBUG
  state_ = State::Destructuring;
#endif
  return true;
}

bool FunctionParamsEmitter::emitDestructuringEnd() {
  MOZ_ASSERT(state_ == State::Destructuring);

  //                [stack] ARG

  if (!bce_->emit1(JSOP_POP)) {
    //              [stack]
    return false;
  }

  if (!leaveParameterExpressionVarScope()) {
    return false;
  }

  argSlot_++;

#ifdef DEBUG
  state_ = State::Start;
#endif
  return true;
}

bool FunctionParamsEmitter::prepareForDestructuringDefaultInitializer() {
  MOZ_ASSERT(state_ == State::Start);

  //                [stack]

  if (!enterParameterExpressionVarScope()) {
    return false;
  }
  if (!prepareForInitializer()) {
    //              [stack]
    return false;
  }

#ifdef DEBUG
  state_ = State::DestructuringDefaultInitializer;
#endif
  return true;
}

bool FunctionParamsEmitter::prepareForDestructuringDefault() {
  MOZ_ASSERT(state_ == State::DestructuringDefaultInitializer);

  //                [stack] DEFAULT

  if (!emitInitializerEnd()) {
    //              [stack] ARG/DEFAULT
    return false;
  }

#ifdef DEBUG
  state_ = State::DestructuringDefault;
#endif
  return true;
}

bool FunctionParamsEmitter::emitDestructuringDefaultEnd() {
  MOZ_ASSERT(state_ == State::DestructuringDefault);

  //                [stack] ARG/DEFAULT

  if (!bce_->emit1(JSOP_POP)) {
    //              [stack]
    return false;
  }

  if (!leaveParameterExpressionVarScope()) {
    return false;
  }

  argSlot_++;

#ifdef DEBUG
  state_ = State::Start;
#endif
  return true;
}

bool FunctionParamsEmitter::emitRest(JS::Handle<JSAtom*> paramName) {
  MOZ_ASSERT(state_ == State::Start);

  //                [stack]

  if (!emitRestArray()) {
    //              [stack] REST
    return false;
  }
  if (!emitAssignment(paramName)) {
    //              [stack]
    return false;
  }

#ifdef DEBUG
  state_ = State::End;
#endif
  return true;
}

bool FunctionParamsEmitter::prepareForDestructuringRest() {
  MOZ_ASSERT(state_ == State::Start);

  //                [stack]

  if (!enterParameterExpressionVarScope()) {
    return false;
  }
  if (!emitRestArray()) {
    //              [stack] REST
    return false;
  }

#ifdef DEBUG
  state_ = State::DestructuringRest;
#endif
  return true;
}

bool FunctionParamsEmitter::emitDestructuringRestEnd() {
  MOZ_ASSERT(state_ == State::DestructuringRest);

  //                [stack] REST

  if (!bce_->emit1(JSOP_POP)) {
    //              [stack]
    return false;
  }

  if (!leaveParameterExpressionVarScope()) {
    return false;
  }

#ifdef DEBUG
  state_ = State::End;
#endif
  return true;
}

bool FunctionParamsEmitter::enterParameterExpressionVarScope() {
  if (!funbox_->hasDirectEvalInParameterExpr) {
    return true;
  }

  // ES 14.1.19 says if BindingElement contains an expression in the
  // production FormalParameter : BindingElement, it is evaluated in a
  // new var environment. This is needed to prevent vars from escaping
  // direct eval in parameter expressions.
  paramExprVarEmitterScope_.emplace(bce_);
  if (!paramExprVarEmitterScope_->enterParameterExpressionVar(bce_)) {
    return false;
  }
  return true;
}

bool FunctionParamsEmitter::leaveParameterExpressionVarScope() {
  if (!paramExprVarEmitterScope_) {
    return true;
  }

  if (!paramExprVarEmitterScope_->leave(bce_)) {
    return false;
  }
  paramExprVarEmitterScope_.reset();

  return true;
}

bool FunctionParamsEmitter::prepareForInitializer() {
  //                [stack]

  // If we have an initializer, emit the initializer and assign it
  // to the argument slot. TDZ is taken care of afterwards.
  MOZ_ASSERT(funbox_->hasParameterExprs);
  if (!bce_->emitArgOp(JSOP_GETARG, argSlot_)) {
    //              [stack] ARG
    return false;
  }
  default_.emplace(bce_);
  if (!default_->prepareForDefault()) {
    //              [stack]
    return false;
  }
  return true;
}

bool FunctionParamsEmitter::emitInitializerEnd() {
  //                [stack] DEFAULT

  if (!default_->emitEnd()) {
    //              [stack] ARG/DEFAULT
    return false;
  }
  default_.reset();
  return true;
}

bool FunctionParamsEmitter::emitRestArray() {
  //                [stack]

  if (!bce_->emit1(JSOP_REST)) {
    //              [stack] REST
    return false;
  }
  return true;
}

bool FunctionParamsEmitter::emitAssignment(JS::Handle<JSAtom*> paramName) {
  //                [stack] ARG

  NameLocation paramLoc =
      *bce_->locationOfNameBoundInScope(paramName, functionEmitterScope_);

  // RHS is already pushed in the caller side.
  // Make sure prepareForRhs doesn't touch stack.
  MOZ_ASSERT(paramLoc.kind() == NameLocation::Kind::ArgumentSlot ||
             paramLoc.kind() == NameLocation::Kind::FrameSlot ||
             paramLoc.kind() == NameLocation::Kind::EnvironmentCoordinate);

  NameOpEmitter noe(bce_, paramName, paramLoc, NameOpEmitter::Kind::Initialize);
  if (!noe.prepareForRhs()) {
    //              [stack] ARG
    return false;
  }

  if (!noe.emitAssignment()) {
    //              [stack] ARG
    return false;
  }

  if (!bce_->emit1(JSOP_POP)) {
    //              [stack]
    return false;
  }

  return true;
}

DestructuringFlavor FunctionParamsEmitter::getDestructuringFlavor() {
  MOZ_ASSERT(state_ == State::Destructuring ||
             state_ == State::DestructuringDefault ||
             state_ == State::DestructuringRest);

  return funbox_->hasDirectEvalInParameterExpr
             ? DestructuringFlavor::FormalParameterInVarScope
             : DestructuringFlavor::Declaration;
}