File: html-containment.html

package info (click to toggle)
owasp-java-html-sanitizer 20191001.1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, trixie
  • size: 2,580 kB
  • sloc: javascript: 39,520; java: 16,303; xml: 561; sh: 120; makefile: 2
file content (869 lines) | stat: -rw-r--r-- 30,751 bytes parent folder | download
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
<!doctype html>
<html>
<head>
<title>HTML containment</title>
<script>
if (!Date.now) { Date.now = function () { return +new Date; }; }
</script>
<script src="html-containment.js"></script>
<script>
// Extract URL query parameters into options
var opts = {
  // use a short list for quick iteration and debugging
  shortlist: false,
  rerun:     false
};
var cannedData;
(function () {
  location.search.replace(
      /[?&]([^&=]*)(?:=(?:false|no|([^&]*))(?![^&]))?/ig,
      function (_, keyEncoded, valueEncoded) {
        var key   = decodeURIComponent(keyEncoded);
        var value = valueEncoded == null ? "true"
                  : decodeURIComponent(valueEncoded);
        opts[key] = value;
      });

  if (opts.rerun) {
    cannedData = newBlankObject();
  } else {
    document.write('<script src="canned-data.js"><\/script>');
  }
})();
</script>
<script>
// Includes both conforming and obsolete elements from
// http://dev.w3.org/html5/html-author/#index-of-elements
// It does not include foreign content.
var elementNames =
  opts.shortlist
? [
  'a', 'font', 'form', 'frameset', 'h1', 'h2', 'iframe',
  'img', 'li', 'ol', 'plaintext', 'script', 'select', 'table', 'tbody',
  'textarea', 'td', 'tr', 'video', 'xmp'
]
: [
  'a', 'abbr', 'acronym', 'address', 'applet', 'area', 'article',
  'aside', 'audio', 'b', 'base', 'basefont', 'bb', 'bdi', 'bdo',
  'bgsound', 'big', 'blink', 'blockquote', 'body', 'br', 'button',
  'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup',
  'command', 'content', 'data', 'datagrid', 'datalist', 'dd', 'del',
  'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element',
  'em', 'embed', 'fieldset', 'figcaption', 'figure', 'font', 'footer',
  'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
  'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img',
  'input', 'ins', 'isindex', 'kbd', 'keygen', 'label', 'legend', 'li',
  'link', 'listing', 'main', 'map', 'mark', 'marquee', 'menu',
  'menuitem', 'meta', 'meter', 'multicol', 'nav', 'nobr', 'noembed',
  'noframes', 'noscript', 'object', 'ol', 'optgroup', 'option',
  'output', 'p', 'param', 'picture', 'plaintext', 'pre', 'progress',
  'q', 'rp', 'rt', 'rtc', 'ruby', 's', 'samp', 'script', 'section',
  'select', 'shadow', 'slot', 'small', 'source', 'spacer', 'span',
  'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table',
  'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead',
  'time', 'title', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video',
  'wbr', 'xmp',

  'xcustom'
];
</script>
<style>
pre.json  { white-space: pre-wrap }
.json-kw          { color: #800 }
.json-str         { color: #080 }
.json-val         { color: #008 }
.json-sep         { background: white }
.json-ell         { color: blue }  /* ellipses are linky */

/* Collapse inner blocks except on roll-over. */
                            .json-int { display: none }
.json-ext.json-expanded   > .json-int,
.json-ext.json-nocollapse > .json-int { display: inline }
.json-ext.json-nocollapse > .json-ell { display: none }
.json-ext.json-expanded   > .json-ell { color: transparent }

#experiment-progress-counter:empty { display: none }
#experiment-progress-counter {
  width: 25em;
  display: block;
  list-style-type: none;
  -webkit-padding-start: 0;
}
div #experiment-progress-counter:empty {
  border-width: 0px solid black;
  padding: 0 0 0 0;
}
div #experiment-progress-counter {
  border:1px solid black;
  padding: 0 0 2px 2px;
}
#experiment-progress-counter li {
  display: block;
  border: 1px solid black;
  padding: 2px;
  margin-top: 2px;
  height: 1em;
  background: #ddf;
  white-space: nowrap;
  font-size:8pt;
}
#experiment-iframes iframe {
  visibility:hidden;
  width:40em;
  height:1em;
}
em { color: #fff; font-weight: bold; background: #800; border: 1px solid #800; padding: 1px }
</style>
</head>
<body>
<p>
This page tries to exhaustively combine tags for all pairings of HTML elements
to answer the following questions about how HTML browsers parse tag soup:</p>
<ul>
  <li><a href="#nests-in-body">Which elements can appear directly in the body of an HTML document?</ad></li>
  <li><a href="#can-contain">Which elements can nest directly in which other elements?</a></li>
  <li><a href="#text-content-model">Which elements can contain text content, comments, entities?</a></li>
  <li><a href="#containment-stack-json">Which elements can be introduced between the body and an element
      to allow it to nest properly?</a></li>
  <li><a href="#implied-elements">Which elements are implied by which tags?</a></li>
  <li><a href="#explicit-closers">Which open tags close which other elements?</a></li>
  <li><a href="#closed-by-close">Which close tags close which elements?</a></li>
  <li><a href="#closed-by-open">Which open tags close which elements?</a></li>
  <li><a href="#resumable">Which inline tags are resumed after misnested tags?</a></li>
</ul>

<p>A <a href="#result-dump">JSON dump</a>
   of the results is available at the end once running is done.</p>

<div><ul id="experiment-progress-counter"></ul></div>

<p>A few query parameters affect the behavior of this page:</p>
<ul>
  <li><a href="?rerun"><tt><span class="basename"></span>?rerun</tt></a> &mdash;
      <em style="font-size:66%">&iexcl;VERY SLOW!</em>
      Rerun experiments on the browser intead of using the canned results from Chrome.
  <li><a href="?rerun&shortlist"><tt><span class="basename"></span>?rerun&amp;shortlist</tt></a> &mdash;
      Rerun experiments on the browser instead of using the canned results from Chrome,
      but with a short list of elements instead of the full 128+ HTML elements
      which speeds debugging.</li>
  <li><a href="?"><tt><span class="basename"></span>?</tt></a> &mdash;
      Quick browsing of canned results from Chrome.</li>
</ul>
<script>(function () {
  var basename = location.pathname.replace(/^[\s\S]*\//, '');
  function toCss(s) {
    return ('\x22'
        + s.replace(/[^\w\-.]/g, function (c) {
                      return '\\' + c.charCodeAt(0).toString(16) + ' ';
                    })
        + '\x22');
  }
  document.write('<style>.basename:after { content: ' + toCss(basename) + ' }<\/style>');
}());</script>



<!-- Contains iframes that are used to parse HTML since innerHTML parsing differs
     from regular parsing in many respects. -->
<div id="experiment-iframes"></div>

<h2 id="nests-in-body">Nests in body</h2>
<p>Does a tag <tt>&lt;X&gt;</tt> directly inside
 <tt>&lt;body&gt;&hellip;&lt;/body&gt;</tt> parse to an element named X
 directly inside the document body?</p>
<pre id="nests-in-body-json" class="json"></pre>
<script>
var canAppearInBody = getOwn(cannedData, 'canAppearInBody') || new Promise();
(function () {
  // Generates HTML for the experiment.
  function nestInBody(elementName) {
    return '<' + elementName + '></' + elementName + '>';
  }
  // Examines the resulting body to fold a single experiment into the result.
  function isNestedInBody(elementName, body, result) {
    result[elementName] = !!(
      body.firstChild && body.firstChild.nodeName.toLowerCase() === elementName
    );
    return result;
  }
  // When the experiment is finished, replace the promise so that we can
  // kick off experiments that depend on the result of this experiment.
  function finish(result) {
    var toSatisfy = canAppearInBody;
    if (toSatisfy instanceof Promise) {
      canAppearInBody = result;
      toSatisfy.satisfy();
    }
    displayJson(result, document.getElementById('nests-in-body-json'))
  }
  if (canAppearInBody instanceof Promise) {
    runExperiment(nestInBody, isNestedInBody, newBlankObject(), finish);
  } else {
    finish(canAppearInBody);
  }
}());
</script>

<h2 id="can-contain">Containment</h2>
<p>For each element, what elements can contain it?</p>
<p>E.g., <code>canAppearIn['x'].indexOf('y') >= 0</code> when
<code>&lt;x&gt;&lt;y&gt;&lt;/y&gt;&lt;/x&gt;</code> parses to
an element <tt>x</tt> that contains an element <tt>y</tt> when embedded
in an element that can contain <code>&lt;x&gt;</code>.</p>
<h3>Can Contain</h3>
<pre class="json" id="can-contain-json"></pre>
<h3>Can Appear In</h3>
<pre class="json" id="can-appear-in-json"></pre>
<h3>Containment stack</h3>
<pre class="json" id="containment-stack-json"></pre>
<script>
// We use promises to allow experiment chaining where one
// experiment depends on the results of another.

var canContain = getOwn(cannedData, 'canContain') || new Promise();
var canAppearIn = getOwn(cannedData, 'canAppearIn') || new Promise();
// For a given element name, give a stack of elements that can
// be validly embedded in body that have the element at the top.
var containmentStackFor = new Promise();

// HTML for the elements in the with the body HTML inside the
// top-most element.
function tagStackToHtml(stack, body) {
  var stackReverse = stack.slice();
  stackReverse.reverse();
  return (
    '<' + stack.join('><') + '>'
    + body
    + '</' + stackReverse.join('></') + '>'
  );
}

(function () {
  var nNeededLast = Infinity;

  // We need a function that tells us which elements we need to have on the
  // open element stack so that we can get the outer element on the stack to
  // test whether an inner tag leads to an inner element inside it.
  // For example, to test whether an <a> tag nestes properly in a <td>, we
  // need to construct <table><tbody><tr><td><a>.
  //
  // Knowing what needs to be on the open element stack for <td> requires
  // knowing what needs to be on the open element stack for <tr>.
  function containmentStackMaker(canAppearIn) {
    var memoTable = newBlankObject();
    return function (elementName, opt_exclusions) {
      if (elementName == 'body') {
        // The experiment framework passes the body element so there's no
        // need for an explicit body tag on the stack.
        return [];
      }
      var memoKey = opt_exclusions
          ? elementName + ' ' + opt_exclusions.join(' / ') : elementName;

      if (getOwn(canAppearInBody, elementName)) { return [elementName]; }
      var prior = getOwn(memoKey, elementName, void 0);
      if (prior !== void 0) { return prior ? prior.slice() : null; }
      var empty = [];

      function end(e) {
        return getOwn(canAppearInBody, e, false);
      }
      function eq (e, f) { return e === f; }
      function neighbors(e) {
        var neighbors = getOwn(canAppearIn, e, empty);
        if (opt_exclusions) {
          var exclusions = makeSet(opt_exclusions);
          var included = null;
          for (var i = 0, n = neighbors.length; i < n; ++i) {
            var neighbor = neighbors[i];
            if (inSet(exclusions, neighbor)) {
              if (!included) { included = neighbors.slice(0, i); }
            } else if (included) {
              included.push(neighbor);
            }
          }
          if (included) { neighbors = included; }
        }
        return neighbors;
      }
      var result = breadthFirstSearch(elementName, end, eq, neighbors) || null;
      memoTable[memoKey] = result;
      return result ? result.slice() : null;
    };
  }

  function run(result) {

    function makeContainerHtmlString(outer, inner) {
      if (neededSet[outer] !== neededSet) { return null; }
      // We try to assemble a stack of elements that can contain outer before
      // checking whether it can contain inner.
      // If we cannot, we punt so that we can retry later after we've fleshed
      // out more of canAppearIn.
      var stack = containmentStack(outer);
      if (!stack) { return null; }
      stack.push(inner);
      return tagStackToHtml(stack, '');
    }

    function checkCanContain(outer, inner, body, canContain) {
      var outerEls = outer == 'body'
          ? [body] : body.getElementsByTagName(outer);
      if (outerEls.length) {
        var containees = getOwn(canContain, outer) || [];
        canContain[outer] = containees;
        var outerEl = outerEls[0];
        var firstChild = outerEl.firstChild;
        if (((firstChild && firstChild.nodeName.toLowerCase() === inner)
             || outerEl.getElementsByTagName(inner).length)
            && containees.indexOf(inner) < 0) {
          containees.push(inner);
        }
      }
      return canContain;
    }

    var elementNamesNeeded = [];
    for (var i = 0, n = elementNames.length; i < n; ++i) {
      var elementName = elementNames[i];
      if (!Object.hasOwnProperty.call(result, elementName)) {
        elementNamesNeeded.push(elementName);
      }
    }
    console.log('nNeededLast=%s, nNeeded=%d, result=%o',
                nNeededLast, elementNamesNeeded.length, result);
    if (elementNamesNeeded.length === nNeededLast) {
      // We made no progress last run.
      console.log('cannot place ' + elementNamesNeeded);
      elementNamesNeeded.length = 0;
    }

    var containmentStack = containmentStackMaker(reverseMultiMap(result));

    var neededSet = newBlankObject();
    for (var i = elementNamesNeeded.length; --i >= 0;) {
      neededSet[elementNamesNeeded[i]] = neededSet;
    }

    if (elementNamesNeeded.length) {
      nNeededLast = elementNamesNeeded.length;
      return runExperiment(
          makeContainerHtmlString, checkCanContain, result, run,
          elementNames);
    } else {
      finishCanContain(result);
      return result;
    }
  }

  function finishCanContain(result) {
    var toSatisfy = canContain;
    if (toSatisfy instanceof Promise) {
      canContain = sortedMultiMap(result);
      // A limitation of our experimental framework is that it passes the body
      // of the document to the result function which means we can't really
      // test the relationship between the HTML and HEAD elements, for example.
      //
      // To work around that limitation, we hard code some canContain
      // relationships here.
      canContain['html'] = ['body', 'frameset', 'head'];
      canContain['head'] = [
          'base', 'command', 'link', 'meta', 'noscript', 'script', 'style',
          'title'];
      canContain['frameset'] = ['frame', 'frameset', 'noframes'];
      // TODO: do the same for the text content model.
      toSatisfy.satisfy();
    }
    displayJson(canContain, document.getElementById('can-contain-json'));
  }

  if (canContain instanceof Promise) {
    when(function () { run(newBlankObject()); }, canAppearInBody);
  } else {
    finishCanContain(canContain);
  }

  function reverseMap() {
    var toSatisfy = canAppearIn;
    if (toSatisfy instanceof Promise) {
      canAppearIn = sortedMultiMap(reverseMultiMap(canContain));
      toSatisfy.satisfy();
    }
    displayJson(canAppearIn, document.getElementById('can-appear-in-json'));
    toSatisfy = containmentStackFor;

    containmentStackFor = containmentStackMaker(canAppearIn);
    toSatisfy.satisfy();
  }

  when(function () { reverseMap(); }, canContain);

  function mapStacks() {
    var containmentStackMap = newBlankObject();
    for (var i = 0, n = elementNames.length; i < n; ++i) {
      var elementName = elementNames[i];
      var stack = containmentStackFor(elementName);
      if (stack && stack.length) { --stack.length; }
      containmentStackMap[elementName] = stack;
    }
    displayJson(containmentStackMap,
                document.getElementById('containment-stack-json'));
  }
  when(mapStacks, containmentStackFor);
}());
</script>

<h2 id="text-content-model">Text and comment content</h2>

<p>Tests which elements can contain a non-whitespace text node and which can
contain comments or other non-text elements as a result of parsing.</p>
<p><code>textContentModel['x'].text</code> is true when
<code>&lt;x&gt;text&lt;/x&gt;</code> parses to an X element containing
a text node.</p>
<p><code>textContentModel['x'].comments</code> is true when
<code>&lt;x&gt;&lt;!--comment--&gt;&lt;/x&gt;</code> parses to an X element
containing a comment node.</p>
<p><code>textContentModel['x'].xml</code> is true when
<code>&lt;x&gt;&amp;amp;&lt;![[CDATA&amp;amp;]]>&lt;/x&gt;</code> parses to an X
element that contains text nodes that normalize to <code>&&amp;</code>.</p>
<p><code>textContentModel['x'].raw</code> is true when
<code>&lt;x&gt;&lt;br&gt;&lt;/x&gt;</code> parses to an X element
containing a text node.</p>
<p><code>textContentModel['x'].entities</code> is true when
<code>&lt;x&gt;&amp;amp;;&lt;/x&gt;</code> parses to an X element
containing a text node <tt>&amp;amp;</tt>.</p>
<pre class="json" id="text-content-model-json"></pre>
<script>
var textContentModel = getOwn(cannedData, 'textContentModel') || new Promise();
(function () {
  function run() {
    function makeHtmlStringWithText(elementName) {
      var stack = containmentStackFor(elementName);
      if (stack == null) { return null; }
      return tagStackToHtml(
          stack, '/*1&amp;2<![CDATA[&amp;]]>3<!---->4<br>5*/');
    }
    function checkText(elementName, body, result) {
      var el = body.getElementsByTagName(elementName)[0];
      var text = innerTextOf(el);
      var model = newBlankObject();
      if (elementName === 'body') {  // Special case.
        text = '/*1&2345*/';
      }
      switch (text) {
        case '':
          if (elementContainsComment(el)) { model.comments = true; }
          break;
        case '/*1&2345*/':  // CDATA section treated as "bogus comment"
          model.text = model.entities = model.comments = true;
          break;
        case '/*1&2&amp;345*/':  // CDATA section treated as per XML
          model.text = model.entities = model.xml = model.comments = true;
          break;
        case '/*1&2<![CDATA[&]]>3<!---->4<br>5*/':  // '<' is raw
          model.text = model.entities = model.raw = true;
          break;
        case '/*1&amp;2<![CDATA[&amp;]]>3<!---->4<br>5*/':  // '<' and '&' raw
          model.text = model.raw = true;
          break;
        case '/*1&amp;2<![CDATA[&amp;]]>3<!---->4<br>5*/</' + elementName + '>':
          // </plaintext> does not close <plaintext>
          model.text = model.raw = model.unended = true;
          break;
        default:
          console.log('unexpected text `%s` in %s', text, elementName);
      }
      if (model.text) {
        if (elementName != 'script' && elementName != 'style') {
          model.plain_text = true;
        }
      }
      result[elementName] = sortedMultiMap(model);
      return result;
    }

    runExperiment(makeHtmlStringWithText, checkText, newBlankObject(), finish);
  }

  function finish(result) {
    var toSatisfy = textContentModel;
    if (toSatisfy instanceof Promise) {
      textContentModel = sortedMultiMap(result);
      toSatisfy.satisfy();
    }
    displayJson(textContentModel,
                document.getElementById('text-content-model-json'));
  }

  if (textContentModel instanceof Promise) {
    when(run, containmentStackFor);
  } else {
    finish(textContentModel);
  }
}());
</script>

<h2 id="implied-elements">Implied Elements</h2>
<p>Which elements are implicitly created when one element is
  nested in another?</p>

<p><code>impliedElements['x']['z'] == ['y']</code> when parsing
  <code>&lt;x&gt;&lt;z&gt;&lt;/z&gt;&lt;/x&gt;</code> produces
  a tree equivalent to <code>&lt;x&gt;&lt;y&gt;&lt;z&gt;&lt;/z&gt;&lt;/y&gt;&lt;/x&gt;</code>

<pre class="json" id="implied-elements-json"></pre>
<script>
var impliedElements = getOwn(cannedData, 'impliedElements') || new Promise();
(function () {
  // Generates HTML for the experiment.
  function nestElements(elementNameA, elementNameB) {
    if (elementNameA === 'html') { return ''; }  // Everything opens body.
    return (
        '<' + elementNameA + '>'
        + '<' + elementNameB + ' id="inner-implied-el">'
        + '</' + elementNameB + '>'
        + '</' + elementNameA + '>');
  }
  // Examines the resulting body to fold a single experiment into the result.
  function computeImpliedElements(elementNameA, elementNameB, body, result) {
    var inner = body.querySelector(elementNameB + "[id='inner-implied-el']");
    if (inner) {
      var ancestors = [];
      for (var el = inner.parentNode;
           el != null && el.nodeType == Node.ELEMENT_NODE;
           el = el.parentNode) {
        var lcName = el.nodeName.toLowerCase();
        if (lcName == elementNameA) {
          if (ancestors.length) {
            if (!Object.hasOwnProperty.call(result, elementNameA)) {
              result[elementNameA] = newBlankObject();
            }
            ancestors.reverse();
            result[elementNameA][elementNameB] = ancestors;
            break;
          }
        } else {
          ancestors.push(lcName);
        }
      }
    }
    return result;
  }
  // When the experiment is finished, replace the promise so that we can
  // kick off experiments that depend on the result of this experiment.
  function finish(result) {
    var toSatisfy = impliedElements;
    if (toSatisfy instanceof Promise) {
      impliedElements = result;
      toSatisfy.satisfy();
    }
    displayJson(result, document.getElementById('implied-elements-json'))
  }
  if (impliedElements instanceof Promise) {
    runExperiment(
        nestElements, computeImpliedElements, newBlankObject(), finish);
  } else {
    finish(impliedElements);
  }
}());
</script>


<h2>Tag Closers</h2>
<h3 id="explicit-closers">Explicit closers</h3>
<p>Are there any close tags besides the tag name itself that close the tag?</p>
<pre class="json" id="explicit-closers-json"></pre>
<script>
var explicitClosers = getOwn(cannedData, 'explicitClosers') || new Promise();
(function () {
  function run() {
    var contentForElement = newBlankObject();
    function nestableContent(openTag, excludedTag) {
      var content = getOwn(contentForElement, openTag);
      if (content === undefined) {
        var tcm = getOwn(textContentModel, openTag);
        if (tcm && tcm.text) {
          content = '#text';
        } else {
          content = getOwn(canContain, openTag, null);
        }
        contentForElement[openTag] = content;
      }
      // arrays are element names
      if (content instanceof Array) {
        for (var i = 0, n = content.length; i < n; ++i) {
          var tag = content[i];
          if (tag === openTag || tag === excludedTag) { continue; }
          return tag;
        }
        return null;
      } else {
        return content;
      }
    }

    function makeHtmlString(openTag, closeTag) {
      if (openTag === closeTag) { return null; }
      var stack = containmentStackFor(openTag, [closeTag]);
      if (stack == null) { return null; }
      if (closeTag === 'body' || closeTag === 'html') {
        return null;
      }
      var content = nestableContent(openTag, closeTag);
      if (content === null) { return null; }
      if (content !== '#text') {
        content = '<' + content + '></' + content + '>';
      }
      return tagStackToHtml(stack, '</' + closeTag + '>' + content);
    }

    function check(openTag, closeTag, body, result) {
      var content = nestableContent(openTag, closeTag);
      var element = body.getElementsByTagName(openTag)[0];
      if (element) {
        var closed = (content === '#text')
          ? innerTextOf(element) === ''
          : !element.getElementsByTagName(content).length;
        if (closed) {
          var closeTags = getOwn(result, openTag) || [];
          closeTags.push(closeTag);
          result[openTag] = closeTags;
        }
      }
      return result;
    }

    runExperiment(makeHtmlString, check, newBlankObject(), finish);
  }

  function finish(result) {
    var toSatisfy = explicitClosers;
    if (toSatisfy instanceof Promise) {
      explicitClosers = sortedMultiMap(result);
      toSatisfy.satisfy();
    }
    displayJson(explicitClosers,
                document.getElementById('explicit-closers-json'));
  }

  if (explicitClosers instanceof Promise) {
    when(run, containmentStackFor, textContentModel);
  } else {
    finish(explicitClosers);
  }
}());
</script>

<h3 id="closed-by-open">Open tags close which elements</h3>
<p>Which open tags close the element when embedded between it and content it
   could otherwise contain?</p>
<p>Which <code>C</code> close <code>T</code> in
   <code>&lt;T&gt;&lt;C&gt;X&lt;/C&gt;&lt;/T&gt;</code>
   leading to X being a sibling of the element T instead of its child as it would
   be if parsed as <code>&lt;T&gt;X&lt;/T&gt;</code>.
<pre class="json" id="closed-by-open-json"></pre>
<script>
var closedOnOpen = getOwn(cannedData, 'closedOnOpen') || new Promise();
(function () {
  function run() {
    function makeHtmlString(outer, inner) {
      if (textContentModel[outer] && textContentModel[outer].comments
          && !(textContentModel[inner] && textContentModel[inner].unended)) {
        var stack = containmentStackFor(outer, [inner]);
        if (stack) {
          // <outer><inner></inner><!--After inner --></outer>
          return tagStackToHtml(
              stack, '<' + inner + '></' + inner + '><!-- After inner -->');
        }
      }
      return null;
    }

    function check(outer, inner, body, result) {
      var outerEl = body.getElementsByTagName(outer)[0];
      var hasComment = elementContainsComment(outerEl);
      var closers = getOwn(result, outer) || [];
      if (!hasComment) {
        closers.push(inner);
      }
      result[outer] = closers;
      return result;
    }

    runExperiment(makeHtmlString, check, newBlankObject(), finish);
  }

  function finish(result) {
    var toSatisfy = closedOnOpen;
    if (toSatisfy instanceof Promise) {
      closedOnOpen = sortedMultiMap(result);
      toSatisfy.satisfy();
    }
    displayJson(closedOnOpen,
                document.getElementById('closed-by-open-json'));
  }

  if (closedOnOpen instanceof Promise) {
    when(run, containmentStackFor, textContentModel, canContain);
  } else {
    finish(closedOnOpen);
  }
}());
</script>


<h3 id="closed-by-close">Close tags close which elements</h3>
<p>Which <code>C</code> close <code>T</code> in
   <code>&lt;C&gt;&lt;T&gt;&lt;/C&gt;X&lt;/T&gt;</code>
   leading to X being a sibling of the element T instead of its child as it
   would be if parsed as <code>&lt;T&gt;X&lt;/T&gt;</code>.
<pre class="json" id="closed-by-close-json"></pre>
<script>
var closedOnClose = getOwn(cannedData, 'closedOnClose') || new Promise();
(function () {
  function run() {
    function makeHtmlString(outer, inner) {
      var outerTc = textContentModel[outer];
      var innerTc = textContentModel[inner];
      if (outerTc && innerTc && outerTc.comments && innerTc.comments) {
        var stack = containmentStackFor(outer, [inner]);
        if (stack && stack.length) {
          --stack.length;  // strip outer.
          // <outer><inner></outer><!--X--></inner>
          return tagStackToHtml(
              stack,
              '<' + outer + '><' + inner + '>'
              + '</' + outer + '><!--X--></' + inner + '>');
        }
      }
      return null;
    }

    function check(outer, inner, body, result) {
      var innerEl = body.getElementsByTagName(inner)[0];
      var closers = getOwn(result, inner) || [];
      if (!elementContainsComment(innerEl)) {
        closers.push(outer);
      }
      result[inner] = closers;
      return result;
    }

    runExperiment(makeHtmlString, check, newBlankObject(), finish);
  }

  function finish(result) {
    var toSatisfy = closedOnClose;
    if (toSatisfy instanceof Promise) {
      closedOnClose = sortedMultiMap(result);
      toSatisfy.satisfy();
    }
    displayJson(closedOnClose,
                document.getElementById('closed-by-close-json'));
  }

  if (closedOnClose instanceof Promise) {
    when(run, containmentStackFor, textContentModel, canContain);
  } else {
    finish(closedOnClose);
  }
}());
</script>

<h2 id="resumable">Resumable</h2>
<p>If misnested with an inline tag, does the tag resume after the misnesting.
<code>&lt;x&gt;</code> is resumable when
<code>&lt;i&gt;&lt;x&gt;foo&lt;/i&gt;bar&lt;/x&gt;</code>
</p>
<pre id="resumable-json" class="json"></pre>
<script>
var resumable = getOwn(cannedData, 'resumable') || new Promise();
(function () {
  // Generates HTML for the experiment.
  function misnest(elementName) {
    var inline = elementName === 'i' ? 'b' : 'i';
    return ('<' + inline + '><' + elementName + '>before</'
        + inline + '>after</' + elementName + '>');
  }
  // Examines the resulting body to fold a single experiment into the result.
  function isResumable(elementName, body, result) {
    //result[elementName] = false;  // until proven otherwise
    var els = body.getElementsByTagName(elementName);
    for (var i = 0, n = els.length; i < n; ++i) {
      if ('after' == els[i].textContent) {
        result[elementName] = true;
        break;
      }
    }
    return result;
  }
  // When the experiment is finished, replace the promise so that we can
  // kick off experiments that depend on the result of this experiment.
  function finish(result) {
    var toSatisfy = resumable;
    if (toSatisfy instanceof Promise) {
      resumable = result;
      toSatisfy.satisfy();
    }
    displayJson(result, document.getElementById('resumable-json'))
  }
  if (resumable instanceof Promise) {
    runExperiment(misnest, isResumable, newBlankObject(), finish);
  } else {
    finish(resumable);
  }
}());
</script>

<h2 id="result-dump">JSON Dump</h2>
<p id="working"><em>working</em></p>
<script>
var fullJson = {
  "canAppearIn":         canAppearIn,
  "canAppearInBody":     canAppearInBody,
  "canContain":          canContain,
  "closedOnClose":       closedOnClose,
  "closedOnOpen":        closedOnOpen,
  "containmentStackFor": containmentStackFor,
  "elementNames":        elementNames,
  "explicitClosers":     explicitClosers,
  "impliedElements":     impliedElements,
  "resumable":           resumable,
  "textContentModel":    textContentModel
};

(function () {

  function run() {
    for (var k in fullJson) {
      if (fullJson.hasOwnProperty(k)) {
        fullJson[k] = window[k];
      }
    }

    var textarea = document.createElement('textarea');
    textarea.setAttribute('cols', '80');
    textarea.setAttribute('rows', '20');
    textarea.setAttribute('readonly', 'readonly');
    textarea.onclick = function () { textarea.select(); };
    textarea.value = JSON.stringify(fullJson);
    var resultDumpHeader = document.getElementById('result-dump');
    resultDumpHeader.parentNode.insertBefore(
        textarea, resultDumpHeader.nextSibling);
    var workingNote = document.getElementById('working');
    workingNote.parentNode.removeChild(workingNote);
  }

  var whenArgs = [run];
  for (var k in fullJson) {
    if (fullJson.hasOwnProperty(k)) {
      whenArgs.push(fullJson[k]);
    }
  }

  when.apply(null, whenArgs);
}());
</script>

</body>
</html>