summaryrefslogtreecommitdiff
path: root/chromium/third_party/blink/renderer/core/html/parser/html_construction_site.h
blob: b0d8394321fc5ac767248711a86675a353163c95 (plain)
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
/*
 * Copyright (C) 2010 Google, Inc. All Rights Reserved.
 * Copyright (C) 2011 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL GOOGLE INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_HTML_PARSER_HTML_CONSTRUCTION_SITE_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_PARSER_HTML_CONSTRUCTION_SITE_H_

#include "base/macros.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/parser_content_policy.h"
#include "third_party/blink/renderer/core/html/parser/html_element_stack.h"
#include "third_party/blink/renderer/core/html/parser/html_formatting_element_list.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"

namespace blink {

struct HTMLConstructionSiteTask {
  DISALLOW_NEW();

 public:
  enum Operation {
    kInsert,
    kInsertText,                // Handles possible merging of text nodes.
    kInsertAlreadyParsedChild,  // Insert w/o calling begin/end parsing.
    kReparent,
    kTakeAllChildren,
  };

  explicit HTMLConstructionSiteTask(Operation op)
      : operation(op), self_closing(false) {}

  void Trace(blink::Visitor* visitor) {
    visitor->Trace(parent);
    visitor->Trace(next_child);
    visitor->Trace(child);
  }

  ContainerNode* OldParent() {
    // It's sort of ugly, but we store the |oldParent| in the |child| field of
    // the task so that we don't bloat the HTMLConstructionSiteTask object in
    // the common case of the Insert operation.
    return ToContainerNode(child.Get());
  }

  Operation operation;
  Member<ContainerNode> parent;
  Member<Node> next_child;
  Member<Node> child;
  bool self_closing;
};

}  // namespace blink

WTF_ALLOW_MOVE_INIT_AND_COMPARE_WITH_MEM_FUNCTIONS(
    blink::HTMLConstructionSiteTask);

namespace blink {

// Note: These are intentionally ordered so that when we concatonate strings and
// whitespaces the resulting whitespace is ws = min(ws1, ws2).
enum WhitespaceMode {
  kWhitespaceUnknown,
  kNotAllWhitespace,
  kAllWhitespace,
};

enum FlushMode {
  // Flush pending text. Flush queued tasks.
  kFlushAlways,

  // Flush pending text if node has length limit. Flush queued tasks.
  kFlushIfAtTextLimit,
};

class AtomicHTMLToken;
class CustomElementDefinition;
class Document;
class Element;
class HTMLFormElement;
class HTMLParserReentryPermit;

class HTMLConstructionSite final {
  DISALLOW_NEW();

 public:
  HTMLConstructionSite(HTMLParserReentryPermit*,
                       Document&,
                       ParserContentPolicy);
  ~HTMLConstructionSite();
  void Trace(blink::Visitor*);

  void InitFragmentParsing(DocumentFragment*, Element* context_element);

  void Detach();

  // executeQueuedTasks empties the queue but does not flush pending text.
  // NOTE: Possible reentrancy via JavaScript execution.
  void ExecuteQueuedTasks();

  // flushPendingText turns pending text into queued Text insertions, but does
  // not execute them.
  void FlushPendingText(FlushMode);

  // Called before every token in HTMLTreeBuilder::processToken, thus inlined:
  void Flush(FlushMode mode) {
    if (!HasPendingTasks())
      return;
    FlushPendingText(mode);
    // NOTE: Possible reentrancy via JavaScript execution.
    ExecuteQueuedTasks();
    DCHECK(mode == kFlushIfAtTextLimit || !HasPendingTasks());
  }

  bool HasPendingTasks() {
    return !pending_text_.IsEmpty() || !task_queue_.IsEmpty();
  }

  void SetDefaultCompatibilityMode();
  void ProcessEndOfFile();
  void FinishedParsing();

  void InsertDoctype(AtomicHTMLToken*);
  void InsertComment(AtomicHTMLToken*);
  void InsertCommentOnDocument(AtomicHTMLToken*);
  void InsertCommentOnHTMLHtmlElement(AtomicHTMLToken*);
  void InsertHTMLElement(AtomicHTMLToken*);
  void InsertSelfClosingHTMLElementDestroyingToken(AtomicHTMLToken*);
  void InsertFormattingElement(AtomicHTMLToken*);
  void InsertHTMLHeadElement(AtomicHTMLToken*);
  void InsertHTMLBodyElement(AtomicHTMLToken*);
  void InsertHTMLFormElement(AtomicHTMLToken*, bool is_demoted = false);
  void InsertScriptElement(AtomicHTMLToken*);
  void InsertTextNode(const StringView&, WhitespaceMode = kWhitespaceUnknown);
  void InsertForeignElement(AtomicHTMLToken*,
                            const AtomicString& namespace_uri);

  void InsertHTMLHtmlStartTagBeforeHTML(AtomicHTMLToken*);
  void InsertHTMLHtmlStartTagInBody(AtomicHTMLToken*);
  void InsertHTMLBodyStartTagInBody(AtomicHTMLToken*);

  void Reparent(HTMLElementStack::ElementRecord* new_parent,
                HTMLElementStack::ElementRecord* child);
  void Reparent(HTMLElementStack::ElementRecord* new_parent,
                HTMLStackItem* child);
  // insertAlreadyParsedChild assumes that |child| has already been parsed
  // (i.e., we're just moving it around in the tree rather than parsing it for
  // the first time). That means this function doesn't call beginParsingChildren
  // / finishParsingChildren.
  void InsertAlreadyParsedChild(HTMLStackItem* new_parent,
                                HTMLElementStack::ElementRecord* child);
  void TakeAllChildren(HTMLStackItem* new_parent,
                       HTMLElementStack::ElementRecord* old_parent);

  HTMLStackItem* CreateElementFromSavedToken(HTMLStackItem*);

  bool ShouldFosterParent() const;
  void FosterParent(Node*);

  bool IndexOfFirstUnopenFormattingElement(
      unsigned& first_unopen_element_index) const;
  void ReconstructTheActiveFormattingElements();

  void GenerateImpliedEndTags();
  void GenerateImpliedEndTagsWithExclusion(const AtomicString& tag_name);

  bool InQuirksMode();

  bool IsEmpty() const { return !open_elements_.StackDepth(); }
  HTMLElementStack::ElementRecord* CurrentElementRecord() const {
    return open_elements_.TopRecord();
  }
  Element* CurrentElement() const { return open_elements_.Top(); }
  ContainerNode* CurrentNode() const { return open_elements_.TopNode(); }
  HTMLStackItem* CurrentStackItem() const {
    return open_elements_.TopStackItem();
  }
  HTMLStackItem* OneBelowTop() const { return open_elements_.OneBelowTop(); }
  Document& OwnerDocumentForCurrentNode();
  HTMLElementStack* OpenElements() const { return &open_elements_; }
  HTMLFormattingElementList* ActiveFormattingElements() const {
    return &active_formatting_elements_;
  }
  bool CurrentIsRootNode() {
    return open_elements_.TopNode() == open_elements_.RootNode();
  }

  Element* Head() const { return head_->GetElement(); }
  HTMLStackItem* HeadStackItem() const { return head_.Get(); }

  bool IsFormElementPointerNonNull() const { return form_; }
  HTMLFormElement* TakeForm();

  ParserContentPolicy GetParserContentPolicy() {
    return parser_content_policy_;
  }

  class RedirectToFosterParentGuard {
    STACK_ALLOCATED();
    DISALLOW_COPY_AND_ASSIGN(RedirectToFosterParentGuard);

   public:
    RedirectToFosterParentGuard(HTMLConstructionSite& tree)
        : tree_(tree),
          was_redirecting_before_(tree.redirect_attach_to_foster_parent_) {
      tree_.redirect_attach_to_foster_parent_ = true;
    }

    ~RedirectToFosterParentGuard() {
      tree_.redirect_attach_to_foster_parent_ = was_redirecting_before_;
    }

   private:
    HTMLConstructionSite& tree_;
    bool was_redirecting_before_;
  };

 private:
  // In the common case, this queue will have only one task because most tokens
  // produce only one DOM mutation.
  typedef HeapVector<HTMLConstructionSiteTask, 1> TaskQueue;

  void SetCompatibilityMode(Document::CompatibilityMode);
  void SetCompatibilityModeFromDoctype(const String& name,
                                       const String& public_id,
                                       const String& system_id);

  void AttachLater(ContainerNode* parent,
                   Node* child,
                   bool self_closing = false);

  void FindFosterSite(HTMLConstructionSiteTask&);

  CreateElementFlags GetCreateElementFlags() const;
  Element* CreateElement(AtomicHTMLToken*, const AtomicString& namespace_uri);

  void MergeAttributesFromTokenIntoElement(AtomicHTMLToken*, Element*);

  void ExecuteTask(HTMLConstructionSiteTask&);
  void QueueTask(const HTMLConstructionSiteTask&);

  CustomElementDefinition* LookUpCustomElementDefinition(
      Document&,
      const QualifiedName&,
      const AtomicString& is);

  HTMLParserReentryPermit* reentry_permit_;
  Member<Document> document_;

  // This is the root ContainerNode to which the parser attaches all newly
  // constructed nodes. It points to a DocumentFragment when parsing fragments
  // and a Document in all other cases.
  Member<ContainerNode> attachment_root_;

  // https://html.spec.whatwg.org/multipage/syntax.html#head-element-pointer
  Member<HTMLStackItem> head_;
  // https://html.spec.whatwg.org/multipage/syntax.html#form-element-pointer
  Member<HTMLFormElement> form_;
  mutable HTMLElementStack open_elements_;
  mutable HTMLFormattingElementList active_formatting_elements_;

  TaskQueue task_queue_;

  class PendingText final {
    DISALLOW_NEW();

   public:
    PendingText() : whitespace_mode(kWhitespaceUnknown) {}

    void Append(ContainerNode* new_parent,
                Node* new_next_child,
                const StringView& new_string,
                WhitespaceMode new_whitespace_mode) {
      DCHECK(!parent || parent == new_parent);
      parent = new_parent;
      DCHECK(!next_child || next_child == new_next_child);
      next_child = new_next_child;
      string_builder.Append(new_string);
      whitespace_mode = std::min(whitespace_mode, new_whitespace_mode);
    }

    void Swap(PendingText& other) {
      std::swap(whitespace_mode, other.whitespace_mode);
      parent.Swap(other.parent);
      next_child.Swap(other.next_child);
      string_builder.Swap(other.string_builder);
    }

    void Discard() {
      PendingText discarded_text;
      Swap(discarded_text);
    }

    bool IsEmpty() {
      // When the stringbuilder is empty, the parent and whitespace should also
      // be "empty".
      DCHECK_EQ(string_builder.IsEmpty(), !parent);
      DCHECK(!string_builder.IsEmpty() || !next_child);
      DCHECK(!string_builder.IsEmpty() ||
             (whitespace_mode == kWhitespaceUnknown));
      return string_builder.IsEmpty();
    }

    void Trace(blink::Visitor*);

    Member<ContainerNode> parent;
    Member<Node> next_child;
    StringBuilder string_builder;
    WhitespaceMode whitespace_mode;
  };

  PendingText pending_text_;

  ParserContentPolicy parser_content_policy_;
  bool is_parsing_fragment_;

  // http://www.whatwg.org/specs/web-apps/current-work/multipage/tokenization.html#parsing-main-intable
  // In the "in table" insertion mode, we sometimes get into a state where
  // "whenever a node would be inserted into the current node, it must instead
  // be foster parented."  This flag tracks whether we're in that state.
  bool redirect_attach_to_foster_parent_;

  bool in_quirks_mode_;

  DISALLOW_COPY_AND_ASSIGN(HTMLConstructionSite);
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_HTML_PARSER_HTML_CONSTRUCTION_SITE_H_