summaryrefslogtreecommitdiffstats
path: root/parser/html/nsHtml5Highlighter.cpp
blob: 92e4b03738c6db43a7e18f580a04c951db932ec1 (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
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
/* 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 "nsHtml5Highlighter.h"
#include "nsDebug.h"
#include "nsHtml5Tokenizer.h"
#include "nsHtml5AttributeName.h"
#include "nsString.h"
#include "nsThreadUtils.h"
#include "nsHtml5ViewSourceUtils.h"

#include "mozilla/Attributes.h"
#include "mozilla/Preferences.h"

using namespace mozilla;

// The old code had a limit of 16 tokens. 1300 is a number picked my measuring
// the size of 16 tokens on cnn.com.
#define NS_HTML5_HIGHLIGHTER_PRE_BREAK_THRESHOLD 1300

char16_t nsHtml5Highlighter::sComment[] =
  { 'c', 'o', 'm', 'm', 'e', 'n', 't', 0 };

char16_t nsHtml5Highlighter::sCdata[] =
  { 'c', 'd', 'a', 't', 'a', 0 };

char16_t nsHtml5Highlighter::sEntity[] =
  { 'e', 'n', 't', 'i', 't', 'y', 0 };

char16_t nsHtml5Highlighter::sEndTag[] =
  { 'e', 'n', 'd', '-', 't', 'a', 'g', 0 };

char16_t nsHtml5Highlighter::sStartTag[] =
  { 's', 't', 'a', 'r', 't', '-', 't', 'a', 'g', 0 };

char16_t nsHtml5Highlighter::sAttributeName[] =
  { 'a', 't', 't', 'r', 'i', 'b', 'u', 't', 'e', '-', 'n', 'a', 'm', 'e', 0 };

char16_t nsHtml5Highlighter::sAttributeValue[] =
  { 'a', 't', 't', 'r', 'i', 'b', 'u', 't', 'e', '-',
    'v', 'a', 'l', 'u', 'e', 0 };

char16_t nsHtml5Highlighter::sDoctype[] =
  { 'd', 'o', 'c', 't', 'y', 'p', 'e', 0 };

char16_t nsHtml5Highlighter::sPi[] =
  { 'p', 'i', 0 };

nsHtml5Highlighter::nsHtml5Highlighter(nsAHtml5TreeOpSink* aOpSink)
 : mState(nsHtml5Tokenizer::DATA)
 , mCStart(INT32_MAX)
 , mPos(0)
 , mLineNumber(1)
 , mInlinesOpen(0)
 , mInCharacters(false)
 , mBuffer(nullptr)
 , mOpSink(aOpSink)
 , mCurrentRun(nullptr)
 , mAmpersand(nullptr)
 , mSlash(nullptr)
 , mHandles(MakeUnique<nsIContent*[]>(NS_HTML5_HIGHLIGHTER_HANDLE_ARRAY_LENGTH))
 , mHandlesUsed(0)
 , mSeenBase(false)
{
  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
}

nsHtml5Highlighter::~nsHtml5Highlighter()
{
  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
}

void
nsHtml5Highlighter::Start(const nsAutoString& aTitle)
{
  // Doctype
  mOpQueue.AppendElement()->Init(nsGkAtoms::html, EmptyString(), EmptyString());

  mOpQueue.AppendElement()->Init(STANDARDS_MODE);

  nsIContent** root = CreateElement(nsHtml5Atoms::html, nullptr, nullptr);
  mOpQueue.AppendElement()->Init(eTreeOpAppendToDocument, root);
  mStack.AppendElement(root);

  Push(nsGkAtoms::head, nullptr);

  Push(nsGkAtoms::title, nullptr);
  // XUL will add the "Source of: " prefix.
  uint32_t length = aTitle.Length();
  if (length > INT32_MAX) {
    length = INT32_MAX;
  }
  AppendCharacters(aTitle.BeginReading(), 0, (int32_t)length);
  Pop(); // title

  Push(nsGkAtoms::link, nsHtml5ViewSourceUtils::NewLinkAttributes());

  mOpQueue.AppendElement()->Init(eTreeOpUpdateStyleSheet, CurrentNode());

  Pop(); // link

  Pop(); // head

  Push(nsGkAtoms::body, nsHtml5ViewSourceUtils::NewBodyAttributes());

  nsHtml5HtmlAttributes* preAttrs = new nsHtml5HtmlAttributes(0);
  nsHtml5String preId = nsHtml5Portability::newStringFromLiteral("line1");
  preAttrs->addAttribute(nsHtml5AttributeName::ATTR_ID, preId, -1);
  Push(nsGkAtoms::pre, preAttrs);

  StartCharacters();

  mOpQueue.AppendElement()->Init(eTreeOpStartLayout);
}

int32_t
nsHtml5Highlighter::Transition(int32_t aState, bool aReconsume, int32_t aPos)
{
  mPos = aPos;
  switch (mState) {
    case nsHtml5Tokenizer::SCRIPT_DATA:
    case nsHtml5Tokenizer::RAWTEXT:
    case nsHtml5Tokenizer::RCDATA:
    case nsHtml5Tokenizer::DATA:
      // We can transition on < and on &. Either way, we don't yet know the
      // role of the token, so open a span without class.
      if (aState == nsHtml5Tokenizer::CONSUME_CHARACTER_REFERENCE) {
        StartSpan();
        // Start another span for highlighting the ampersand
        StartSpan();
        mAmpersand = CurrentNode();
      } else {
        EndCharactersAndStartMarkupRun();
      }
      break;
    case nsHtml5Tokenizer::TAG_OPEN:
      switch (aState) {
        case nsHtml5Tokenizer::TAG_NAME:
          StartSpan(sStartTag);
          break;
        case nsHtml5Tokenizer::DATA:
          FinishTag(); // DATA
          break;
        case nsHtml5Tokenizer::PROCESSING_INSTRUCTION:
          AddClass(sPi);
          break;
      }
      break;
    case nsHtml5Tokenizer::TAG_NAME:
      switch (aState) {
        case nsHtml5Tokenizer::BEFORE_ATTRIBUTE_NAME:
          EndSpanOrA(); // nsHtml5Tokenizer::TAG_NAME
          break;
        case nsHtml5Tokenizer::SELF_CLOSING_START_TAG:
          EndSpanOrA(); // nsHtml5Tokenizer::TAG_NAME
          StartSpan(); // for highlighting the slash
          mSlash = CurrentNode();
          break;
        default:
          FinishTag();
          break;
      }
      break;
    case nsHtml5Tokenizer::BEFORE_ATTRIBUTE_NAME:
      switch (aState) {
        case nsHtml5Tokenizer::ATTRIBUTE_NAME:
          StartSpan(sAttributeName);
          break;
        case nsHtml5Tokenizer::SELF_CLOSING_START_TAG:
          StartSpan(); // for highlighting the slash
          mSlash = CurrentNode();
          break;
        default:
          FinishTag();
          break;
      }
      break;
    case nsHtml5Tokenizer::ATTRIBUTE_NAME:
      switch (aState) {
        case nsHtml5Tokenizer::AFTER_ATTRIBUTE_NAME:
        case nsHtml5Tokenizer::BEFORE_ATTRIBUTE_VALUE:
          EndSpanOrA(); // nsHtml5Tokenizer::BEFORE_ATTRIBUTE_NAME
          break;
        case nsHtml5Tokenizer::SELF_CLOSING_START_TAG:
          EndSpanOrA(); // nsHtml5Tokenizer::BEFORE_ATTRIBUTE_NAME
          StartSpan(); // for highlighting the slash
          mSlash = CurrentNode();
          break;
        default:
          FinishTag();
          break;
      }
      break;
    case nsHtml5Tokenizer::BEFORE_ATTRIBUTE_VALUE:
      switch (aState) {
        case nsHtml5Tokenizer::ATTRIBUTE_VALUE_DOUBLE_QUOTED:
        case nsHtml5Tokenizer::ATTRIBUTE_VALUE_SINGLE_QUOTED:
          FlushCurrent();
          StartA();
          break;
        case nsHtml5Tokenizer::ATTRIBUTE_VALUE_UNQUOTED:
          StartA();
          break;
        default:
          FinishTag();
          break;
      }
      break;
    case nsHtml5Tokenizer::ATTRIBUTE_VALUE_DOUBLE_QUOTED:
    case nsHtml5Tokenizer::ATTRIBUTE_VALUE_SINGLE_QUOTED:
      switch (aState) {
        case nsHtml5Tokenizer::AFTER_ATTRIBUTE_VALUE_QUOTED:
          EndSpanOrA();
          break;
        case nsHtml5Tokenizer::CONSUME_CHARACTER_REFERENCE:
          StartSpan();
          StartSpan(); // for ampersand itself
          mAmpersand = CurrentNode();
          break;
        default:
          NS_NOTREACHED("Impossible transition.");
          break;
      }
      break;
    case nsHtml5Tokenizer::AFTER_ATTRIBUTE_VALUE_QUOTED:
      switch (aState) {
        case nsHtml5Tokenizer::BEFORE_ATTRIBUTE_NAME:
          break;
        case nsHtml5Tokenizer::SELF_CLOSING_START_TAG:
          StartSpan(); // for highlighting the slash
          mSlash = CurrentNode();
          break;
        default:
          FinishTag();
          break;
      }
      break;
    case nsHtml5Tokenizer::SELF_CLOSING_START_TAG:
      EndSpanOrA(); // end the slash highlight
      switch (aState) {
        case nsHtml5Tokenizer::BEFORE_ATTRIBUTE_NAME:
          break;
        default:
          FinishTag();
          break;
      }
      break;
    case nsHtml5Tokenizer::ATTRIBUTE_VALUE_UNQUOTED:
      switch (aState) {
        case nsHtml5Tokenizer::BEFORE_ATTRIBUTE_NAME:
          EndSpanOrA();
          break;
        case nsHtml5Tokenizer::CONSUME_CHARACTER_REFERENCE:
          StartSpan();
          StartSpan(); // for ampersand itself
          mAmpersand = CurrentNode();
          break;
        default:
          FinishTag();
          break;
      }
      break;
    case nsHtml5Tokenizer::AFTER_ATTRIBUTE_NAME:
      switch (aState) {
        case nsHtml5Tokenizer::SELF_CLOSING_START_TAG:
          StartSpan(); // for highlighting the slash
          mSlash = CurrentNode();
          break;
        case nsHtml5Tokenizer::BEFORE_ATTRIBUTE_VALUE:
          break;
        case nsHtml5Tokenizer::ATTRIBUTE_NAME:
          StartSpan(sAttributeName);
          break;
        default:
          FinishTag();
          break;
      }
      break;
      // most comment states are omitted, because they don't matter to
      // highlighting
    case nsHtml5Tokenizer::COMMENT_START:
    case nsHtml5Tokenizer::COMMENT_END:
    case nsHtml5Tokenizer::COMMENT_END_BANG:
    case nsHtml5Tokenizer::COMMENT_START_DASH:
    case nsHtml5Tokenizer::BOGUS_COMMENT:
    case nsHtml5Tokenizer::BOGUS_COMMENT_HYPHEN:
      if (aState == nsHtml5Tokenizer::DATA) {
        AddClass(sComment);
        FinishTag();
      }
      break;
      // most cdata states are omitted, because they don't matter to
      // highlighting
    case nsHtml5Tokenizer::CDATA_RSQB_RSQB:
      if (aState == nsHtml5Tokenizer::DATA) {
        AddClass(sCdata);
        FinishTag();
      }
      break;
    case nsHtml5Tokenizer::CONSUME_CHARACTER_REFERENCE:
      EndSpanOrA(); // the span for the ampersand
      switch (aState) {
        case nsHtml5Tokenizer::CONSUME_NCR:
        case nsHtml5Tokenizer::CHARACTER_REFERENCE_HILO_LOOKUP:
          break;
        default:
          // not actually a character reference
          EndSpanOrA();
          break;
      }
      break;
    case nsHtml5Tokenizer::CHARACTER_REFERENCE_HILO_LOOKUP:
      if (aState == nsHtml5Tokenizer::CHARACTER_REFERENCE_TAIL) {
        break;
      }
      // not actually a character reference
      EndSpanOrA();
      break;
    case nsHtml5Tokenizer::CHARACTER_REFERENCE_TAIL:
      if (!aReconsume) {
        FlushCurrent();
      }
      EndSpanOrA();
      break;
    case nsHtml5Tokenizer::DECIMAL_NRC_LOOP:
    case nsHtml5Tokenizer::HEX_NCR_LOOP:
      switch (aState) {
        case nsHtml5Tokenizer::HANDLE_NCR_VALUE:
          AddClass(sEntity);
          FlushCurrent();
          break;
        case nsHtml5Tokenizer::HANDLE_NCR_VALUE_RECONSUME:
          AddClass(sEntity);
          break;
      }
      EndSpanOrA();
      break;
    case nsHtml5Tokenizer::CLOSE_TAG_OPEN:
      switch (aState) {
        case nsHtml5Tokenizer::DATA:
          FinishTag();
          break;
        case nsHtml5Tokenizer::TAG_NAME:
          StartSpan(sEndTag);
          break;
      }
      break;
    case nsHtml5Tokenizer::RAWTEXT_RCDATA_LESS_THAN_SIGN:
      if (aState == nsHtml5Tokenizer::NON_DATA_END_TAG_NAME) {
        FlushCurrent();
        StartSpan(); // don't know if it is "end-tag" yet :-(
        break;
      }
      EndSpanOrA();
      StartCharacters();
      break;
    case nsHtml5Tokenizer::NON_DATA_END_TAG_NAME:
      switch (aState) {
        case nsHtml5Tokenizer::BEFORE_ATTRIBUTE_NAME:
          AddClass(sEndTag);
          EndSpanOrA();
          break;
        case nsHtml5Tokenizer::SELF_CLOSING_START_TAG:
          AddClass(sEndTag);
          EndSpanOrA();
          StartSpan(); // for highlighting the slash
          mSlash = CurrentNode();
          break;
        case nsHtml5Tokenizer::DATA: // yes, as a result of emitting the token
          AddClass(sEndTag);
          FinishTag();
          break;
        default:
          FinishTag();
          break;
      }
      break;
    case nsHtml5Tokenizer::SCRIPT_DATA_LESS_THAN_SIGN:
    case nsHtml5Tokenizer::SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN:
      if (aState == nsHtml5Tokenizer::NON_DATA_END_TAG_NAME) {
        FlushCurrent();
        StartSpan(); // don't know if it is "end-tag" yet :-(
        break;
      }
      FinishTag();
      break;
    case nsHtml5Tokenizer::SCRIPT_DATA_ESCAPED_DASH_DASH:
    case nsHtml5Tokenizer::SCRIPT_DATA_ESCAPED:
    case nsHtml5Tokenizer::SCRIPT_DATA_ESCAPED_DASH:
      if (aState == nsHtml5Tokenizer::SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN) {
        EndCharactersAndStartMarkupRun();
      }
      break;
      // Lots of double escape states omitted, because they don't highlight.
      // Likewise, only doctype states that can emit the doctype are of
      // interest. Otherwise, the transition out of bogus comment deals.
    case nsHtml5Tokenizer::BEFORE_DOCTYPE_NAME:
    case nsHtml5Tokenizer::DOCTYPE_NAME:
    case nsHtml5Tokenizer::AFTER_DOCTYPE_NAME:
    case nsHtml5Tokenizer::AFTER_DOCTYPE_PUBLIC_KEYWORD:
    case nsHtml5Tokenizer::BEFORE_DOCTYPE_PUBLIC_IDENTIFIER:
    case nsHtml5Tokenizer::DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED:
    case nsHtml5Tokenizer::AFTER_DOCTYPE_PUBLIC_IDENTIFIER:
    case nsHtml5Tokenizer::BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS:
    case nsHtml5Tokenizer::DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED:
    case nsHtml5Tokenizer::AFTER_DOCTYPE_SYSTEM_IDENTIFIER:
    case nsHtml5Tokenizer::BOGUS_DOCTYPE:
    case nsHtml5Tokenizer::AFTER_DOCTYPE_SYSTEM_KEYWORD:
    case nsHtml5Tokenizer::BEFORE_DOCTYPE_SYSTEM_IDENTIFIER:
    case nsHtml5Tokenizer::DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED:
    case nsHtml5Tokenizer::DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED:
      if (aState == nsHtml5Tokenizer::DATA) {
        AddClass(sDoctype);
        FinishTag();
      }
      break;
    case nsHtml5Tokenizer::PROCESSING_INSTRUCTION_QUESTION_MARK:
      if (aState == nsHtml5Tokenizer::DATA) {
        FinishTag();
      }
      break;
    default:
      break;
  }
  mState = aState;
  return aState;
}

void
nsHtml5Highlighter::End()
{
  switch (mState) {
    case nsHtml5Tokenizer::COMMENT_END:
    case nsHtml5Tokenizer::COMMENT_END_BANG:
    case nsHtml5Tokenizer::COMMENT_START_DASH:
    case nsHtml5Tokenizer::BOGUS_COMMENT:
    case nsHtml5Tokenizer::BOGUS_COMMENT_HYPHEN:
      AddClass(sComment);
      break;
    case nsHtml5Tokenizer::CDATA_RSQB_RSQB:
      AddClass(sCdata);
      break;
    case nsHtml5Tokenizer::DECIMAL_NRC_LOOP:
    case nsHtml5Tokenizer::HEX_NCR_LOOP:
      // XXX need tokenizer help here
      break;
    case nsHtml5Tokenizer::BEFORE_DOCTYPE_NAME:
    case nsHtml5Tokenizer::DOCTYPE_NAME:
    case nsHtml5Tokenizer::AFTER_DOCTYPE_NAME:
    case nsHtml5Tokenizer::AFTER_DOCTYPE_PUBLIC_KEYWORD:
    case nsHtml5Tokenizer::BEFORE_DOCTYPE_PUBLIC_IDENTIFIER:
    case nsHtml5Tokenizer::DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED:
    case nsHtml5Tokenizer::AFTER_DOCTYPE_PUBLIC_IDENTIFIER:
    case nsHtml5Tokenizer::BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS:
    case nsHtml5Tokenizer::DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED:
    case nsHtml5Tokenizer::AFTER_DOCTYPE_SYSTEM_IDENTIFIER:
    case nsHtml5Tokenizer::BOGUS_DOCTYPE:
    case nsHtml5Tokenizer::AFTER_DOCTYPE_SYSTEM_KEYWORD:
    case nsHtml5Tokenizer::BEFORE_DOCTYPE_SYSTEM_IDENTIFIER:
    case nsHtml5Tokenizer::DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED:
    case nsHtml5Tokenizer::DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED:
      AddClass(sDoctype);
      break;
    default:
      break;
  }
  nsHtml5TreeOperation* treeOp = mOpQueue.AppendElement();
  NS_ASSERTION(treeOp, "Tree op allocation failed.");
  treeOp->Init(eTreeOpStreamEnded);
  FlushOps();
}

void
nsHtml5Highlighter::SetBuffer(nsHtml5UTF16Buffer* aBuffer)
{
  NS_PRECONDITION(!mBuffer, "Old buffer still here!");
  mBuffer = aBuffer;
  mCStart = aBuffer->getStart();
}

void
nsHtml5Highlighter::DropBuffer(int32_t aPos)
{
  NS_PRECONDITION(mBuffer, "No buffer to drop!");
  mPos = aPos;
  FlushChars();
  mBuffer = nullptr;
}

void
nsHtml5Highlighter::StartSpan()
{
  FlushChars();
  Push(nsGkAtoms::span, nullptr);
  ++mInlinesOpen;
}

void
nsHtml5Highlighter::StartSpan(const char16_t* aClass)
{
  StartSpan();
  AddClass(aClass);
}

void
nsHtml5Highlighter::EndSpanOrA()
{
  FlushChars();
  Pop();
  --mInlinesOpen;
}

void
nsHtml5Highlighter::StartCharacters()
{
  NS_PRECONDITION(!mInCharacters, "Already in characters!");
  FlushChars();
  Push(nsGkAtoms::span, nullptr);
  mCurrentRun = CurrentNode();
  mInCharacters = true;
}

void
nsHtml5Highlighter::EndCharactersAndStartMarkupRun()
{
  NS_PRECONDITION(mInCharacters, "Not in characters!");
  FlushChars();
  Pop();
  mInCharacters = false;
  // Now start markup run
  StartSpan();
  mCurrentRun = CurrentNode();
}

void
nsHtml5Highlighter::StartA()
{
  FlushChars();
  Push(nsGkAtoms::a, nullptr);
  AddClass(sAttributeValue);
  ++mInlinesOpen;
}

void
nsHtml5Highlighter::FinishTag()
{
  while (mInlinesOpen > 1) {
    EndSpanOrA();
  }
  FlushCurrent(); // >
  EndSpanOrA(); // DATA
  NS_ASSERTION(!mInlinesOpen, "mInlinesOpen got out of sync!");
  StartCharacters();
}

void
nsHtml5Highlighter::FlushChars()
{
  if (mCStart < mPos) {
    char16_t* buf = mBuffer->getBuffer();
    int32_t i = mCStart;
    while (i < mPos) {
      char16_t c = buf[i];
      switch (c) {
        case '\r':
          // The input this code sees has been normalized so that there are
          // CR breaks and LF breaks but no CRLF breaks. Overwrite CR with LF
          // to show consistent LF line breaks to layout. It is OK to mutate
          // the input data, because there are no reparses in the View Source
          // case, so we won't need the original data in the buffer anymore.
          buf[i] = '\n';
          MOZ_FALLTHROUGH;
        case '\n': {
          ++i;
          if (mCStart < i) {
            int32_t len = i - mCStart;
            AppendCharacters(buf, mCStart, len);
            mCStart = i;
          }
          ++mLineNumber;
          Push(nsGkAtoms::span, nullptr);
          nsHtml5TreeOperation* treeOp = mOpQueue.AppendElement();
          NS_ASSERTION(treeOp, "Tree op allocation failed.");
          treeOp->InitAddLineNumberId(CurrentNode(), mLineNumber);
          Pop();
          break;
        }
        default:
          ++i;
          break;
      }
    }
    if (mCStart < mPos) {
      int32_t len = mPos - mCStart;
      AppendCharacters(buf, mCStart, len);
      mCStart = mPos;
    }
  }
}

void
nsHtml5Highlighter::FlushCurrent()
{
  mPos++;
  FlushChars();
}

bool
nsHtml5Highlighter::FlushOps()
{
  bool hasOps = !mOpQueue.IsEmpty();
  if (hasOps) {
    mOpSink->MoveOpsFrom(mOpQueue);
  }
  return hasOps;
}

void
nsHtml5Highlighter::MaybeLinkifyAttributeValue(nsHtml5AttributeName* aName,
                                               nsHtml5String aValue)
{
  if (!(nsHtml5AttributeName::ATTR_HREF == aName ||
        nsHtml5AttributeName::ATTR_SRC == aName ||
        nsHtml5AttributeName::ATTR_ACTION == aName ||
        nsHtml5AttributeName::ATTR_CITE == aName ||
        nsHtml5AttributeName::ATTR_BACKGROUND == aName ||
        nsHtml5AttributeName::ATTR_LONGDESC == aName ||
        nsHtml5AttributeName::ATTR_XLINK_HREF == aName ||
        nsHtml5AttributeName::ATTR_DEFINITIONURL == aName)) {
    return;
  }
  AddViewSourceHref(aValue);
}

void
nsHtml5Highlighter::CompletedNamedCharacterReference()
{
  AddClass(sEntity);
}

nsIContent**
nsHtml5Highlighter::AllocateContentHandle()
{
  if (mHandlesUsed == NS_HTML5_HIGHLIGHTER_HANDLE_ARRAY_LENGTH) {
    mOldHandles.AppendElement(Move(mHandles));
    mHandles = MakeUnique<nsIContent*[]>(NS_HTML5_HIGHLIGHTER_HANDLE_ARRAY_LENGTH);
    mHandlesUsed = 0;
  }
#ifdef DEBUG
  mHandles[mHandlesUsed] = reinterpret_cast<nsIContent*>(uintptr_t(0xC0DEDBAD));
#endif
  return &mHandles[mHandlesUsed++];
}

nsIContent**
nsHtml5Highlighter::CreateElement(nsIAtom* aName,
                                  nsHtml5HtmlAttributes* aAttributes,
                                  nsIContent** aIntendedParent)
{
  NS_PRECONDITION(aName, "Got null name.");
  nsIContent** content = AllocateContentHandle();
  mOpQueue.AppendElement()->Init(kNameSpaceID_XHTML,
                                 aName,
                                 aAttributes,
                                 content,
                                 aIntendedParent,
                                 true);
  return content;
}

nsIContent**
nsHtml5Highlighter::CurrentNode()
{
  NS_PRECONDITION(mStack.Length() >= 1, "Must have something on stack.");
  return mStack[mStack.Length() - 1];
}

void
nsHtml5Highlighter::Push(nsIAtom* aName,
                         nsHtml5HtmlAttributes* aAttributes)
{
  NS_PRECONDITION(mStack.Length() >= 1, "Pushing without root.");
  nsIContent** elt = CreateElement(aName, aAttributes, CurrentNode()); // Don't inline below!
  mOpQueue.AppendElement()->Init(eTreeOpAppend, elt, CurrentNode());
  mStack.AppendElement(elt);
}

void
nsHtml5Highlighter::Pop()
{
  NS_PRECONDITION(mStack.Length() >= 2, "Popping when stack too short.");
  mStack.RemoveElementAt(mStack.Length() - 1);
}

void
nsHtml5Highlighter::AppendCharacters(const char16_t* aBuffer,
                                     int32_t aStart,
                                     int32_t aLength)
{
  NS_PRECONDITION(aBuffer, "Null buffer");

  char16_t* bufferCopy = new char16_t[aLength];
  memcpy(bufferCopy, aBuffer + aStart, aLength * sizeof(char16_t));

  mOpQueue.AppendElement()->Init(eTreeOpAppendText,
                                 bufferCopy,
                                 aLength,
                                 CurrentNode());
}


void
nsHtml5Highlighter::AddClass(const char16_t* aClass)
{
  mOpQueue.AppendElement()->InitAddClass(CurrentNode(), aClass);
}

void
nsHtml5Highlighter::AddViewSourceHref(nsHtml5String aValue)
{
  char16_t* bufferCopy = new char16_t[aValue.Length() + 1];
  aValue.CopyToBuffer(bufferCopy);
  bufferCopy[aValue.Length()] = 0;

  mOpQueue.AppendElement()->Init(eTreeOpAddViewSourceHref,
                                 bufferCopy,
                                 aValue.Length(),
                                 CurrentNode());
}

void
nsHtml5Highlighter::AddBase(nsHtml5String aValue)
{
  if(mSeenBase) {
    return;
  }
  mSeenBase = true;
  char16_t* bufferCopy = new char16_t[aValue.Length() + 1];
  aValue.CopyToBuffer(bufferCopy);
  bufferCopy[aValue.Length()] = 0;

  mOpQueue.AppendElement()->Init(eTreeOpAddViewSourceBase,
                                 bufferCopy,
                                 aValue.Length());
}

void
nsHtml5Highlighter::AddErrorToCurrentNode(const char* aMsgId)
{
  nsHtml5TreeOperation* treeOp = mOpQueue.AppendElement();
  NS_ASSERTION(treeOp, "Tree op allocation failed.");
  treeOp->Init(CurrentNode(), aMsgId);
}

void
nsHtml5Highlighter::AddErrorToCurrentRun(const char* aMsgId)
{
  NS_PRECONDITION(mCurrentRun, "Adding error to run without one!");
  nsHtml5TreeOperation* treeOp = mOpQueue.AppendElement();
  NS_ASSERTION(treeOp, "Tree op allocation failed.");
  treeOp->Init(mCurrentRun, aMsgId);
}

void
nsHtml5Highlighter::AddErrorToCurrentRun(const char* aMsgId,
                                         nsIAtom* aName)
{
  NS_PRECONDITION(mCurrentRun, "Adding error to run without one!");
  nsHtml5TreeOperation* treeOp = mOpQueue.AppendElement();
  NS_ASSERTION(treeOp, "Tree op allocation failed.");
  treeOp->Init(mCurrentRun, aMsgId, aName);
}

void
nsHtml5Highlighter::AddErrorToCurrentRun(const char* aMsgId,
                                         nsIAtom* aName,
                                         nsIAtom* aOther)
{
  NS_PRECONDITION(mCurrentRun, "Adding error to run without one!");
  nsHtml5TreeOperation* treeOp = mOpQueue.AppendElement();
  NS_ASSERTION(treeOp, "Tree op allocation failed.");
  treeOp->Init(mCurrentRun, aMsgId, aName, aOther);
}

void
nsHtml5Highlighter::AddErrorToCurrentAmpersand(const char* aMsgId)
{
  NS_PRECONDITION(mAmpersand, "Adding error to ampersand without one!");
  nsHtml5TreeOperation* treeOp = mOpQueue.AppendElement();
  NS_ASSERTION(treeOp, "Tree op allocation failed.");
  treeOp->Init(mAmpersand, aMsgId);
}

void
nsHtml5Highlighter::AddErrorToCurrentSlash(const char* aMsgId)
{
  NS_PRECONDITION(mSlash, "Adding error to slash without one!");
  nsHtml5TreeOperation* treeOp = mOpQueue.AppendElement();
  NS_ASSERTION(treeOp, "Tree op allocation failed.");
  treeOp->Init(mSlash, aMsgId);
}