DXR will be turned off on Tuesday, December 29th. It will redirect to Searchfox.
See the announcement on Discourse.

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.

Mercurial (c68fe15a81fc)

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 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
/* -*- 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
/* 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/. */

/**
 * This file is near-OBSOLETE. It is used for about:blank only and for the
 * This file is near-OBSOLETE. It is used for about:blank only and for the
 * HTML element factory.
 * Don't bother adding new stuff in this file.
 */

#include "mozilla/ArrayUtils.h"
#include "mozilla/ArrayUtils.h"

#include "nsContentSink.h"
#include "nsCOMPtr.h"
#include "nsHTMLTags.h"
#include "nsReadableUtils.h"
#include "nsReadableUtils.h"
#include "nsUnicharUtils.h"
#include "nsIHTMLContentSink.h"
#include "nsIInterfaceRequestor.h"
#include "nsIInterfaceRequestorUtils.h"
#include "nsIInterfaceRequestorUtils.h"
#include "nsIURI.h"
#include "mozilla/dom/NodeInfo.h"
#include "mozilla/dom/ScriptLoader.h"
#include "nsCRT.h"
#include "prtime.h"
#include "prtime.h"
#include "mozilla/Logging.h"
#include "nsIContent.h"
#include "mozilla/dom/CustomElementRegistry.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/MutationObservers.h"
#include "mozilla/dom/MutationObservers.h"
#include "mozilla/Preferences.h"

#include "nsGenericHTMLElement.h"

#include "nsIScriptElement.h"
#include "nsIScriptElement.h"

#include "nsDocElementCreatedNotificationRunner.h"
#include "nsGkAtoms.h"
#include "nsContentUtils.h"
#include "nsContentUtils.h"
#include "nsIChannel.h"
#include "mozilla/dom/Document.h"
#include "nsStubDocumentObserver.h"
#include "nsHTMLDocument.h"
#include "nsTArray.h"
#include "nsTextFragment.h"
#include "nsIScriptGlobalObject.h"
#include "nsIScriptGlobalObject.h"
#include "nsNameSpaceManager.h"

#include "nsError.h"
#include "nsContentPolicyUtils.h"
#include "nsIScriptContext.h"

#include "nsLayoutCID.h"

#include "nsLayoutCID.h"
#include "nsEscape.h"
#include "nsNodeInfoManager.h"
#include "nsContentCreatorFunctions.h"
#include "mozAutoDocUpdate.h"
#include "nsTextNode.h"
#include "mozAutoDocUpdate.h"

using namespace mozilla;
using namespace mozilla::dom;

//----------------------------------------------------------------------


nsGenericHTMLElement* NS_NewHTMLNOTUSEDElement(
    already_AddRefed<mozilla::dom::NodeInfo>&& aNodeInfo,
nsGenericHTMLElement* NS_NewHTMLNOTUSEDElement(
    FromParser aFromParser) {
  MOZ_ASSERT_UNREACHABLE("The element ctor should never be called");
  return nullptr;
}

#define HTML_TAG(_tag, _classname, _interfacename) \
  NS_NewHTML##_classname##Element,
#define HTML_OTHER(_tag) NS_NewHTMLNOTUSEDElement,
#define HTML_TAG(_tag, _classname, _interfacename) \
static const HTMLContentCreatorFunction sHTMLContentCreatorFunctions[] = {
    NS_NewHTMLUnknownElement,
#include "nsHTMLTagList.h"
#undef HTML_TAG
#include "nsHTMLTagList.h"
#undef HTML_OTHER
    NS_NewHTMLUnknownElement};

class SinkContext;
class HTMLContentSink;
class SinkContext;

/**
 * This class is near-OBSOLETE. It is used for about:blank only.
 * Don't bother adding new stuff in this file.
 */
 * Don't bother adding new stuff in this file.
class HTMLContentSink : public nsContentSink, public nsIHTMLContentSink {
 public:
  friend class SinkContext;

  HTMLContentSink();


  nsresult Init(Document* aDoc, nsIURI* aURI, nsISupports* aContainer,
                nsIChannel* aChannel);

  // nsISupports
  NS_DECL_ISUPPORTS_INHERITED
  NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(HTMLContentSink, nsContentSink)
  NS_DECL_ISUPPORTS_INHERITED

  // nsIContentSink
  NS_IMETHOD WillParse(void) override;
  NS_IMETHOD WillBuildModel(nsDTDMode aDTDMode) override;
  NS_IMETHOD DidBuildModel(bool aTerminated) override;
  NS_IMETHOD WillBuildModel(nsDTDMode aDTDMode) override;
  NS_IMETHOD WillInterrupt(void) override;
  NS_IMETHOD WillResume(void) override;
  NS_IMETHOD SetParser(nsParserBase* aParser) override;
  virtual void FlushPendingNotifications(FlushType aType) override;
  virtual void SetDocumentCharset(NotNull<const Encoding*> aEncoding) override;
  virtual void FlushPendingNotifications(FlushType aType) override;
  virtual nsISupports* GetTarget() override;
  virtual bool IsScriptExecuting() override;
  virtual void ContinueInterruptedParsingAsync() override;

  virtual void ContinueInterruptedParsingAsync() override;
  // nsIHTMLContentSink
  NS_IMETHOD OpenContainer(ElementType aNodeType) override;
  NS_IMETHOD CloseContainer(ElementType aTag) override;

 protected:

  virtual ~HTMLContentSink();

  RefPtr<nsHTMLDocument> mHTMLDocument;

  // The maximum length of a text run

  int32_t mMaxTextRun;

  RefPtr<nsGenericHTMLElement> mRoot;
  RefPtr<nsGenericHTMLElement> mBody;
  RefPtr<nsGenericHTMLElement> mHead;
  RefPtr<nsGenericHTMLElement> mBody;

  AutoTArray<SinkContext*, 8> mContextStack;
  SinkContext* mCurrentContext;
  SinkContext* mHeadContext;
  SinkContext* mCurrentContext;

  // Boolean indicating whether we've seen a <head> tag that might have had
  // attributes once already.
  bool mHaveSeenHead;

  // Boolean indicating whether we've notified insertion of our root content
  bool mHaveSeenHead;
  // yet.  We want to make sure to only do this once.
  bool mNotifiedRootInsertion;

  nsresult FlushTags() override;

  // Routines for tags that require special handling
  nsresult FlushTags() override;
  nsresult CloseHTML();
  nsresult OpenBody();
  nsresult CloseBody();

  void CloseHeadContext();
  nsresult CloseBody();

  // nsContentSink overrides
  void UpdateChildCounts() override;

  void UpdateChildCounts() override;
  void NotifyInsert(nsIContent* aContent, nsIContent* aChildContent);
  void NotifyRootInsertion();

 private:
  void ContinueInterruptedParsingIfEnabled();
 private:
};

class SinkContext {
 public:
  explicit SinkContext(HTMLContentSink* aSink);
 public:
  ~SinkContext();

  nsresult Begin(nsHTMLTag aNodeType, nsGenericHTMLElement* aRoot,
                 uint32_t aNumFlushed, int32_t aInsertionPoint);
  nsresult Begin(nsHTMLTag aNodeType, nsGenericHTMLElement* aRoot,
  nsresult OpenBody();
  nsresult CloseBody();
  nsresult End();

  nsresult GrowStack();

  nsresult FlushTags();

  bool IsCurrentContainer(nsHTMLTag mType);

  void DidAddContent(nsIContent* aContent);

  void UpdateChildCounts();

 private:
  // Function to check whether we've notified for the current content.
  // What this actually does is check whether we've notified for all
  // of the parent's kids.
  // Function to check whether we've notified for the current content.
  bool HaveNotifiedForCurrentContent() const;

 public:
  HTMLContentSink* mSink;
  int32_t mNotifyLevel;

  struct Node {
    nsHTMLTag mType;
    nsGenericHTMLElement* mContent;
  struct Node {
    uint32_t mNumFlushed;
    nsGenericHTMLElement* mContent;
    int32_t mInsertionPoint;

    nsIContent* Add(nsIContent* child);

  };

  Node* mStack;
  int32_t mStackSize;
  int32_t mStackPos;
  int32_t mStackSize;
};

nsresult NS_NewHTMLElement(Element** aResult,
                           already_AddRefed<mozilla::dom::NodeInfo>&& aNodeInfo,
                           FromParser aFromParser, nsAtom* aIsAtom,
                           already_AddRefed<mozilla::dom::NodeInfo>&& aNodeInfo,
                           mozilla::dom::CustomElementDefinition* aDefinition) {
  RefPtr<mozilla::dom::NodeInfo> nodeInfo = aNodeInfo;

  NS_ASSERTION(
      nodeInfo->NamespaceEquals(kNameSpaceID_XHTML),
  NS_ASSERTION(
      "Trying to create HTML elements that don't have the XHTML namespace");

  return nsContentUtils::NewXULOrHTMLElement(aResult, nodeInfo, aFromParser,
                                             aIsAtom, aDefinition);
}
                                             aIsAtom, aDefinition);

already_AddRefed<nsGenericHTMLElement> CreateHTMLElement(
    uint32_t aNodeType, already_AddRefed<mozilla::dom::NodeInfo>&& aNodeInfo,
    FromParser aFromParser) {
  NS_ASSERTION(
      aNodeType <= NS_HTML_TAG_MAX || aNodeType == eHTMLTag_userdefined,
      "aNodeType is out of bounds");
      aNodeType <= NS_HTML_TAG_MAX || aNodeType == eHTMLTag_userdefined,

  HTMLContentCreatorFunction cb = sHTMLContentCreatorFunctions[aNodeType];

  NS_ASSERTION(cb != NS_NewHTMLNOTUSEDElement,
               "Don't know how to construct tag element!");
  NS_ASSERTION(cb != NS_NewHTMLNOTUSEDElement,

  RefPtr<nsGenericHTMLElement> result = cb(std::move(aNodeInfo), aFromParser);

  return result.forget();
}
  return result.forget();

//----------------------------------------------------------------------

SinkContext::SinkContext(HTMLContentSink* aSink)
    : mSink(aSink),
SinkContext::SinkContext(HTMLContentSink* aSink)
      mNotifyLevel(0),
      mStack(nullptr),
      mStackSize(0),
      mStackPos(0) {
  MOZ_COUNT_CTOR(SinkContext);
      mStackPos(0) {
}

SinkContext::~SinkContext() {
  MOZ_COUNT_DTOR(SinkContext);

  if (mStack) {
    for (int32_t i = 0; i < mStackPos; i++) {
      NS_RELEASE(mStack[i].mContent);
    }
    for (int32_t i = 0; i < mStackPos; i++) {
    delete[] mStack;
  }
}

nsresult SinkContext::Begin(nsHTMLTag aNodeType, nsGenericHTMLElement* aRoot,
}
                            uint32_t aNumFlushed, int32_t aInsertionPoint) {
  if (mStackSize < 1) {
    nsresult rv = GrowStack();
    if (NS_FAILED(rv)) {
      return rv;
    nsresult rv = GrowStack();
    }
  }

  mStack[0].mType = aNodeType;
  mStack[0].mContent = aRoot;

  mStack[0].mNumFlushed = aNumFlushed;
  mStack[0].mInsertionPoint = aInsertionPoint;
  NS_ADDREF(aRoot);
  mStackPos = 1;

  NS_ADDREF(aRoot);
  return NS_OK;
}

bool SinkContext::IsCurrentContainer(nsHTMLTag aTag) {
  if (aTag == mStack[mStackPos - 1].mType) {
    return true;
  if (aTag == mStack[mStackPos - 1].mType) {
  }

  return false;
}

}
void SinkContext::DidAddContent(nsIContent* aContent) {
  if ((mStackPos == 2) && (mSink->mBody == mStack[1].mContent)) {
    // We just finished adding something to the body
    mNotifyLevel = 0;
  }
    mNotifyLevel = 0;

  // If we just added content to a node for which
  // an insertion happen, we need to do an immediate
  // notification for that insertion.
  if (0 < mStackPos && mStack[mStackPos - 1].mInsertionPoint != -1 &&
  // notification for that insertion.
      mStack[mStackPos - 1].mNumFlushed <
          mStack[mStackPos - 1].mContent->GetChildCount()) {
    nsIContent* parent = mStack[mStackPos - 1].mContent;
    mSink->NotifyInsert(parent, aContent);
    mStack[mStackPos - 1].mNumFlushed = parent->GetChildCount();
    mSink->NotifyInsert(parent, aContent);
  } else if (mSink->IsTimeToNotify()) {
    FlushTags();
  }
}
  }

nsresult SinkContext::OpenBody() {
  if (mStackPos <= 0) {
    NS_ERROR("container w/o parent");

    NS_ERROR("container w/o parent");
    return NS_ERROR_FAILURE;
  }

  nsresult rv;
  if (mStackPos + 1 > mStackSize) {
  nsresult rv;
    rv = GrowStack();
    if (NS_FAILED(rv)) {
      return rv;
    }
  }
    }

  RefPtr<mozilla::dom::NodeInfo> nodeInfo =
      mSink->mNodeInfoManager->GetNodeInfo(
          nsGkAtoms::body, nullptr, kNameSpaceID_XHTML, nsINode::ELEMENT_NODE);
  NS_ENSURE_TRUE(nodeInfo, NS_ERROR_UNEXPECTED);
          nsGkAtoms::body, nullptr, kNameSpaceID_XHTML, nsINode::ELEMENT_NODE);

  // Make the content object
  RefPtr<nsGenericHTMLElement> body =
      NS_NewHTMLBodyElement(nodeInfo.forget(), FROM_PARSER_NETWORK);
  if (!body) {
      NS_NewHTMLBodyElement(nodeInfo.forget(), FROM_PARSER_NETWORK);
    return NS_ERROR_OUT_OF_MEMORY;
  }

  mStack[mStackPos].mType = eHTMLTag_body;
  body.forget(&mStack[mStackPos].mContent);
  mStack[mStackPos].mNumFlushed = 0;
  mStack[mStackPos].mInsertionPoint = -1;
  ++mStackPos;
  mStack[mStackPos].mInsertionPoint = -1;
  mStack[mStackPos - 2].Add(mStack[mStackPos - 1].mContent);

  return NS_OK;
}

}
bool SinkContext::HaveNotifiedForCurrentContent() const {
  if (0 < mStackPos) {
    nsIContent* parent = mStack[mStackPos - 1].mContent;
    return mStack[mStackPos - 1].mNumFlushed == parent->GetChildCount();
  }
    return mStack[mStackPos - 1].mNumFlushed == parent->GetChildCount();

  return true;
}

nsIContent* SinkContext::Node::Add(nsIContent* child) {

  NS_ASSERTION(mContent, "No parent to insert/append into!");
  if (mInsertionPoint != -1) {
    NS_ASSERTION(mNumFlushed == mContent->GetChildCount(),
                 "Inserting multiple children without flushing.");
    nsCOMPtr<nsIContent> nodeToInsertBefore =
                 "Inserting multiple children without flushing.");
        mContent->GetChildAt_Deprecated(mInsertionPoint++);
    nsCOMPtr<nsIContent> nodeToInsertBefore =
    mContent->InsertChildBefore(child, nodeToInsertBefore, false);
  } else {
    mContent->AppendChildTo(child, false);
  }
  return child;
  }
}

nsresult SinkContext::CloseBody() {
  NS_ASSERTION(mStackPos > 0, "stack out of bounds. wrong context probably!");

  NS_ASSERTION(mStackPos > 0, "stack out of bounds. wrong context probably!");
  if (mStackPos <= 0) {
    return NS_OK;  // Fix crash - Ref. bug 45975 or 45007
  }

  --mStackPos;
  }
  NS_ASSERTION(mStack[mStackPos].mType == eHTMLTag_body,
               "Tag mismatch.  Closing tag on wrong context or something?");

  nsGenericHTMLElement* content = mStack[mStackPos].mContent;


  content->Compact();

  // If we're in a state where we do append notifications as
  // we go up the tree, and we're at the level where the next
  // If we're in a state where we do append notifications as
  // notification needs to be done, do the notification.
  if (mNotifyLevel >= mStackPos) {
    // Check to see if new content has been added after our last
    // notification

    // notification
    if (mStack[mStackPos].mNumFlushed < content->GetChildCount()) {
      mSink->NotifyAppend(content, mStack[mStackPos].mNumFlushed);
      mStack[mStackPos].mNumFlushed = content->GetChildCount();
    }

    }
    // Indicate that notification has now happened at this level
    mNotifyLevel = mStackPos - 1;
  }

  DidAddContent(content);

  NS_IF_RELEASE(content);

  return NS_OK;
}

}
nsresult SinkContext::End() {
  for (int32_t i = 0; i < mStackPos; i++) {
    NS_RELEASE(mStack[i].mContent);
  }

  }
  mStackPos = 0;

  return NS_OK;
}

nsresult SinkContext::GrowStack() {
  int32_t newSize = mStackSize * 2;
nsresult SinkContext::GrowStack() {
  if (newSize == 0) {
    newSize = 32;
  }

  Node* stack = new Node[newSize];


  if (mStackPos != 0) {
    memcpy(stack, mStack, sizeof(Node) * mStackPos);
    delete[] mStack;
  }

    delete[] mStack;
  mStack = stack;
  mStackSize = newSize;

  return NS_OK;
}


/**
 * NOTE!! Forked into nsXMLContentSink. Please keep in sync.
 *
 * Flush all elements that have been seen so far such that
 * NOTE!! Forked into nsXMLContentSink. Please keep in sync.
 * they are visible in the tree. Specifically, make sure
 * that they are all added to their respective parents.
 * Also, do notification at the top for all content that
 * has been newly added so that the frame tree is complete.
 */
nsresult SinkContext::FlushTags() {
  mSink->mDeferredFlushTags = false;
nsresult SinkContext::FlushTags() {
  uint32_t oldUpdates = mSink->mUpdatesInNotification;

  ++(mSink->mInNotification);
  mSink->mUpdatesInNotification = 0;
  {
  mSink->mUpdatesInNotification = 0;
    // Scope so we call EndUpdate before we decrease mInNotification
    mozAutoDocUpdate updateBatch(mSink->mDocument, true);

    // Start from the base of the stack (growing downward) and do
    // a notification from the node that is closest to the root of
    // Start from the base of the stack (growing downward) and do
    // tree for any content that has been added.

    // Note that we can start at stackPos == 0 here, because it's the caller's
    // responsibility to handle flushing interactions between contexts (see
    // HTMLContentSink::BeginContext).
    // responsibility to handle flushing interactions between contexts (see
    int32_t stackPos = 0;
    bool flushed = false;
    uint32_t childCount;
    nsGenericHTMLElement* content;

    while (stackPos < mStackPos) {
      content = mStack[stackPos].mContent;
    while (stackPos < mStackPos) {
      childCount = content->GetChildCount();
      content = mStack[stackPos].mContent;

      if (!flushed && (mStack[stackPos].mNumFlushed < childCount)) {
        if (mStack[stackPos].mInsertionPoint != -1) {
          // We might have popped the child off our stack already
          // but not notified on it yet, which is why we have to get it
          // We might have popped the child off our stack already
          // directly from its parent node.

          int32_t childIndex = mStack[stackPos].mInsertionPoint - 1;
          nsIContent* child = content->GetChildAt_Deprecated(childIndex);
          // Child not on stack anymore; can't assert it's correct
          nsIContent* child = content->GetChildAt_Deprecated(childIndex);
          NS_ASSERTION(!(mStackPos > (stackPos + 1)) ||
                           (child == mStack[stackPos + 1].mContent),
                       "Flushing the wrong child.");
          mSink->NotifyInsert(content, child);
                       "Flushing the wrong child.");
        } else {
          mSink->NotifyAppend(content, mStack[stackPos].mNumFlushed);
        }

        flushed = true;

      }

      mStack[stackPos].mNumFlushed = childCount;
      stackPos++;
    }
      stackPos++;
    mNotifyLevel = mStackPos - 1;
  }
  --(mSink->mInNotification);
    mNotifyLevel = mStackPos - 1;

  if (mSink->mUpdatesInNotification > 1) {
    UpdateChildCounts();
  }

    UpdateChildCounts();
  mSink->mUpdatesInNotification = oldUpdates;

  return NS_OK;
}

  return NS_OK;
/**
 * NOTE!! Forked into nsXMLContentSink. Please keep in sync.
 */
void SinkContext::UpdateChildCounts() {
  // Start from the top of the stack (growing upwards) and see if any
  // new content has been appended. If so, we recognize that reflows
  // Start from the top of the stack (growing upwards) and see if any
  // have been generated for it and we should make sure that no
  // further reflows occur.  Note that we have to include stackPos == 0
  // to properly notify on kids of <html>.
  int32_t stackPos = mStackPos - 1;
  while (stackPos >= 0) {
  int32_t stackPos = mStackPos - 1;
    Node& node = mStack[stackPos];
    node.mNumFlushed = node.mContent->GetChildCount();

    stackPos--;
  }

    stackPos--;
  mNotifyLevel = mStackPos - 1;
}

nsresult NS_NewHTMLContentSink(nsIHTMLContentSink** aResult, Document* aDoc,
                               nsIURI* aURI, nsISupports* aContainer,

                               nsIChannel* aChannel) {
  NS_ENSURE_ARG_POINTER(aResult);

  RefPtr<HTMLContentSink> it = new HTMLContentSink();


  nsresult rv = it->Init(aDoc, aURI, aContainer, aChannel);

  NS_ENSURE_SUCCESS(rv, rv);


  *aResult = it;
  NS_ADDREF(*aResult);

  return NS_OK;

}

HTMLContentSink::HTMLContentSink()
    : mMaxTextRun(0),
      mCurrentContext(nullptr),
    : mMaxTextRun(0),
      mHeadContext(nullptr),
      mHaveSeenHead(false),
      mNotifiedRootInsertion(false) {}

HTMLContentSink::~HTMLContentSink() {
  if (mNotificationTimer) {
HTMLContentSink::~HTMLContentSink() {
    mNotificationTimer->Cancel();
  }

  if (mCurrentContext == mHeadContext && !mContextStack.IsEmpty()) {
    // Pop off the second html context if it's not done earlier
  int32_t numContexts = mContextStack.Length();
    mContextStack.RemoveLastElement();
  }

  for (int32_t i = 0, numContexts = mContextStack.Length(); i < numContexts;
       i++) {
  }
    SinkContext* sc = mContextStack.ElementAt(i);
    if (sc) {
      sc->End();
      if (sc == mCurrentContext) {
        mCurrentContext = nullptr;
      }

      if (sc == mCurrentContext) {
      delete sc;
    }
  }

  if (mCurrentContext == mHeadContext) {
    }
    mCurrentContext = nullptr;
  }

  delete mCurrentContext;

  delete mHeadContext;
}


NS_IMPL_CYCLE_COLLECTION_INHERITED(HTMLContentSink, nsContentSink,
                                   mHTMLDocument, mRoot, mBody, mHead)

NS_IMPL_ISUPPORTS_CYCLE_COLLECTION_INHERITED(HTMLContentSink, nsContentSink,

                                             nsIContentSink, nsIHTMLContentSink)

nsresult HTMLContentSink::Init(Document* aDoc, nsIURI* aURI,
NS_IMPL_ISUPPORTS_CYCLE_COLLECTION_INHERITED(HTMLContentSink, nsContentSink,
                               nsISupports* aContainer, nsIChannel* aChannel) {
  NS_ENSURE_TRUE(aContainer, NS_ERROR_NULL_POINTER);

  nsresult rv = nsContentSink::Init(aDoc, aURI, aContainer, aChannel);
  if (NS_FAILED(rv)) {
    return rv;
  NS_ENSURE_TRUE(aContainer, NS_ERROR_NULL_POINTER);
  }

  aDoc->AddObserver(this);
  mIsDocumentObserver = true;
  mHTMLDocument = aDoc->AsHTMLDocument();
  }

  NS_ASSERTION(mDocShell, "oops no docshell!");

  // Changed from 8192 to greatly improve page loading performance on
  // large pages.  See bugzilla bug 77540.

  mMaxTextRun = Preferences::GetInt("content.maxtextrun", 8191);

  RefPtr<mozilla::dom::NodeInfo> nodeInfo;
  nodeInfo = mNodeInfoManager->GetNodeInfo(
      nsGkAtoms::html, nullptr, kNameSpaceID_XHTML, nsINode::ELEMENT_NODE);
  mMaxTextRun = Preferences::GetInt("content.maxtextrun", 8191);

  // Make root part
  mRoot = NS_NewHTMLHtmlElement(nodeInfo.forget());
  if (!mRoot) {
    return NS_ERROR_OUT_OF_MEMORY;

  }

  NS_ASSERTION(mDocument->GetChildCount() == 0,
               "Document should have no kids here!");
  rv = mDocument->AppendChildTo(mRoot, false);
  }
  NS_ENSURE_SUCCESS(rv, rv);

  // Make head part
  nodeInfo = mNodeInfoManager->GetNodeInfo(
      nsGkAtoms::head, nullptr, kNameSpaceID_XHTML, nsINode::ELEMENT_NODE);

  // Make head part
  mHead = NS_NewHTMLHeadElement(nodeInfo.forget());
  if (NS_FAILED(rv)) {
    return NS_ERROR_OUT_OF_MEMORY;
  }

  mRoot->AppendChildTo(mHead, false);

  }
  mCurrentContext = new SinkContext(this);
  mCurrentContext->Begin(eHTMLTag_html, mRoot, 0, -1);
  mContextStack.AppendElement(mCurrentContext);

  return NS_OK;
  mCurrentContext->Begin(eHTMLTag_html, mRoot, 0, -1);
}

NS_IMETHODIMP
HTMLContentSink::WillParse(void) { return WillParseImpl(); }
}

NS_IMETHODIMP
HTMLContentSink::WillBuildModel(nsDTDMode aDTDMode) {
  WillBuildModelImpl();

NS_IMETHODIMP
  nsCompatibility mode = eCompatibility_NavQuirks;
  switch (aDTDMode) {
    case eDTDMode_full_standards:
      mode = eCompatibility_FullStandards;
      break;
  switch (aDTDMode) {
    case eDTDMode_almost_standards:
      mode = eCompatibility_AlmostStandards;
      break;
    default:
      break;
      mode = eCompatibility_AlmostStandards;
  }
  mDocument->SetCompatibilityMode(mode);

  // Notify document that the load is beginning
  mDocument->BeginLoad();
  mDocument->SetCompatibilityMode(mode);

  return NS_OK;
}

NS_IMETHODIMP
  return NS_OK;
HTMLContentSink::DidBuildModel(bool aTerminated) {
  DidBuildModelImpl(aTerminated);

  // Reflow the last batch of content
  if (mBody) {
    mCurrentContext->FlushTags();
  } else if (!mLayoutStarted) {
    // We never saw the body, and layout never got started. Force
  // Reflow the last batch of content
    // layout *now*, to get an initial reflow.
    // NOTE: only force the layout if we are NOT destroying the
    // docshell. If we are destroying it, then starting layout will
    // likely cause us to crash, or at best waste a lot of time as we
    // are just going to tear it down anyway.
    // layout *now*, to get an initial reflow.
    bool bDestroying = true;
    if (mDocShell) {
      mDocShell->IsBeingDestroyed(&bDestroying);
    }

    if (!bDestroying) {
      StartLayout(false);
      mDocShell->IsBeingDestroyed(&bDestroying);
    }
  }

  ScrollToRef();

    }
  // Make sure we no longer respond to document mutations.  We've flushed all
  // our notifications out, so there's no need to do anything else here.

  // XXXbz I wonder whether we could End() our contexts here too, or something,
  // just to make sure we no longer notify...  Or is the mIsDocumentObserver
  // Make sure we no longer respond to document mutations.  We've flushed all
  // thing sufficient?
  mDocument->RemoveObserver(this);
  mIsDocumentObserver = false;

  mDocument->EndLoad();
  // thing sufficient?

  DropParserAndPerfHint();

  mDocument->EndLoad();
  return NS_OK;
}

NS_IMETHODIMP
HTMLContentSink::SetParser(nsParserBase* aParser) {
  MOZ_ASSERT(aParser, "Should have a parser here!");
  mParser = aParser;
  return NS_OK;
NS_IMETHODIMP
}

nsresult HTMLContentSink::CloseHTML() {
  if (mHeadContext) {
    if (mCurrentContext == mHeadContext) {
}
      // Pop off the second html context if it's not done earlier
      mCurrentContext = mContextStack.PopLastElement();
    }

    mHeadContext->End();
      uint32_t numContexts = mContextStack.Length();

    delete mHeadContext;
    mHeadContext = nullptr;
  }

    }
  return NS_OK;
}

nsresult HTMLContentSink::OpenBody() {
  CloseHeadContext();  // do this just in case if the HEAD was left open!
    mHeadContext = nullptr;

  // if we already have a body we're done
  if (mBody) {
    return NS_OK;
  }


  nsresult rv = mCurrentContext->OpenBody();

  // if we already have a body we're done
  if (NS_FAILED(rv)) {
    return rv;
  }

  mBody = mCurrentContext->mStack[mCurrentContext->mStackPos - 1].mContent;
  nsresult rv = mCurrentContext->OpenBody();

  if (mCurrentContext->mStackPos > 1) {
    int32_t parentIndex = mCurrentContext->mStackPos - 2;
    nsGenericHTMLElement* parent =
        mCurrentContext->mStack[parentIndex].mContent;
    int32_t numFlushed = mCurrentContext->mStack[parentIndex].mNumFlushed;

    int32_t childCount = parent->GetChildCount();
    NS_ASSERTION(numFlushed < childCount, "Already notified on the body?");

    int32_t insertionPoint =
        mCurrentContext->mStack[parentIndex].mInsertionPoint;
    nsGenericHTMLElement* parent =

    // XXX: I have yet to see a case where numFlushed is non-zero and
    // insertionPoint is not -1, but this code will try to handle
    // those cases too.


    uint32_t oldUpdates = mUpdatesInNotification;
    mUpdatesInNotification = 0;
    if (insertionPoint != -1) {
      NotifyInsert(parent, mBody);
    // insertionPoint is not -1, but this code will try to handle
    } else {
      NotifyAppend(parent, numFlushed);
    }
    mCurrentContext->mStack[parentIndex].mNumFlushed = childCount;
    mUpdatesInNotification = 0;
    if (mUpdatesInNotification > 1) {
      UpdateChildCounts();
    }
    mUpdatesInNotification = oldUpdates;
  }
    }

  StartLayout(false);

  return NS_OK;
}
    mUpdatesInNotification = oldUpdates;

nsresult HTMLContentSink::CloseBody() {
  // Flush out anything that's left
  mCurrentContext->FlushTags();
  mCurrentContext->CloseBody();
  return NS_OK;

  return NS_OK;
}

NS_IMETHODIMP
  mCurrentContext->FlushTags();
HTMLContentSink::OpenContainer(ElementType aElementType) {
  nsresult rv = NS_OK;


  switch (aElementType) {
    case eBody:
      rv = OpenBody();
      break;
    case eHTML:
HTMLContentSink::OpenContainer(ElementType aElementType) {
      if (mRoot) {
        // If we've already hit this code once, then we're done
        if (!mNotifiedRootInsertion) {
          NotifyRootInsertion();
        }
      rv = OpenBody();
        ProcessOfflineManifest(mRoot);
      }
      break;
  }

        if (!mNotifiedRootInsertion) {
  return rv;
}

NS_IMETHODIMP
HTMLContentSink::CloseContainer(const ElementType aTag) {
      break;
  nsresult rv = NS_OK;

  switch (aTag) {
    case eBody:
      rv = CloseBody();

      break;
    case eHTML:
      rv = CloseHTML();
      break;
  }
    case eBody:

  return rv;
}

NS_IMETHODIMP
      break;
HTMLContentSink::WillInterrupt() { return WillInterruptImpl(); }

NS_IMETHODIMP
HTMLContentSink::WillResume() { return WillResumeImpl(); }


void HTMLContentSink::CloseHeadContext() {
  if (mCurrentContext) {
    if (!mCurrentContext->IsCurrentContainer(eHTMLTag_head)) return;

    mCurrentContext->FlushTags();
HTMLContentSink::WillResume() { return WillResumeImpl(); }
  }

  if (!mContextStack.IsEmpty()) {
    mCurrentContext = mContextStack.PopLastElement();
  }

}

void HTMLContentSink::NotifyInsert(nsIContent* aContent,
                                   nsIContent* aChildContent) {
  if (!mContextStack.IsEmpty()) {
  mInNotification++;

  {
    // Scope so we call EndUpdate before we decrease mInNotification
    // Note that aContent->OwnerDoc() may be different to mDocument already.
  }
    MOZ_AUTO_DOC_UPDATE(aContent ? aContent->OwnerDoc() : mDocument.get(),
                        true);
    MutationObservers::NotifyContentInserted(NODE_FROM(aContent, mDocument),
                                             aChildContent);
                                   nsIContent* aChildContent) {
    mLastNotificationTime = PR_Now();
  }

  mInNotification--;
}
    // Note that aContent->OwnerDoc() may be different to mDocument already.

void HTMLContentSink::NotifyRootInsertion() {
  MOZ_ASSERT(!mNotifiedRootInsertion, "Double-notifying on root?");
  NS_ASSERTION(!mLayoutStarted,
               "How did we start layout without notifying on root?");
    mLastNotificationTime = PR_Now();
  // Now make sure to notify that we have now inserted our root.  If
  // there has been no initial reflow yet it'll be a no-op, but if
  // there has been one we need this to get its frames constructed.
  // Note that if mNotifiedRootInsertion is true we don't notify here,
  // since that just means there are multiple <html> tags in the

  // document; in those cases we just want to put all the attrs on one
  // tag.
  mNotifiedRootInsertion = true;
  NotifyInsert(nullptr, mRoot);

  // Now update the notification information in all our
  // contexts, since we just inserted the root and notified on
  // our whole tree
  UpdateChildCounts();
  // since that just means there are multiple <html> tags in the

  nsContentUtils::AddScriptRunner(
      new nsDocElementCreatedNotificationRunner(mDocument));
}


void HTMLContentSink::UpdateChildCounts() {
  uint32_t numContexts = mContextStack.Length();
  for (uint32_t i = 0; i < numContexts; i++) {
    SinkContext* sc = mContextStack.ElementAt(i);


    sc->UpdateChildCounts();
  }

  mCurrentContext->UpdateChildCounts();
void HTMLContentSink::UpdateChildCounts() {
}

void HTMLContentSink::FlushPendingNotifications(FlushType aType) {
  // Only flush tags if we're not doing the notification ourselves
  // (since we aren't reentrant)
    sc->UpdateChildCounts();
  if (!mInNotification) {
    // Only flush if we're still a document observer (so that our child counts
    // should be correct).
    if (mIsDocumentObserver) {
      if (aType >= FlushType::ContentAndNotify) {

        FlushTags();
      }
    }
    if (aType >= FlushType::EnsurePresShellInitAndFrames) {
      // Make sure that layout has started so that the reflow flush
    // Only flush if we're still a document observer (so that our child counts
      // will actually happen.
      StartLayout(true);
    }
  }
}
      }

nsresult HTMLContentSink::FlushTags() {
  if (!mNotifiedRootInsertion) {
    NotifyRootInsertion();
    return NS_OK;
      StartLayout(true);
  }

  return mCurrentContext ? mCurrentContext->FlushTags() : NS_OK;
}


void HTMLContentSink::SetDocumentCharset(NotNull<const Encoding*> aEncoding) {
  MOZ_ASSERT_UNREACHABLE("<meta charset> case doesn't occur with about:blank");
}

  }
nsISupports* HTMLContentSink::GetTarget() { return ToSupports(mDocument); }

bool HTMLContentSink::IsScriptExecuting() { return IsScriptExecutingImpl(); }

void HTMLContentSink::ContinueInterruptedParsingIfEnabled() {
void HTMLContentSink::SetDocumentCharset(NotNull<const Encoding*> aEncoding) {
  if (mParser && mParser->IsParserEnabled()) {
    static_cast<nsIParser*>(mParser.get())->ContinueInterruptedParsing();
  }
}


void HTMLContentSink::ContinueInterruptedParsingAsync() {
  nsCOMPtr<nsIRunnable> ev = NewRunnableMethod(
      "HTMLContentSink::ContinueInterruptedParsingIfEnabled", this,
      &HTMLContentSink::ContinueInterruptedParsingIfEnabled);
  if (mParser && mParser->IsParserEnabled()) {

  RefPtr<Document> doc = mHTMLDocument;
  doc->Dispatch(mozilla::TaskCategory::Other, ev.forget());
}
void HTMLContentSink::ContinueInterruptedParsingAsync() {
  RefPtr<Document> doc = mHTMLDocument;