LayoutTests:
[WebKit-https.git] / WebCore / html / HTMLTokenizer.cpp
1 /*
2     This file is part of the KDE libraries
3
4     Copyright (C) 1997 Martin Jones (mjones@kde.org)
5               (C) 1997 Torben Weis (weis@kde.org)
6               (C) 1998 Waldo Bastian (bastian@kde.org)
7               (C) 1999 Lars Knoll (knoll@kde.org)
8               (C) 1999 Antti Koivisto (koivisto@kde.org)
9               (C) 2001 Dirk Mueller (mueller@kde.org)
10     Copyright (C) 2004, 2005, 2006, 2007 Apple Inc.
11     Copyright (C) 2005, 2006 Alexey Proskuryakov (ap@nypop.com)
12
13     This library is free software; you can redistribute it and/or
14     modify it under the terms of the GNU Library General Public
15     License as published by the Free Software Foundation; either
16     version 2 of the License, or (at your option) any later version.
17
18     This library is distributed in the hope that it will be useful,
19     but WITHOUT ANY WARRANTY; without even the implied warranty of
20     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21     Library General Public License for more details.
22
23     You should have received a copy of the GNU Library General Public License
24     along with this library; see the file COPYING.LIB.  If not, write to
25     the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
26     Boston, MA 02111-1307, USA.
27 */
28
29 #include "config.h"
30 #include "HTMLTokenizer.h"
31
32 #include "Cache.h"
33 #include "CachedScript.h"
34 #include "DocLoader.h"
35 #include "DocumentFragment.h"
36 #include "EventNames.h"
37 #include "Frame.h"
38 #include "FrameLoader.h"
39 #include "FrameView.h"
40 #include "HTMLElement.h"
41 #include "HTMLNames.h"
42 #include "HTMLParser.h"
43 #include "HTMLScriptElement.h"
44 #include "HTMLViewSourceDocument.h"
45 #include "Settings.h"
46 #include "SystemTime.h"
47 #include "csshelper.h"
48 #include "kjs_proxy.h"
49
50 #include "HTMLEntityNames.c"
51
52 // #define INSTRUMENT_LAYOUT_SCHEDULING 1
53
54 #if MOBILE
55 // The mobile device needs to be responsive, as such the tokenizer chunk size is reduced.
56 // This value is used to define how many characters the tokenizer will process before 
57 // yeilding control.
58 #define TOKENIZER_CHUNK_SIZE  256
59 #else
60 #define TOKENIZER_CHUNK_SIZE  4096
61 #endif
62
63 using namespace std;
64
65 namespace WebCore {
66
67 using namespace HTMLNames;
68 using namespace EventNames;
69
70 #if MOBILE
71 // As the chunks are smaller (above), the tokenizer should not yield for as long a period, otherwise
72 // it will take way to long to load a page.
73 const double tokenizerTimeDelay = 0.300;
74
75 #else
76 // FIXME: We would like this constant to be 200ms.
77 // Yielding more aggressively results in increased responsiveness and better incremental rendering.
78 // It slows down overall page-load on slower machines, though, so for now we set a value of 500.
79 const double tokenizerTimeDelay = 0.500;
80 #endif
81
82 static const char commentStart [] = "<!--";
83 static const char scriptEnd [] = "</script";
84 static const char xmpEnd [] = "</xmp";
85 static const char styleEnd [] =  "</style";
86 static const char textareaEnd [] = "</textarea";
87 static const char titleEnd [] = "</title";
88
89 // Full support for MS Windows extensions to Latin-1.
90 // Technically these extensions should only be activated for pages
91 // marked "windows-1252" or "cp1252", but
92 // in the standard Microsoft way, these extensions infect hundreds of thousands
93 // of web pages.  Note that people with non-latin-1 Microsoft extensions
94 // are SOL.
95 //
96 // See: http://www.microsoft.com/globaldev/reference/WinCP.asp
97 //      http://www.bbsinc.com/iso8859.html
98 //      http://www.obviously.com/
99 //
100 // There may be better equivalents
101
102 // We only need this for entities. For non-entity text, we handle this in the text encoding.
103
104 static const UChar windowsLatin1ExtensionArray[32] = {
105     0x20AC, 0x0081, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, // 80-87
106     0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0x008D, 0x017D, 0x008F, // 88-8F
107     0x0090, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, // 90-97
108     0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0x009D, 0x017E, 0x0178  // 98-9F
109 };
110
111 static inline UChar fixUpChar(UChar c)
112 {
113     if ((c & ~0x1F) != 0x0080)
114         return c;
115     return windowsLatin1ExtensionArray[c - 0x80];
116 }
117
118 static inline bool tagMatch(const char* s1, const UChar* s2, unsigned length)
119 {
120     for (unsigned i = 0; i != length; ++i) {
121         unsigned char c1 = s1[i];
122         unsigned char uc1 = toupper(c1);
123         UChar c2 = s2[i];
124         if (c1 != c2 && uc1 != c2)
125             return false;
126     }
127     return true;
128 }
129
130 inline void Token::addAttribute(Document* doc, AtomicString& attrName, const AtomicString& v, bool viewSourceMode)
131 {
132     if (!attrName.isEmpty()) {
133         ASSERT(!attrName.contains('/'));
134         Attribute* a = new MappedAttribute(attrName, v);
135         if (!attrs)
136             attrs = new NamedMappedAttrMap(0);
137         attrs->insertAttribute(a, viewSourceMode);
138     }
139     
140     attrName = emptyAtom;
141 }
142
143 // ----------------------------------------------------------------------------
144
145 HTMLTokenizer::HTMLTokenizer(HTMLDocument* doc, bool reportErrors)
146     : Tokenizer()
147     , buffer(0)
148     , scriptCode(0)
149     , scriptCodeSize(0)
150     , scriptCodeMaxSize(0)
151     , scriptCodeResync(0)
152     , m_executingScript(0)
153     , m_requestingScript(false)
154     , m_timer(this, &HTMLTokenizer::timerFired)
155     , m_doc(doc)
156     , parser(new HTMLParser(doc, reportErrors))
157     , inWrite(false)
158     , m_fragment(false)
159 {
160     begin();
161 }
162
163 HTMLTokenizer::HTMLTokenizer(HTMLViewSourceDocument* doc)
164     : Tokenizer(true)
165     , buffer(0)
166     , scriptCode(0)
167     , scriptCodeSize(0)
168     , scriptCodeMaxSize(0)
169     , scriptCodeResync(0)
170     , m_executingScript(0)
171     , m_requestingScript(false)
172     , m_timer(this, &HTMLTokenizer::timerFired)
173     , m_doc(doc)
174     , parser(0)
175     , inWrite(false)
176     , m_fragment(false)
177 {
178     begin();
179 }
180
181 HTMLTokenizer::HTMLTokenizer(DocumentFragment* frag)
182     : buffer(0)
183     , scriptCode(0)
184     , scriptCodeSize(0)
185     , scriptCodeMaxSize(0)
186     , scriptCodeResync(0)
187     , m_executingScript(0)
188     , m_requestingScript(false)
189     , m_timer(this, &HTMLTokenizer::timerFired)
190     , m_doc(frag->document())
191     , inWrite(false)
192     , m_fragment(true)
193 {
194     parser = new HTMLParser(frag);
195     begin();
196 }
197
198 void HTMLTokenizer::reset()
199 {
200     ASSERT(m_executingScript == 0);
201
202     while (!pendingScripts.isEmpty()) {
203       CachedScript *cs = pendingScripts.dequeue();
204       ASSERT(cache()->disabled() || cs->accessCount() > 0);
205       cs->deref(this);
206     }
207     
208     fastFree(buffer);
209     buffer = dest = 0;
210     size = 0;
211
212     fastFree(scriptCode);
213     scriptCode = 0;
214     scriptCodeSize = scriptCodeMaxSize = scriptCodeResync = 0;
215
216     m_timer.stop();
217     m_state.setAllowYield(false);
218     m_state.setForceSynchronous(false);
219
220     currToken.reset();
221 }
222
223 void HTMLTokenizer::begin()
224 {
225     m_executingScript = 0;
226     m_requestingScript = false;
227     m_state.setLoadingExtScript(false);
228     reset();
229     size = 254;
230     buffer = static_cast<UChar*>(fastMalloc(sizeof(UChar) * 254));
231     dest = buffer;
232     tquote = NoQuote;
233     searchCount = 0;
234     m_state.setEntityState(NoEntity);
235     scriptSrc = String();
236     pendingSrc.clear();
237     currentPrependingSrc = 0;
238     noMoreData = false;
239     brokenComments = false;
240     brokenServer = false;
241     lineno = 0;
242     scriptStartLineno = 0;
243     tagStartLineno = 0;
244     m_state.setForceSynchronous(false);
245 }
246
247 void HTMLTokenizer::setForceSynchronous(bool force)
248 {
249     m_state.setForceSynchronous(force);
250 }
251
252 HTMLTokenizer::State HTMLTokenizer::processListing(SegmentedString list, State state)
253 {
254     // This function adds the listing 'list' as
255     // preformatted text-tokens to the token-collection
256     while (!list.isEmpty()) {
257         if (state.skipLF()) {
258             state.setSkipLF(false);
259             if (*list == '\n') {
260                 list.advance(0);
261                 continue;
262             }
263         }
264
265         checkBuffer();
266
267         if (*list == '\n' || *list == '\r') {
268             if (state.discardLF())
269                 // Ignore this LF
270                 state.setDiscardLF(false); // We have discarded 1 LF
271             else
272                 *dest++ = '\n';
273
274             /* Check for MS-DOS CRLF sequence */
275             if (*list == '\r')
276                 state.setSkipLF(true);
277
278             list.advance(0);
279         } else {
280             state.setDiscardLF(false);
281             *dest++ = *list;
282             list.advance(0);
283         }
284     }
285
286     return state;
287 }
288
289 HTMLTokenizer::State HTMLTokenizer::parseSpecial(SegmentedString &src, State state)
290 {
291     ASSERT(state.inTextArea() || state.inTitle() || !state.hasEntityState());
292     ASSERT(!state.hasTagState());
293     ASSERT(state.inXmp() + state.inTextArea() + state.inTitle() + state.inStyle() + state.inScript() == 1 );
294     if (state.inScript())
295         scriptStartLineno = lineno;
296
297     if (state.inComment()) 
298         state = parseComment(src, state);
299
300     while ( !src.isEmpty() ) {
301         checkScriptBuffer();
302         UChar ch = *src;
303
304         if (!scriptCodeResync && !brokenComments && !state.inTextArea() && !state.inXmp() && ch == '-' && scriptCodeSize >= 3 && !src.escaped() && scriptCode[scriptCodeSize-3] == '<' && scriptCode[scriptCodeSize-2] == '!' && scriptCode[scriptCodeSize-1] == '-') {
305             state.setInComment(true);
306             state = parseComment(src, state);
307             continue;
308         }
309         if (scriptCodeResync && !tquote && ch == '>') {
310             src.advance(lineNumberPtr());
311             scriptCodeSize = scriptCodeResync-1;
312             scriptCodeResync = 0;
313             scriptCode[ scriptCodeSize ] = scriptCode[ scriptCodeSize + 1 ] = 0;
314             if (state.inScript())
315                 state = scriptHandler(state);
316             else {
317                 state = processListing(SegmentedString(scriptCode, scriptCodeSize), state);
318                 processToken();
319                 if (state.inStyle()) { 
320                     currToken.tagName = styleTag.localName(); 
321                     currToken.beginTag = false; 
322                 } else if (state.inTextArea()) { 
323                     currToken.tagName = textareaTag.localName(); 
324                     currToken.beginTag = false; 
325                 } else if (state.inTitle()) { 
326                     currToken.tagName = titleTag.localName(); 
327                     currToken.beginTag = false; 
328                 } else if (state.inXmp()) {
329                     currToken.tagName = xmpTag.localName(); 
330                     currToken.beginTag = false; 
331                 }
332                 processToken();
333                 state.setInStyle(false);
334                 state.setInScript(false);
335                 state.setInTextArea(false);
336                 state.setInTitle(false);
337                 state.setInXmp(false);
338                 tquote = NoQuote;
339                 scriptCodeSize = scriptCodeResync = 0;
340             }
341             return state;
342         }
343         // possible end of tagname, lets check.
344         if (!scriptCodeResync && !state.escaped() && !src.escaped() && (ch == '>' || ch == '/' || ch <= ' ') && ch &&
345              scriptCodeSize >= searchStopperLen &&
346              tagMatch( searchStopper, scriptCode+scriptCodeSize-searchStopperLen, searchStopperLen )) {
347             scriptCodeResync = scriptCodeSize-searchStopperLen+1;
348             tquote = NoQuote;
349             continue;
350         }
351         if (scriptCodeResync && !state.escaped()) {
352             if (ch == '\"')
353                 tquote = (tquote == NoQuote) ? DoubleQuote : ((tquote == SingleQuote) ? SingleQuote : NoQuote);
354             else if (ch == '\'')
355                 tquote = (tquote == NoQuote) ? SingleQuote : (tquote == DoubleQuote) ? DoubleQuote : NoQuote;
356             else if (tquote != NoQuote && (ch == '\r' || ch == '\n'))
357                 tquote = NoQuote;
358         }
359         state.setEscaped(!state.escaped() && ch == '\\');
360         if (!scriptCodeResync && (state.inTextArea() || state.inTitle()) && !src.escaped() && ch == '&') {
361             UChar* scriptCodeDest = scriptCode+scriptCodeSize;
362             src.advance(lineNumberPtr());
363             state = parseEntity(src, scriptCodeDest, state, m_cBufferPos, true, false);
364             scriptCodeSize = scriptCodeDest-scriptCode;
365         } else {
366             scriptCode[scriptCodeSize++] = *src;
367             src.advance(lineNumberPtr());
368         }
369     }
370
371     return state;
372 }
373
374 HTMLTokenizer::State HTMLTokenizer::scriptHandler(State state)
375 {
376     // We are inside a <script>
377     bool doScriptExec = false;
378
379     // (Bugzilla 3837) Scripts following a frameset element should not execute or, 
380     // in the case of extern scripts, even load.
381     bool followingFrameset = (m_doc->body() && m_doc->body()->hasTagName(framesetTag));
382   
383     CachedScript* cs = 0;
384     // don't load external scripts for standalone documents (for now)
385     if (!inViewSourceMode()) {
386         if (!scriptSrc.isEmpty() && m_doc->frame()) {
387             // forget what we just got; load from src url instead
388             if (!parser->skipMode() && !followingFrameset) {
389 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
390                 if (!m_doc->ownerElement())
391                     printf("Requesting script at time %d\n", m_doc->elapsedTime());
392 #endif
393                 // The parser might have been stopped by for example a window.close call in an earlier script.
394                 // If so, we don't want to load scripts.
395                 if (!m_parserStopped && (cs = m_doc->docLoader()->requestScript(scriptSrc, scriptSrcCharset)))
396                     pendingScripts.enqueue(cs);
397                 else
398                     scriptNode = 0;
399             } else
400                 scriptNode = 0;
401             scriptSrc = String();
402         } else {
403 #ifdef TOKEN_DEBUG
404             kdDebug( 6036 ) << "---START SCRIPT---" << endl;
405             kdDebug( 6036 ) << DeprecatedString(scriptCode, scriptCodeSize) << endl;
406             kdDebug( 6036 ) << "---END SCRIPT---" << endl;
407 #endif
408             // Parse scriptCode containing <script> info
409 #if USE(LOW_BANDWIDTH_DISPLAY)
410             if (m_doc->inLowBandwidthDisplay()) {
411                 // ideal solution is only skipping internal JavaScript if there is external JavaScript.
412                 // but internal JavaScript can use document.write() to create an external JavaScript,
413                 // so we have to skip internal JavaScript all the time.
414                 m_doc->frame()->loader()->needToSwitchOutLowBandwidthDisplay();
415                 doScriptExec = false;
416             } else
417 #endif
418             doScriptExec = static_cast<HTMLScriptElement*>(scriptNode.get())->shouldExecuteAsJavaScript();
419             scriptNode = 0;
420         }
421     }
422
423     state = processListing(SegmentedString(scriptCode, scriptCodeSize), state);
424     DeprecatedString exScript(reinterpret_cast<DeprecatedChar*>(buffer), dest - buffer);
425     processToken();
426     currToken.tagName = scriptTag.localName();
427     currToken.beginTag = false;
428     processToken();
429
430     state.setInScript(false);
431     
432     // FIXME: The script should be syntax highlighted.
433     if (inViewSourceMode())
434         return state;
435
436     SegmentedString *savedPrependingSrc = currentPrependingSrc;
437     SegmentedString prependingSrc;
438     currentPrependingSrc = &prependingSrc;
439     scriptCodeSize = scriptCodeResync = 0;
440
441     if (!parser->skipMode() && !followingFrameset) {
442         if (cs) {
443             if (savedPrependingSrc)
444                 savedPrependingSrc->append(src);
445             else
446                 pendingSrc.prepend(src);
447             setSrc(SegmentedString());
448
449             // the ref() call below may call notifyFinished if the script is already in cache,
450             // and that mucks with the state directly, so we must write it back to the object.
451             m_state = state;
452             bool savedRequestingScript = m_requestingScript;
453             m_requestingScript = true;
454             cs->ref(this);
455             m_requestingScript = savedRequestingScript;
456             state = m_state;
457             // will be 0 if script was already loaded and ref() executed it
458             if (!pendingScripts.isEmpty())
459                 state.setLoadingExtScript(true);
460         } else if (!m_fragment && doScriptExec) {
461             if (!m_executingScript)
462                 pendingSrc.prepend(src);
463             else
464                 prependingSrc = src;
465             setSrc(SegmentedString());
466             state = scriptExecution(exScript, state, DeprecatedString::null, scriptStartLineno);
467         }
468     }
469
470     if (!m_executingScript && !state.loadingExtScript()) {
471         src.append(pendingSrc);
472         pendingSrc.clear();
473     } else if (!prependingSrc.isEmpty()) {
474         // restore first so that the write appends in the right place
475         // (does not hurt to do it again below)
476         currentPrependingSrc = savedPrependingSrc;
477
478         // we need to do this slightly modified bit of one of the write() cases
479         // because we want to prepend to pendingSrc rather than appending
480         // if there's no previous prependingSrc
481         if (state.loadingExtScript()) {
482             if (currentPrependingSrc) {
483                 currentPrependingSrc->append(prependingSrc);
484             } else {
485                 pendingSrc.prepend(prependingSrc);
486             }
487         } else {
488             m_state = state;
489             write(prependingSrc, false);
490             state = m_state;
491         }
492     }
493
494     currentPrependingSrc = savedPrependingSrc;
495
496     return state;
497 }
498
499 HTMLTokenizer::State HTMLTokenizer::scriptExecution(const DeprecatedString& str, State state, DeprecatedString scriptURL, int baseLine)
500 {
501     if (m_fragment || !m_doc->frame())
502         return state;
503     m_executingScript++;
504     DeprecatedString url = scriptURL.isNull() ? m_doc->frame()->document()->URL() : scriptURL;
505
506     SegmentedString *savedPrependingSrc = currentPrependingSrc;
507     SegmentedString prependingSrc;
508     currentPrependingSrc = &prependingSrc;
509
510 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
511     if (!m_doc->ownerElement())
512         printf("beginning script execution at %d\n", m_doc->elapsedTime());
513 #endif
514
515     m_state = state;
516     m_doc->frame()->loader()->executeScript(url, baseLine, str);
517     state = m_state;
518
519     state.setAllowYield(true);
520
521 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
522     if (!m_doc->ownerElement())
523         printf("ending script execution at %d\n", m_doc->elapsedTime());
524 #endif
525     
526     m_executingScript--;
527
528     if (!m_executingScript && !state.loadingExtScript()) {
529         src.append(pendingSrc);
530         pendingSrc.clear();
531     } else if (!prependingSrc.isEmpty()) {
532         // restore first so that the write appends in the right place
533         // (does not hurt to do it again below)
534         currentPrependingSrc = savedPrependingSrc;
535
536         // we need to do this slightly modified bit of one of the write() cases
537         // because we want to prepend to pendingSrc rather than appending
538         // if there's no previous prependingSrc
539         if (state.loadingExtScript()) {
540             if (currentPrependingSrc)
541                 currentPrependingSrc->append(prependingSrc);
542             else
543                 pendingSrc.prepend(prependingSrc);
544         } else {
545             m_state = state;
546             write(prependingSrc, false);
547             state = m_state;
548         }
549     }
550
551     currentPrependingSrc = savedPrependingSrc;
552
553     return state;
554 }
555
556 HTMLTokenizer::State HTMLTokenizer::parseComment(SegmentedString &src, State state)
557 {
558     // FIXME: Why does this code even run for comments inside <script> and <style>? This seems bogus.
559     checkScriptBuffer(src.length());
560     while ( !src.isEmpty() ) {
561         scriptCode[ scriptCodeSize++ ] = *src;
562
563         if (*src == '>') {
564             bool handleBrokenComments = brokenComments && !(state.inScript() || state.inStyle());
565             int endCharsCount = 1; // start off with one for the '>' character
566             if (scriptCodeSize > 2 && scriptCode[scriptCodeSize-3] == '-' && scriptCode[scriptCodeSize-2] == '-') {
567                 endCharsCount = 3;
568             }
569             else if (scriptCodeSize > 3 && scriptCode[scriptCodeSize-4] == '-' && scriptCode[scriptCodeSize-3] == '-' && 
570                 scriptCode[scriptCodeSize-2] == '!') {
571                 // Other browsers will accept --!> as a close comment, even though it's
572                 // not technically valid.
573                 endCharsCount = 4;
574             }
575             if (handleBrokenComments || endCharsCount > 1) {
576                 src.advance(lineNumberPtr());
577                 if (!(state.inTitle() || state.inScript() || state.inXmp() || state.inTextArea() || state.inStyle())) {
578                     checkScriptBuffer();
579                     scriptCode[scriptCodeSize] = 0;
580                     scriptCode[scriptCodeSize + 1] = 0;
581                     currToken.tagName = commentAtom;
582                     currToken.beginTag = true;
583                     state = processListing(SegmentedString(scriptCode, scriptCodeSize - endCharsCount), state);
584                     processToken();
585                     currToken.tagName = commentAtom;
586                     currToken.beginTag = false;
587                     processToken();
588                     scriptCodeSize = 0;
589                 }
590                 state.setInComment(false);
591                 return state; // Finished parsing comment
592             }
593         }
594         src.advance(lineNumberPtr());
595     }
596
597     return state;
598 }
599
600 HTMLTokenizer::State HTMLTokenizer::parseServer(SegmentedString& src, State state)
601 {
602     checkScriptBuffer(src.length());
603     while (!src.isEmpty()) {
604         scriptCode[scriptCodeSize++] = *src;
605         if (*src == '>' &&
606             scriptCodeSize > 1 && scriptCode[scriptCodeSize-2] == '%') {
607             src.advance(lineNumberPtr());
608             state.setInServer(false);
609             scriptCodeSize = 0;
610             return state; // Finished parsing server include
611         }
612         src.advance(lineNumberPtr());
613     }
614     return state;
615 }
616
617 HTMLTokenizer::State HTMLTokenizer::parseProcessingInstruction(SegmentedString &src, State state)
618 {
619     UChar oldchar = 0;
620     while (!src.isEmpty()) {
621         UChar chbegin = *src;
622         if (chbegin == '\'')
623             tquote = tquote == SingleQuote ? NoQuote : SingleQuote;
624         else if (chbegin == '\"')
625             tquote = tquote == DoubleQuote ? NoQuote : DoubleQuote;
626         // Look for '?>'
627         // Some crappy sites omit the "?" before it, so
628         // we look for an unquoted '>' instead. (IE compatible)
629         else if (chbegin == '>' && (!tquote || oldchar == '?')) {
630             // We got a '?>' sequence
631             state.setInProcessingInstruction(false);
632             src.advance(lineNumberPtr());
633             state.setDiscardLF(true);
634             return state; // Finished parsing comment!
635         }
636         src.advance(lineNumberPtr());
637         oldchar = chbegin;
638     }
639     
640     return state;
641 }
642
643 HTMLTokenizer::State HTMLTokenizer::parseText(SegmentedString &src, State state)
644 {
645     while (!src.isEmpty()) {
646         UChar cc = *src;
647
648         if (state.skipLF()) {
649             state.setSkipLF(false);
650             if (cc == '\n') {
651                 src.advance(lineNumberPtr());
652                 continue;
653             }
654         }
655
656         // do we need to enlarge the buffer?
657         checkBuffer();
658
659         if (cc == '\r') {
660             state.setSkipLF(true);
661             *dest++ = '\n';
662         } else
663             *dest++ = cc;
664         src.advance(lineNumberPtr());
665     }
666
667     return state;
668 }
669
670
671 HTMLTokenizer::State HTMLTokenizer::parseEntity(SegmentedString &src, UChar*& dest, State state, unsigned &cBufferPos, bool start, bool parsingTag)
672 {
673     if (start)
674     {
675         cBufferPos = 0;
676         state.setEntityState(SearchEntity);
677         EntityUnicodeValue = 0;
678     }
679
680     while(!src.isEmpty())
681     {
682         UChar cc = *src;
683         switch(state.entityState()) {
684         case NoEntity:
685             ASSERT(state.entityState() != NoEntity);
686             return state;
687         
688         case SearchEntity:
689             if(cc == '#') {
690                 cBuffer[cBufferPos++] = cc;
691                 src.advance(lineNumberPtr());
692                 state.setEntityState(NumericSearch);
693             }
694             else
695                 state.setEntityState(EntityName);
696
697             break;
698
699         case NumericSearch:
700             if (cc == 'x' || cc == 'X') {
701                 cBuffer[cBufferPos++] = cc;
702                 src.advance(lineNumberPtr());
703                 state.setEntityState(Hexadecimal);
704             } else if (cc >= '0' && cc <= '9')
705                 state.setEntityState(Decimal);
706             else
707                 state.setEntityState(SearchSemicolon);
708             break;
709
710         case Hexadecimal: {
711             int ll = min(src.length(), 10 - cBufferPos);
712             while (ll--) {
713                 cc = *src;
714                 if (!((cc >= '0' && cc <= '9') || (cc >= 'a' && cc <= 'f') || (cc >= 'A' && cc <= 'F'))) {
715                     state.setEntityState(SearchSemicolon);
716                     break;
717                 }
718                 int digit;
719                 if (cc < 'A')
720                     digit = cc - '0';
721                 else
722                     digit = (cc - 'A' + 10) & 0xF; // handle both upper and lower case without a branch
723                 EntityUnicodeValue = EntityUnicodeValue * 16 + digit;
724                 cBuffer[cBufferPos++] = cc;
725                 src.advance(lineNumberPtr());
726             }
727             if (cBufferPos == 10)  
728                 state.setEntityState(SearchSemicolon);
729             break;
730         }
731         case Decimal:
732         {
733             int ll = min(src.length(), 9-cBufferPos);
734             while(ll--) {
735                 cc = *src;
736
737                 if (!(cc >= '0' && cc <= '9')) {
738                     state.setEntityState(SearchSemicolon);
739                     break;
740                 }
741
742                 EntityUnicodeValue = EntityUnicodeValue * 10 + (cc - '0');
743                 cBuffer[cBufferPos++] = cc;
744                 src.advance(lineNumberPtr());
745             }
746             if (cBufferPos == 9)  
747                 state.setEntityState(SearchSemicolon);
748             break;
749         }
750         case EntityName:
751         {
752             int ll = min(src.length(), 9-cBufferPos);
753             while(ll--) {
754                 cc = *src;
755
756                 if (!((cc >= 'a' && cc <= 'z') || (cc >= '0' && cc <= '9') || (cc >= 'A' && cc <= 'Z'))) {
757                     state.setEntityState(SearchSemicolon);
758                     break;
759                 }
760
761                 cBuffer[cBufferPos++] = cc;
762                 src.advance(lineNumberPtr());
763             }
764             if (cBufferPos == 9) 
765                 state.setEntityState(SearchSemicolon);
766             if (state.entityState() == SearchSemicolon) {
767                 if(cBufferPos > 1) {
768                     const Entity *e = findEntity(cBuffer, cBufferPos);
769                     if(e)
770                         EntityUnicodeValue = e->code;
771
772                     // be IE compatible
773                     if(parsingTag && EntityUnicodeValue > 255 && *src != ';')
774                         EntityUnicodeValue = 0;
775                 }
776             }
777             else
778                 break;
779         }
780         case SearchSemicolon:
781             // Don't allow values that are more than 21 bits.
782             if (EntityUnicodeValue > 0 && EntityUnicodeValue <= 0x10FFFF) {
783                 if (!inViewSourceMode()) {
784                     if (*src == ';')
785                         src.advance(lineNumberPtr());
786                     if (EntityUnicodeValue <= 0xFFFF) {
787                         checkBuffer();
788                         src.push(fixUpChar(EntityUnicodeValue));
789                     } else {
790                         // Convert to UTF-16, using surrogate code points.
791                         checkBuffer(2);
792                         src.push(U16_LEAD(EntityUnicodeValue));
793                         src.push(U16_TRAIL(EntityUnicodeValue));
794                     }
795                 } else {
796                     // FIXME: We should eventually colorize entities by sending them as a special token.
797                     checkBuffer(11);
798                     *dest++ = '&';
799                     for (unsigned i = 0; i < cBufferPos; i++)
800                         dest[i] = cBuffer[i];
801                     dest += cBufferPos;
802                     if (*src == ';') {
803                         *dest++ = ';';
804                         src.advance(lineNumberPtr());
805                     }
806                 }
807             } else {
808                 checkBuffer(10);
809                 // ignore the sequence, add it to the buffer as plaintext
810                 *dest++ = '&';
811                 for (unsigned i = 0; i < cBufferPos; i++)
812                     dest[i] = cBuffer[i];
813                 dest += cBufferPos;
814             }
815
816             state.setEntityState(NoEntity);
817             return state;
818         }
819     }
820
821     return state;
822 }
823
824 HTMLTokenizer::State HTMLTokenizer::parseTag(SegmentedString &src, State state)
825 {
826     ASSERT(!state.hasEntityState());
827
828     unsigned cBufferPos = m_cBufferPos;
829
830     int* lineNoPtr = lineNumberPtr();
831     bool lastIsSlash = false;
832
833     while (!src.isEmpty()) {
834         checkBuffer();
835         switch(state.tagState()) {
836         case NoTag:
837         {
838             m_cBufferPos = cBufferPos;
839             return state;
840         }
841         case TagName:
842         {
843 #if defined(TOKEN_DEBUG) && TOKEN_DEBUG > 1
844             qDebug("TagName");
845 #endif
846             if (searchCount > 0)
847             {
848                 if (*src == commentStart[searchCount])
849                 {
850                     searchCount++;
851                     if (searchCount == 4)
852                     {
853 #ifdef TOKEN_DEBUG
854                         kdDebug( 6036 ) << "Found comment" << endl;
855 #endif
856                         // Found '<!--' sequence
857                         src.advance(lineNoPtr);
858                         dest = buffer; // ignore the previous part of this tag
859                         state.setInComment(true);
860                         state.setTagState(NoTag);
861
862                         // Fix bug 34302 at kde.bugs.org.  Go ahead and treat
863                         // <!--> as a valid comment, since both mozilla and IE on windows
864                         // can handle this case.  Only do this in quirks mode. -dwh
865                         if (!src.isEmpty() && *src == '>' && m_doc->inCompatMode()) {
866                           state.setInComment(false);
867                           src.advance(lineNoPtr);
868                           if (!src.isEmpty())
869                               // cuts off high bits, which is okay
870                               cBuffer[cBufferPos++] = *src;
871                         }
872                         else
873                           state = parseComment(src, state);
874
875                         m_cBufferPos = cBufferPos;
876                         return state; // Finished parsing tag!
877                     }
878                     // cuts off high bits, which is okay
879                     cBuffer[cBufferPos++] = *src;
880                     src.advance(lineNoPtr);
881                     break;
882                 }
883                 else
884                     searchCount = 0; // Stop looking for '<!--' sequence
885             }
886
887             bool finish = false;
888             unsigned int ll = min(src.length(), CBUFLEN - cBufferPos);
889             while (ll--) {
890                 UChar curchar = *src;
891                 if (curchar <= ' ' || curchar == '>' || curchar == '<') {
892                     finish = true;
893                     break;
894                 }
895                 
896                 // tolower() shows up on profiles. This is faster!
897                 if (curchar >= 'A' && curchar <= 'Z' && !inViewSourceMode())
898                     cBuffer[cBufferPos++] = curchar + ('a' - 'A');
899                 else
900                     cBuffer[cBufferPos++] = curchar;
901                 src.advance(lineNoPtr);
902             }
903
904             // Disadvantage: we add the possible rest of the tag
905             // as attribute names. ### judge if this causes problems
906             if(finish || CBUFLEN == cBufferPos) {
907                 bool beginTag;
908                 char* ptr = cBuffer;
909                 unsigned int len = cBufferPos;
910                 cBuffer[cBufferPos] = '\0';
911                 if ((cBufferPos > 0) && (*ptr == '/')) {
912                     // End Tag
913                     beginTag = false;
914                     ptr++;
915                     len--;
916                 }
917                 else
918                     // Start Tag
919                     beginTag = true;
920
921                 // Ignore the / in fake xml tags like <br/>.  We trim off the "/" so that we'll get "br" as the tag name and not "br/".
922                 if (len > 1 && ptr[len-1] == '/' && !inViewSourceMode())
923                     ptr[--len] = '\0';
924
925                 // Now that we've shaved off any invalid / that might have followed the name), make the tag.
926                 // FIXME: FireFox and WinIE turn !foo nodes into comments, we ignore comments. (fast/parser/tag-with-exclamation-point.html)
927                 if (ptr[0] != '!' || inViewSourceMode()) {
928                     currToken.tagName = AtomicString(ptr);
929                     currToken.beginTag = beginTag;
930                 }
931                 dest = buffer;
932                 state.setTagState(SearchAttribute);
933                 cBufferPos = 0;
934             }
935             break;
936         }
937         case SearchAttribute:
938 #if defined(TOKEN_DEBUG) && TOKEN_DEBUG > 1
939             qDebug("SearchAttribute");
940 #endif
941             while(!src.isEmpty()) {
942                 UChar curchar = *src;
943                 // In this mode just ignore any quotes we encounter and treat them like spaces.
944                 if (curchar > ' ' && curchar != '\'' && curchar != '"') {
945                     if (curchar == '<' || curchar == '>')
946                         state.setTagState(SearchEnd);
947                     else
948                         state.setTagState(AttributeName);
949
950                     cBufferPos = 0;
951                     break;
952                 }
953                 if (inViewSourceMode())
954                     currToken.addViewSourceChar(curchar);
955                 src.advance(lineNoPtr);
956             }
957             break;
958         case AttributeName:
959         {
960 #if defined(TOKEN_DEBUG) && TOKEN_DEBUG > 1
961             qDebug("AttributeName");
962 #endif
963             int ll = min(src.length(), CBUFLEN-cBufferPos);
964             while(ll--) {
965                 UChar curchar = *src;
966                 // If we encounter a "/" when scanning an attribute name, treat it as a delimiter.  This allows the 
967                 // cases like <input type=checkbox checked/> to work (and accommodates XML-style syntax as per HTML5).
968                 if (curchar <= '>' && (curchar >= '<' || curchar <= ' ' || curchar == '/')) {
969                     cBuffer[cBufferPos] = '\0';
970                     attrName = AtomicString(cBuffer);
971                     dest = buffer;
972                     *dest++ = 0;
973                     state.setTagState(SearchEqual);
974                     if (inViewSourceMode())
975                         currToken.addViewSourceChar('a');
976                     break;
977                 }
978                 
979                 // tolower() shows up on profiles. This is faster!
980                 if (curchar >= 'A' && curchar <= 'Z' && !inViewSourceMode())
981                     cBuffer[cBufferPos++] = curchar + ('a' - 'A');
982                 else
983                     cBuffer[cBufferPos++] = curchar;
984                     
985                 src.advance(lineNoPtr);
986             }
987             if ( cBufferPos == CBUFLEN ) {
988                 cBuffer[cBufferPos] = '\0';
989                 attrName = AtomicString(cBuffer);
990                 dest = buffer;
991                 *dest++ = 0;
992                 state.setTagState(SearchEqual);
993                 if (inViewSourceMode())
994                     currToken.addViewSourceChar('a');
995             }
996             break;
997         }
998         case SearchEqual:
999 #if defined(TOKEN_DEBUG) && TOKEN_DEBUG > 1
1000             qDebug("SearchEqual");
1001 #endif
1002             while(!src.isEmpty()) {
1003                 UChar curchar = *src;
1004
1005                 if (lastIsSlash && curchar == '>') {
1006                     // This is a quirk (with a long sad history).  We have to do this
1007                     // since widgets do <script src="foo.js"/> and expect the tag to close.
1008                     if (currToken.tagName == scriptTag)
1009                         currToken.flat = true;
1010                     currToken.brokenXMLStyle = true;
1011                 }
1012
1013                 // In this mode just ignore any quotes or slashes we encounter and treat them like spaces.
1014                 if (curchar > ' ' && curchar != '\'' && curchar != '"' && curchar != '/') {
1015                     if(curchar == '=') {
1016 #ifdef TOKEN_DEBUG
1017                         kdDebug(6036) << "found equal" << endl;
1018 #endif
1019                         state.setTagState(SearchValue);
1020                         if (inViewSourceMode())
1021                             currToken.addViewSourceChar(curchar);
1022                         src.advance(lineNoPtr);
1023                     }
1024                     else {
1025                         currToken.addAttribute(m_doc, attrName, emptyAtom, inViewSourceMode());
1026                         dest = buffer;
1027                         state.setTagState(SearchAttribute);
1028                         lastIsSlash = false;
1029                     }
1030                     break;
1031                 }
1032                 if (inViewSourceMode())
1033                     currToken.addViewSourceChar(curchar);
1034                     
1035                 lastIsSlash = curchar == '/';
1036
1037                 src.advance(lineNoPtr);
1038             }
1039             break;
1040         case SearchValue:
1041             while(!src.isEmpty()) {
1042                 UChar curchar = *src;
1043                 if(curchar > ' ') {
1044                     if(( curchar == '\'' || curchar == '\"' )) {
1045                         tquote = curchar == '\"' ? DoubleQuote : SingleQuote;
1046                         state.setTagState(QuotedValue);
1047                         if (inViewSourceMode())
1048                             currToken.addViewSourceChar(curchar);
1049                         src.advance(lineNoPtr);
1050                     } else
1051                         state.setTagState(Value);
1052
1053                     break;
1054                 }
1055                 if (inViewSourceMode())
1056                     currToken.addViewSourceChar(curchar);
1057                 src.advance(lineNoPtr);
1058             }
1059             break;
1060         case QuotedValue:
1061 #if defined(TOKEN_DEBUG) && TOKEN_DEBUG > 1
1062             qDebug("QuotedValue");
1063 #endif
1064             while(!src.isEmpty()) {
1065                 checkBuffer();
1066
1067                 UChar curchar = *src;
1068                 if (curchar == '>' && attrName.isEmpty()) {
1069                     // Handle a case like <img '>.  Just go ahead and be willing
1070                     // to close the whole tag.  Don't consume the character and
1071                     // just go back into SearchEnd while ignoring the whole
1072                     // value.
1073                     // FIXME: Note that this is actually not a very good solution. It's
1074                     // an interim hack and doesn't handle the general case of
1075                     // unmatched quotes among attributes that have names. -dwh
1076                     while(dest > buffer+1 && (*(dest-1) == '\n' || *(dest-1) == '\r'))
1077                         dest--; // remove trailing newlines
1078                     AtomicString v(buffer+1, dest-buffer-1);
1079                     attrName = v; // Just make the name/value match. (FIXME: Is this some WinIE quirk?)
1080                     currToken.addAttribute(m_doc, attrName, v, inViewSourceMode());
1081                     if (inViewSourceMode())
1082                         currToken.addViewSourceChar('x');
1083                     state.setTagState(SearchAttribute);
1084                     dest = buffer;
1085                     tquote = NoQuote;
1086                     break;
1087                 }
1088                 
1089                 if(curchar <= '\'' && !src.escaped()) {
1090                     // ### attributes like '&{blaa....};' are supposed to be treated as jscript.
1091                     if ( curchar == '&' )
1092                     {
1093                         src.advance(lineNoPtr);
1094                         state = parseEntity(src, dest, state, cBufferPos, true, true);
1095                         break;
1096                     }
1097                     else if ( (tquote == SingleQuote && curchar == '\'') ||
1098                               (tquote == DoubleQuote && curchar == '\"') )
1099                     {
1100                         // some <input type=hidden> rely on trailing spaces. argh
1101                         while(dest > buffer+1 && (*(dest-1) == '\n' || *(dest-1) == '\r'))
1102                             dest--; // remove trailing newlines
1103                         AtomicString v(buffer+1, dest-buffer-1);
1104                         if (attrName.isEmpty()) {
1105                             attrName = v; // Make the name match the value. (FIXME: Is this a WinIE quirk?)
1106                             if (inViewSourceMode())
1107                                 currToken.addViewSourceChar('x');
1108                         } else if (inViewSourceMode())
1109                             currToken.addViewSourceChar('v');
1110                         currToken.addAttribute(m_doc, attrName, v, inViewSourceMode());
1111                         dest = buffer;
1112                         state.setTagState(SearchAttribute);
1113                         tquote = NoQuote;
1114                         if (inViewSourceMode())
1115                             currToken.addViewSourceChar(curchar);
1116                         src.advance(lineNoPtr);
1117                         break;
1118                     }
1119                 }
1120                 *dest++ = *src;
1121                 src.advance(lineNoPtr);
1122             }
1123             break;
1124         case Value:
1125 #if defined(TOKEN_DEBUG) && TOKEN_DEBUG > 1
1126             qDebug("Value");
1127 #endif
1128             while(!src.isEmpty()) {
1129                 checkBuffer();
1130                 UChar curchar = *src;
1131                 if(curchar <= '>' && !src.escaped()) {
1132                     // parse Entities
1133                     if ( curchar == '&' )
1134                     {
1135                         src.advance(lineNoPtr);
1136                         state = parseEntity(src, dest, state, cBufferPos, true, true);
1137                         break;
1138                     }
1139                     // no quotes. Every space means end of value
1140                     // '/' does not delimit in IE!
1141                     if ( curchar <= ' ' || curchar == '>' )
1142                     {
1143                         AtomicString v(buffer+1, dest-buffer-1);
1144                         currToken.addAttribute(m_doc, attrName, v, inViewSourceMode());
1145                         if (inViewSourceMode())
1146                             currToken.addViewSourceChar('v');
1147                         dest = buffer;
1148                         state.setTagState(SearchAttribute);
1149                         break;
1150                     }
1151                 }
1152
1153                 *dest++ = *src;
1154                 src.advance(lineNoPtr);
1155             }
1156             break;
1157         case SearchEnd:
1158         {
1159 #if defined(TOKEN_DEBUG) && TOKEN_DEBUG > 1
1160                 qDebug("SearchEnd");
1161 #endif
1162             while(!src.isEmpty()) {
1163                 if (*src == '>' || *src == '<')
1164                     break;
1165
1166                 if (*src == '/')
1167                     currToken.flat = true;
1168
1169                 if (inViewSourceMode())
1170                     currToken.addViewSourceChar(*src);
1171                 src.advance(lineNoPtr);
1172             }
1173             if (src.isEmpty()) break;
1174
1175             searchCount = 0; // Stop looking for '<!--' sequence
1176             state.setTagState(NoTag);
1177             tquote = NoQuote;
1178
1179             if (*src != '<')
1180                 src.advance(lineNoPtr);
1181
1182             if (currToken.tagName == nullAtom) { //stop if tag is unknown
1183                 m_cBufferPos = cBufferPos;
1184                 return state;
1185             }
1186
1187             AtomicString tagName = currToken.tagName;
1188 #if defined(TOKEN_DEBUG) && TOKEN_DEBUG > 0
1189             kdDebug( 6036 ) << "appending Tag: " << tagName.deprecatedString() << endl;
1190 #endif
1191
1192             // Handle <script src="foo"/> like Mozilla/Opera. We have to do this now for Dashboard
1193             // compatibility.
1194             bool isSelfClosingScript = currToken.flat && currToken.beginTag && currToken.tagName == scriptTag;
1195             bool beginTag = !currToken.flat && currToken.beginTag;
1196             if (currToken.beginTag && currToken.tagName == scriptTag && !inViewSourceMode() && !parser->skipMode()) {
1197                 Attribute* a = 0;
1198                 scriptSrc = String();
1199                 scriptSrcCharset = String();
1200                 if (currToken.attrs && !m_fragment) {
1201                     Settings* settings = m_doc->settings();
1202                     if (settings && settings->isJavaScriptEnabled()) {
1203                         if ((a = currToken.attrs->getAttributeItem(srcAttr)))
1204                             scriptSrc = m_doc->completeURL(parseURL(a->value()));
1205                         if ((a = currToken.attrs->getAttributeItem(charsetAttr)))
1206                             scriptSrcCharset = a->value().domString().stripWhiteSpace();
1207                         if (scriptSrcCharset.isEmpty())
1208                             scriptSrcCharset = m_doc->frame()->loader()->encoding();
1209                     }
1210                 }
1211             }
1212
1213             RefPtr<Node> n = processToken();
1214             m_cBufferPos = cBufferPos;
1215             if (n) {
1216                 if ((tagName == preTag || tagName == listingTag) && !inViewSourceMode()) {
1217                     if (beginTag)
1218                         state.setDiscardLF(true); // Discard the first LF after we open a pre.
1219                 } else if (tagName == scriptTag && n) {
1220                     ASSERT(!scriptNode);
1221                     scriptNode = n;
1222                     if (beginTag) {
1223                         searchStopper = scriptEnd;
1224                         searchStopperLen = 8;
1225                         state.setInScript(true);
1226                         state = parseSpecial(src, state);
1227                     } else if (isSelfClosingScript) { // Handle <script src="foo"/>
1228                         state.setInScript(true);
1229                         state = scriptHandler(state);
1230                     }
1231                 } else if (tagName == styleTag) {
1232                     if (beginTag) {
1233                         searchStopper = styleEnd;
1234                         searchStopperLen = 7;
1235                         state.setInStyle(true);
1236                         state = parseSpecial(src, state);
1237                     }
1238                 } else if (tagName == textareaTag) {
1239                     if (beginTag) {
1240                         searchStopper = textareaEnd;
1241                         searchStopperLen = 10;
1242                         state.setInTextArea(true);
1243                         state = parseSpecial(src, state);
1244                     }
1245                 } else if (tagName == titleTag) {
1246                     if (beginTag) {
1247                         searchStopper = titleEnd;
1248                         searchStopperLen = 7;
1249                         State savedState = state;
1250                         SegmentedString savedSrc = src;
1251                         long savedLineno = lineno;
1252                         state.setInTitle(true);
1253                         state = parseSpecial(src, state);
1254                         if (state.inTitle() && src.isEmpty()) {
1255                             // We just ate the rest of the document as the title #text node!
1256                             // Reset the state then retokenize without special title handling.
1257                             // Let the parser clean up the missing </title> tag.
1258                             // FIXME: This is incorrect, because src.isEmpty() doesn't mean we're
1259                             // at the end of the document unless noMoreData is also true. We need
1260                             // to detect this case elsewhere, and save the state somewhere other
1261                             // than a local variable.
1262                             state = savedState;
1263                             src = savedSrc;
1264                             lineno = savedLineno;
1265                             scriptCodeSize = 0;
1266                         }
1267                     }
1268                 } else if (tagName == xmpTag) {
1269                     if (beginTag) {
1270                         searchStopper = xmpEnd;
1271                         searchStopperLen = 5;
1272                         state.setInXmp(true);
1273                         state = parseSpecial(src, state);
1274                     }
1275                 }
1276             }
1277             if (tagName == plaintextTag)
1278                 state.setInPlainText(beginTag);
1279             return state; // Finished parsing tag!
1280         }
1281         } // end switch
1282     }
1283     m_cBufferPos = cBufferPos;
1284     return state;
1285 }
1286
1287 inline bool HTMLTokenizer::continueProcessing(int& processedCount, double startTime, State &state)
1288 {
1289     // We don't want to be checking elapsed time with every character, so we only check after we've
1290     // processed a certain number of characters.
1291     bool allowedYield = state.allowYield();
1292     state.setAllowYield(false);
1293     if (!state.loadingExtScript() && !state.forceSynchronous() && !m_executingScript && (processedCount > TOKENIZER_CHUNK_SIZE || allowedYield)) {
1294         processedCount = 0;
1295         if (currentTime() - startTime > tokenizerTimeDelay) {
1296             /* FIXME: We'd like to yield aggressively to give stylesheets the opportunity to
1297                load, but this hurts overall performance on slower machines.  For now turn this
1298                off.
1299             || (!m_doc->haveStylesheetsLoaded() && 
1300                 (m_doc->documentElement()->id() != ID_HTML || m_doc->body()))) {*/
1301             // Schedule the timer to keep processing as soon as possible.
1302             m_timer.startOneShot(0);
1303 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1304             if (currentTime() - startTime > tokenizerTimeDelay)
1305                 printf("Deferring processing of data because 500ms elapsed away from event loop.\n");
1306 #endif
1307             return false;
1308         }
1309     }
1310     
1311     processedCount++;
1312     return true;
1313 }
1314
1315 bool HTMLTokenizer::write(const SegmentedString& str, bool appendData)
1316 {
1317 #ifdef TOKEN_DEBUG
1318     kdDebug( 6036 ) << this << " Tokenizer::write(\"" << str.toString() << "\"," << appendData << ")" << endl;
1319 #endif
1320
1321     if (!buffer)
1322         return false;
1323     
1324     if (m_parserStopped)
1325         return false;
1326
1327     SegmentedString source(str);
1328     if (m_executingScript)
1329         source.setExcludeLineNumbers();
1330
1331     if ((m_executingScript && appendData) || !pendingScripts.isEmpty()) {
1332         // don't parse; we will do this later
1333         if (currentPrependingSrc)
1334             currentPrependingSrc->append(source);
1335         else
1336             pendingSrc.append(source);
1337         return false;
1338     }
1339
1340     if (!src.isEmpty())
1341         src.append(source);
1342     else
1343         setSrc(source);
1344
1345     // Once a timer is set, it has control of when the tokenizer continues.
1346     if (m_timer.isActive())
1347         return false;
1348
1349     bool wasInWrite = inWrite;
1350     inWrite = true;
1351     
1352 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1353     if (!m_doc->ownerElement())
1354         printf("Beginning write at time %d\n", m_doc->elapsedTime());
1355 #endif
1356     
1357     int processedCount = 0;
1358     double startTime = currentTime();
1359
1360     Frame *frame = m_doc->frame();
1361
1362     State state = m_state;
1363
1364     int* lineNoPtr = lineNumberPtr();
1365
1366     while (!src.isEmpty() && (!frame || !frame->loader()->isScheduledLocationChangePending())) {
1367         if (!continueProcessing(processedCount, startTime, state))
1368             break;
1369
1370         // do we need to enlarge the buffer?
1371         checkBuffer();
1372
1373         UChar cc = *src;
1374
1375         bool wasSkipLF = state.skipLF();
1376         if (wasSkipLF)
1377             state.setSkipLF(false);
1378
1379         if (wasSkipLF && (cc == '\n'))
1380             src.advance(0);
1381         else if (state.needsSpecialWriteHandling()) {
1382             // it's important to keep needsSpecialWriteHandling with the flags this block tests
1383             if (state.hasEntityState())
1384                 state = parseEntity(src, dest, state, m_cBufferPos, false, state.hasTagState());
1385             else if (state.inPlainText())
1386                 state = parseText(src, state);
1387             else if (state.inAnySpecial())
1388                 state = parseSpecial(src, state);
1389             else if (state.inComment())
1390                 state = parseComment(src, state);
1391             else if (state.inServer())
1392                 state = parseServer(src, state);
1393             else if (state.inProcessingInstruction())
1394                 state = parseProcessingInstruction(src, state);
1395             else if (state.hasTagState())
1396                 state = parseTag(src, state);
1397             else if (state.startTag()) {
1398                 state.setStartTag(false);
1399                 
1400                 switch(cc) {
1401                 case '/':
1402                     break;
1403                 case '!': {
1404                     // <!-- comment -->
1405                     searchCount = 1; // Look for '<!--' sequence to start comment
1406                     
1407                     break;
1408                 }
1409                 case '?': {
1410                     // xml processing instruction
1411                     state.setInProcessingInstruction(true);
1412                     tquote = NoQuote;
1413                     state = parseProcessingInstruction(src, state);
1414                     continue;
1415
1416                     break;
1417                 }
1418                 case '%':
1419                     if (!brokenServer) {
1420                         // <% server stuff, handle as comment %>
1421                         state.setInServer(true);
1422                         tquote = NoQuote;
1423                         state = parseServer(src, state);
1424                         continue;
1425                     }
1426                     // else fall through
1427                 default: {
1428                     if( ((cc >= 'a') && (cc <= 'z')) || ((cc >= 'A') && (cc <= 'Z'))) {
1429                         // Start of a Start-Tag
1430                     } else {
1431                         // Invalid tag
1432                         // Add as is
1433                         *dest = '<';
1434                         dest++;
1435                         continue;
1436                     }
1437                 }
1438                 }; // end case
1439
1440                 processToken();
1441
1442                 m_cBufferPos = 0;
1443                 state.setTagState(TagName);
1444                 state = parseTag(src, state);
1445             }
1446         } else if (cc == '&' && !src.escaped()) {
1447             src.advance(lineNoPtr);
1448             state = parseEntity(src, dest, state, m_cBufferPos, true, state.hasTagState());
1449         } else if (cc == '<' && !src.escaped()) {
1450             tagStartLineno = lineno;
1451             src.advance(lineNoPtr);
1452             state.setStartTag(true);
1453         } else if (cc == '\n' || cc == '\r') {
1454             if (state.discardLF())
1455                 // Ignore this LF
1456                 state.setDiscardLF(false); // We have discarded 1 LF
1457             else {
1458                 // Process this LF
1459                 *dest++ = '\n';
1460                 if (cc == '\r' && !src.excludeLineNumbers())
1461                     lineno++;
1462             }
1463
1464             /* Check for MS-DOS CRLF sequence */
1465             if (cc == '\r')
1466                 state.setSkipLF(true);
1467             src.advance(lineNoPtr);
1468         } else {
1469             state.setDiscardLF(false);
1470             *dest++ = cc;
1471             src.advance(lineNoPtr);
1472         }
1473     }
1474     
1475 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1476     if (!m_doc->ownerElement())
1477         printf("Ending write at time %d\n", m_doc->elapsedTime());
1478 #endif
1479     
1480     inWrite = wasInWrite;
1481
1482     m_state = state;
1483
1484     if (noMoreData && !inWrite && !state.loadingExtScript() && !m_executingScript && !m_timer.isActive()) {
1485         end(); // this actually causes us to be deleted
1486         return true;
1487     }
1488     return false;
1489 }
1490
1491 void HTMLTokenizer::stopParsing()
1492 {
1493     Tokenizer::stopParsing();
1494     m_timer.stop();
1495
1496     // The part needs to know that the tokenizer has finished with its data,
1497     // regardless of whether it happened naturally or due to manual intervention.
1498     if (!m_fragment && m_doc->frame())
1499         m_doc->frame()->loader()->tokenizerProcessedData();
1500 }
1501
1502 bool HTMLTokenizer::processingData() const
1503 {
1504     return m_timer.isActive();
1505 }
1506
1507 void HTMLTokenizer::timerFired(Timer<HTMLTokenizer>*)
1508 {
1509 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1510     if (!m_doc->ownerElement())
1511         printf("Beginning timer write at time %d\n", m_doc->elapsedTime());
1512 #endif
1513
1514     if (m_doc->view() && m_doc->view()->layoutPending() && !m_doc->minimumLayoutDelay()) {
1515         // Restart the timer and let layout win.  This is basically a way of ensuring that the layout
1516         // timer has higher priority than our timer.
1517         m_timer.startOneShot(0);
1518         return;
1519     }
1520     
1521     RefPtr<Frame> frame = m_fragment ? 0 : m_doc->frame();
1522
1523     // Invoke write() as though more data came in.
1524     bool didCallEnd = write(SegmentedString(), true);
1525   
1526     // If we called end() during the write,  we need to let WebKit know that we're done processing the data.
1527     if (didCallEnd && frame)
1528         frame->loader()->tokenizerProcessedData();
1529 }
1530
1531 void HTMLTokenizer::end()
1532 {
1533     ASSERT(!m_timer.isActive());
1534     m_timer.stop(); // Only helps if assertion above fires, but do it anyway.
1535
1536     if (buffer) {
1537         // parseTag is using the buffer for different matters
1538         if (!m_state.hasTagState())
1539             processToken();
1540
1541         fastFree(scriptCode);
1542         scriptCode = 0;
1543         scriptCodeSize = scriptCodeMaxSize = scriptCodeResync = 0;
1544
1545         fastFree(buffer);
1546         buffer = 0;
1547     }
1548
1549     if (!inViewSourceMode())
1550         parser->finished();
1551     else
1552         m_doc->finishedParsing();
1553 }
1554
1555 void HTMLTokenizer::finish()
1556 {
1557     // do this as long as we don't find matching comment ends
1558     while((m_state.inComment() || m_state.inServer()) && scriptCode && scriptCodeSize) {
1559         // we've found an unmatched comment start
1560         if (m_state.inComment())
1561             brokenComments = true;
1562         else
1563             brokenServer = true;
1564         checkScriptBuffer();
1565         scriptCode[scriptCodeSize] = 0;
1566         scriptCode[scriptCodeSize + 1] = 0;
1567         int pos;
1568         String food;
1569         if (m_state.inScript() || m_state.inStyle())
1570             food = String(scriptCode, scriptCodeSize);
1571         else if (m_state.inServer()) {
1572             food = "<";
1573             food.append(String(scriptCode, scriptCodeSize));
1574         } else {
1575             pos = DeprecatedConstString(reinterpret_cast<DeprecatedChar*>(scriptCode), scriptCodeSize).string().find('>');
1576             food = String(scriptCode + pos + 1, scriptCodeSize - pos - 1);
1577         }
1578         fastFree(scriptCode);
1579         scriptCode = 0;
1580         scriptCodeSize = scriptCodeMaxSize = scriptCodeResync = 0;
1581         m_state.setInComment(false);
1582         m_state.setInServer(false);
1583         if (!food.isEmpty())
1584             write(food, true);
1585     }
1586     // this indicates we will not receive any more data... but if we are waiting on
1587     // an external script to load, we can't finish parsing until that is done
1588     noMoreData = true;
1589     if (!inWrite && !m_state.loadingExtScript() && !m_executingScript && !m_timer.isActive())
1590         end(); // this actually causes us to be deleted
1591 }
1592
1593 PassRefPtr<Node> HTMLTokenizer::processToken()
1594 {
1595     KJSProxy* jsProxy = (!m_fragment && m_doc->frame()) ? m_doc->frame()->scriptProxy() : 0;
1596     if (jsProxy)
1597         jsProxy->setEventHandlerLineno(tagStartLineno);
1598     if (dest > buffer) {
1599 #ifdef TOKEN_DEBUG
1600         if(currToken.tagName.length()) {
1601             qDebug( "unexpected token: %s, str: *%s*", currToken.tagName.deprecatedString().latin1(),DeprecatedConstString( buffer,dest-buffer ).deprecatedString().latin1() );
1602             ASSERT(0);
1603         }
1604
1605 #endif
1606         currToken.text = StringImpl::createStrippingNull(buffer, dest - buffer);
1607         if (currToken.tagName != commentAtom)
1608             currToken.tagName = textAtom;
1609     } else if (currToken.tagName == nullAtom) {
1610         currToken.reset();
1611         if (jsProxy)
1612             jsProxy->setEventHandlerLineno(lineno);
1613         return 0;
1614     }
1615
1616     dest = buffer;
1617
1618 #ifdef TOKEN_DEBUG
1619     DeprecatedString name = currToken.tagName.deprecatedString();
1620     DeprecatedString text;
1621     if(currToken.text)
1622         text = DeprecatedConstString(currToken.text->unicode(), currToken.text->length()).deprecatedString();
1623
1624     kdDebug( 6036 ) << "Token --> " << name << endl;
1625     if (currToken.flat)
1626         kdDebug( 6036 ) << "Token is FLAT!" << endl;
1627     if(!text.isNull())
1628         kdDebug( 6036 ) << "text: \"" << text << "\"" << endl;
1629     unsigned l = currToken.attrs ? currToken.attrs->length() : 0;
1630     if(l) {
1631         kdDebug( 6036 ) << "Attributes: " << l << endl;
1632         for (unsigned i = 0; i < l; ++i) {
1633             Attribute* c = currToken.attrs->attributeItem(i);
1634             kdDebug( 6036 ) << "    " << c->localName().deprecatedString()
1635                             << "=\"" << c->value().deprecatedString() << "\"" << endl;
1636         }
1637     }
1638     kdDebug( 6036 ) << endl;
1639 #endif
1640
1641     RefPtr<Node> n;
1642     
1643     if (!m_parserStopped) {
1644         if (inViewSourceMode())
1645             static_cast<HTMLViewSourceDocument*>(m_doc)->addViewSourceToken(&currToken);
1646         else
1647             // pass the token over to the parser, the parser DOES NOT delete the token
1648             n = parser->parseToken(&currToken);
1649     }
1650     currToken.reset();
1651     if (jsProxy)
1652         jsProxy->setEventHandlerLineno(0);
1653
1654     return n.release();
1655 }
1656
1657 HTMLTokenizer::~HTMLTokenizer()
1658 {
1659     ASSERT(!inWrite);
1660     reset();
1661     delete parser;
1662 }
1663
1664
1665 void HTMLTokenizer::enlargeBuffer(int len)
1666 {
1667     int newSize = max(size * 2, size + len);
1668     int oldOffset = dest - buffer;
1669     buffer = static_cast<UChar*>(fastRealloc(buffer, newSize * sizeof(UChar)));
1670     dest = buffer + oldOffset;
1671     size = newSize;
1672 }
1673
1674 void HTMLTokenizer::enlargeScriptBuffer(int len)
1675 {
1676     int newSize = max(scriptCodeMaxSize * 2, scriptCodeMaxSize + len);
1677     scriptCode = static_cast<UChar*>(fastRealloc(scriptCode, newSize * sizeof(UChar)));
1678     scriptCodeMaxSize = newSize;
1679 }
1680
1681 void HTMLTokenizer::notifyFinished(CachedResource*)
1682 {
1683 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1684     if (!m_doc->ownerElement())
1685         printf("script loaded at %d\n", m_doc->elapsedTime());
1686 #endif
1687
1688     ASSERT(!pendingScripts.isEmpty());
1689     bool finished = false;
1690     while (!finished && pendingScripts.head()->isLoaded()) {
1691 #ifdef TOKEN_DEBUG
1692         kdDebug( 6036 ) << "Finished loading an external script" << endl;
1693 #endif
1694         CachedScript* cs = pendingScripts.dequeue();
1695         ASSERT(cache()->disabled() || cs->accessCount() > 0);
1696
1697         String scriptSource = cs->script();
1698 #ifdef TOKEN_DEBUG
1699         kdDebug( 6036 ) << "External script is:" << endl << scriptSource.deprecatedString() << endl;
1700 #endif
1701         setSrc(SegmentedString());
1702
1703         // make sure we forget about the script before we execute the new one
1704         // infinite recursion might happen otherwise
1705         DeprecatedString cachedScriptUrl( cs->url().deprecatedString() );
1706         bool errorOccurred = cs->errorOccurred();
1707         cs->deref(this);
1708         RefPtr<Node> n = scriptNode.release();
1709
1710 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1711         if (!m_doc->ownerElement())
1712             printf("external script beginning execution at %d\n", m_doc->elapsedTime());
1713 #endif
1714
1715         if (errorOccurred)
1716             EventTargetNodeCast(n.get())->dispatchHTMLEvent(errorEvent, true, false);
1717         else {
1718             if (static_cast<HTMLScriptElement*>(n.get())->shouldExecuteAsJavaScript())
1719                 m_state = scriptExecution(scriptSource.deprecatedString(), m_state, cachedScriptUrl);
1720             EventTargetNodeCast(n.get())->dispatchHTMLEvent(loadEvent, false, false);
1721         }
1722
1723         // The state of pendingScripts.isEmpty() can change inside the scriptExecution()
1724         // call above, so test afterwards.
1725         finished = pendingScripts.isEmpty();
1726         if (finished) {
1727             m_state.setLoadingExtScript(false);
1728 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1729             if (!m_doc->ownerElement())
1730                 printf("external script finished execution at %d\n", m_doc->elapsedTime());
1731 #endif
1732         }
1733
1734         // 'm_requestingScript' is true when we are called synchronously from
1735         // scriptHandler(). In that case scriptHandler() will take care
1736         // of pendingSrc.
1737         if (!m_requestingScript) {
1738             SegmentedString rest = pendingSrc;
1739             pendingSrc.clear();
1740             write(rest, false);
1741             // we might be deleted at this point, do not
1742             // access any members.
1743         }
1744     }
1745 }
1746
1747 bool HTMLTokenizer::isWaitingForScripts() const
1748 {
1749     return m_state.loadingExtScript();
1750 }
1751
1752 void HTMLTokenizer::setSrc(const SegmentedString &source)
1753 {
1754     src = source;
1755 }
1756
1757 void parseHTMLDocumentFragment(const String& source, DocumentFragment* fragment)
1758 {
1759     HTMLTokenizer tok(fragment);
1760     tok.setForceSynchronous(true);
1761     tok.write(source, true);
1762     tok.finish();
1763     ASSERT(!tok.processingData());      // make sure we're done (see 3963151)
1764 }
1765
1766 UChar decodeNamedEntity(const char* name)
1767 {
1768     const Entity* e = findEntity(name, strlen(name));
1769     return e ? e->code : 0;
1770 }
1771
1772 }