52c1321476f835d33253e5e704c178b5361b7d01
[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
832     while (!src.isEmpty()) {
833         checkBuffer();
834         switch(state.tagState()) {
835         case NoTag:
836         {
837             m_cBufferPos = cBufferPos;
838             return state;
839         }
840         case TagName:
841         {
842 #if defined(TOKEN_DEBUG) && TOKEN_DEBUG > 1
843             qDebug("TagName");
844 #endif
845             if (searchCount > 0)
846             {
847                 if (*src == commentStart[searchCount])
848                 {
849                     searchCount++;
850                     if (searchCount == 4)
851                     {
852 #ifdef TOKEN_DEBUG
853                         kdDebug( 6036 ) << "Found comment" << endl;
854 #endif
855                         // Found '<!--' sequence
856                         src.advance(lineNoPtr);
857                         dest = buffer; // ignore the previous part of this tag
858                         state.setInComment(true);
859                         state.setTagState(NoTag);
860
861                         // Fix bug 34302 at kde.bugs.org.  Go ahead and treat
862                         // <!--> as a valid comment, since both mozilla and IE on windows
863                         // can handle this case.  Only do this in quirks mode. -dwh
864                         if (!src.isEmpty() && *src == '>' && m_doc->inCompatMode()) {
865                           state.setInComment(false);
866                           src.advance(lineNoPtr);
867                           if (!src.isEmpty())
868                               // cuts off high bits, which is okay
869                               cBuffer[cBufferPos++] = *src;
870                         }
871                         else
872                           state = parseComment(src, state);
873
874                         m_cBufferPos = cBufferPos;
875                         return state; // Finished parsing tag!
876                     }
877                     // cuts off high bits, which is okay
878                     cBuffer[cBufferPos++] = *src;
879                     src.advance(lineNoPtr);
880                     break;
881                 }
882                 else
883                     searchCount = 0; // Stop looking for '<!--' sequence
884             }
885
886             bool finish = false;
887             unsigned int ll = min(src.length(), CBUFLEN - cBufferPos);
888             while (ll--) {
889                 UChar curchar = *src;
890                 if (curchar <= ' ' || curchar == '>' || curchar == '<') {
891                     finish = true;
892                     break;
893                 }
894                 
895                 // tolower() shows up on profiles. This is faster!
896                 if (curchar >= 'A' && curchar <= 'Z' && !inViewSourceMode())
897                     cBuffer[cBufferPos++] = curchar + ('a' - 'A');
898                 else
899                     cBuffer[cBufferPos++] = curchar;
900                 src.advance(lineNoPtr);
901             }
902
903             // Disadvantage: we add the possible rest of the tag
904             // as attribute names. ### judge if this causes problems
905             if(finish || CBUFLEN == cBufferPos) {
906                 bool beginTag;
907                 char* ptr = cBuffer;
908                 unsigned int len = cBufferPos;
909                 cBuffer[cBufferPos] = '\0';
910                 if ((cBufferPos > 0) && (*ptr == '/')) {
911                     // End Tag
912                     beginTag = false;
913                     ptr++;
914                     len--;
915                 }
916                 else
917                     // Start Tag
918                     beginTag = true;
919
920                 // 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/".
921                 if (len > 1 && ptr[len-1] == '/' && !inViewSourceMode())
922                     ptr[--len] = '\0';
923
924                 // Now that we've shaved off any invalid / that might have followed the name), make the tag.
925                 // FIXME: FireFox and WinIE turn !foo nodes into comments, we ignore comments. (fast/parser/tag-with-exclamation-point.html)
926                 if (ptr[0] != '!' || inViewSourceMode()) {
927                     currToken.tagName = AtomicString(ptr);
928                     currToken.beginTag = beginTag;
929                 }
930                 dest = buffer;
931                 state.setTagState(SearchAttribute);
932                 cBufferPos = 0;
933             }
934             break;
935         }
936         case SearchAttribute:
937 #if defined(TOKEN_DEBUG) && TOKEN_DEBUG > 1
938             qDebug("SearchAttribute");
939 #endif
940             while(!src.isEmpty()) {
941                 UChar curchar = *src;
942                 // In this mode just ignore any quotes we encounter and treat them like spaces.
943                 if (curchar > ' ' && curchar != '\'' && curchar != '"') {
944                     if (curchar == '<' || curchar == '>')
945                         state.setTagState(SearchEnd);
946                     else
947                         state.setTagState(AttributeName);
948
949                     cBufferPos = 0;
950                     break;
951                 }
952                 if (inViewSourceMode())
953                     currToken.addViewSourceChar(curchar);
954                 src.advance(lineNoPtr);
955             }
956             break;
957         case AttributeName:
958         {
959 #if defined(TOKEN_DEBUG) && TOKEN_DEBUG > 1
960             qDebug("AttributeName");
961 #endif
962             int ll = min(src.length(), CBUFLEN-cBufferPos);
963             while(ll--) {
964                 UChar curchar = *src;
965                 // If we encounter a "/" when scanning an attribute name, treat it as a delimiter.  This allows the 
966                 // cases like <input type=checkbox checked/> to work (and accommodates XML-style syntax as per HTML5).
967                 if (curchar <= '>' && (curchar >= '<' || curchar <= ' ' || curchar == '/')) {
968                     cBuffer[cBufferPos] = '\0';
969                     attrName = AtomicString(cBuffer);
970                     dest = buffer;
971                     *dest++ = 0;
972                     state.setTagState(SearchEqual);
973                     if (inViewSourceMode())
974                         currToken.addViewSourceChar('a');
975                     break;
976                 }
977                 
978                 // tolower() shows up on profiles. This is faster!
979                 if (curchar >= 'A' && curchar <= 'Z' && !inViewSourceMode())
980                     cBuffer[cBufferPos++] = curchar + ('a' - 'A');
981                 else
982                     cBuffer[cBufferPos++] = curchar;
983                     
984                 src.advance(lineNoPtr);
985             }
986             if ( cBufferPos == CBUFLEN ) {
987                 cBuffer[cBufferPos] = '\0';
988                 attrName = AtomicString(cBuffer);
989                 dest = buffer;
990                 *dest++ = 0;
991                 state.setTagState(SearchEqual);
992                 if (inViewSourceMode())
993                     currToken.addViewSourceChar('a');
994             }
995             break;
996         }
997         case SearchEqual:
998 #if defined(TOKEN_DEBUG) && TOKEN_DEBUG > 1
999             qDebug("SearchEqual");
1000 #endif
1001             while(!src.isEmpty()) {
1002                 UChar curchar = *src;
1003                 // In this mode just ignore any quotes or slashes we encounter and treat them like spaces.
1004                 if (curchar > ' ' && curchar != '\'' && curchar != '"' && curchar != '/') {
1005                     if(curchar == '=') {
1006 #ifdef TOKEN_DEBUG
1007                         kdDebug(6036) << "found equal" << endl;
1008 #endif
1009                         state.setTagState(SearchValue);
1010                         if (inViewSourceMode())
1011                             currToken.addViewSourceChar(curchar);
1012                         src.advance(lineNoPtr);
1013                     }
1014                     else {
1015                         currToken.addAttribute(m_doc, attrName, emptyAtom, inViewSourceMode());
1016                         dest = buffer;
1017                         state.setTagState(SearchAttribute);
1018                     }
1019                     break;
1020                 }
1021                 if (inViewSourceMode())
1022                     currToken.addViewSourceChar(curchar);
1023                     
1024                 if (curchar == '/') {
1025                     // This is a quirk (with a long sad history).  We have to do this
1026                     // since widgets do <script src="foo.js"/> and expect the tag to close.
1027                     if (currToken.tagName == scriptTag)
1028                         currToken.flat = true;
1029                     currToken.brokenXMLStyle = true;
1030                 }
1031                 src.advance(lineNoPtr);
1032             }
1033             break;
1034         case SearchValue:
1035             while(!src.isEmpty()) {
1036                 UChar curchar = *src;
1037                 if(curchar > ' ') {
1038                     if(( curchar == '\'' || curchar == '\"' )) {
1039                         tquote = curchar == '\"' ? DoubleQuote : SingleQuote;
1040                         state.setTagState(QuotedValue);
1041                         if (inViewSourceMode())
1042                             currToken.addViewSourceChar(curchar);
1043                         src.advance(lineNoPtr);
1044                     } else
1045                         state.setTagState(Value);
1046
1047                     break;
1048                 }
1049                 if (inViewSourceMode())
1050                     currToken.addViewSourceChar(curchar);
1051                 src.advance(lineNoPtr);
1052             }
1053             break;
1054         case QuotedValue:
1055 #if defined(TOKEN_DEBUG) && TOKEN_DEBUG > 1
1056             qDebug("QuotedValue");
1057 #endif
1058             while(!src.isEmpty()) {
1059                 checkBuffer();
1060
1061                 UChar curchar = *src;
1062                 if (curchar == '>' && attrName.isEmpty()) {
1063                     // Handle a case like <img '>.  Just go ahead and be willing
1064                     // to close the whole tag.  Don't consume the character and
1065                     // just go back into SearchEnd while ignoring the whole
1066                     // value.
1067                     // FIXME: Note that this is actually not a very good solution. It's
1068                     // an interim hack and doesn't handle the general case of
1069                     // unmatched quotes among attributes that have names. -dwh
1070                     while(dest > buffer+1 && (*(dest-1) == '\n' || *(dest-1) == '\r'))
1071                         dest--; // remove trailing newlines
1072                     AtomicString v(buffer+1, dest-buffer-1);
1073                     attrName = v; // Just make the name/value match. (FIXME: Is this some WinIE quirk?)
1074                     currToken.addAttribute(m_doc, attrName, v, inViewSourceMode());
1075                     if (inViewSourceMode())
1076                         currToken.addViewSourceChar('x');
1077                     state.setTagState(SearchAttribute);
1078                     dest = buffer;
1079                     tquote = NoQuote;
1080                     break;
1081                 }
1082                 
1083                 if(curchar <= '\'' && !src.escaped()) {
1084                     // ### attributes like '&{blaa....};' are supposed to be treated as jscript.
1085                     if ( curchar == '&' )
1086                     {
1087                         src.advance(lineNoPtr);
1088                         state = parseEntity(src, dest, state, cBufferPos, true, true);
1089                         break;
1090                     }
1091                     else if ( (tquote == SingleQuote && curchar == '\'') ||
1092                               (tquote == DoubleQuote && curchar == '\"') )
1093                     {
1094                         // some <input type=hidden> rely on trailing spaces. argh
1095                         while(dest > buffer+1 && (*(dest-1) == '\n' || *(dest-1) == '\r'))
1096                             dest--; // remove trailing newlines
1097                         AtomicString v(buffer+1, dest-buffer-1);
1098                         if (attrName.isEmpty()) {
1099                             attrName = v; // Make the name match the value. (FIXME: Is this a WinIE quirk?)
1100                             if (inViewSourceMode())
1101                                 currToken.addViewSourceChar('x');
1102                         } else if (inViewSourceMode())
1103                             currToken.addViewSourceChar('v');
1104                         currToken.addAttribute(m_doc, attrName, v, inViewSourceMode());
1105                         dest = buffer;
1106                         state.setTagState(SearchAttribute);
1107                         tquote = NoQuote;
1108                         if (inViewSourceMode())
1109                             currToken.addViewSourceChar(curchar);
1110                         src.advance(lineNoPtr);
1111                         break;
1112                     }
1113                 }
1114                 *dest++ = *src;
1115                 src.advance(lineNoPtr);
1116             }
1117             break;
1118         case Value:
1119 #if defined(TOKEN_DEBUG) && TOKEN_DEBUG > 1
1120             qDebug("Value");
1121 #endif
1122             while(!src.isEmpty()) {
1123                 checkBuffer();
1124                 UChar curchar = *src;
1125                 if(curchar <= '>' && !src.escaped()) {
1126                     // parse Entities
1127                     if ( curchar == '&' )
1128                     {
1129                         src.advance(lineNoPtr);
1130                         state = parseEntity(src, dest, state, cBufferPos, true, true);
1131                         break;
1132                     }
1133                     // no quotes. Every space means end of value
1134                     // '/' does not delimit in IE!
1135                     if ( curchar <= ' ' || curchar == '>' )
1136                     {
1137                         AtomicString v(buffer+1, dest-buffer-1);
1138                         currToken.addAttribute(m_doc, attrName, v, inViewSourceMode());
1139                         if (inViewSourceMode())
1140                             currToken.addViewSourceChar('v');
1141                         dest = buffer;
1142                         state.setTagState(SearchAttribute);
1143                         break;
1144                     }
1145                 }
1146
1147                 *dest++ = *src;
1148                 src.advance(lineNoPtr);
1149             }
1150             break;
1151         case SearchEnd:
1152         {
1153 #if defined(TOKEN_DEBUG) && TOKEN_DEBUG > 1
1154                 qDebug("SearchEnd");
1155 #endif
1156             while(!src.isEmpty()) {
1157                 if (*src == '>' || *src == '<')
1158                     break;
1159
1160                 if (*src == '/')
1161                     currToken.flat = true;
1162
1163                 if (inViewSourceMode())
1164                     currToken.addViewSourceChar(*src);
1165                 src.advance(lineNoPtr);
1166             }
1167             if (src.isEmpty()) break;
1168
1169             searchCount = 0; // Stop looking for '<!--' sequence
1170             state.setTagState(NoTag);
1171             tquote = NoQuote;
1172
1173             if (*src != '<')
1174                 src.advance(lineNoPtr);
1175
1176             if (currToken.tagName == nullAtom) { //stop if tag is unknown
1177                 m_cBufferPos = cBufferPos;
1178                 return state;
1179             }
1180
1181             AtomicString tagName = currToken.tagName;
1182 #if defined(TOKEN_DEBUG) && TOKEN_DEBUG > 0
1183             kdDebug( 6036 ) << "appending Tag: " << tagName.deprecatedString() << endl;
1184 #endif
1185
1186             // Handle <script src="foo"/> like Mozilla/Opera. We have to do this now for Dashboard
1187             // compatibility.
1188             bool isSelfClosingScript = currToken.flat && currToken.beginTag && currToken.tagName == scriptTag;
1189             bool beginTag = !currToken.flat && currToken.beginTag;
1190             if (currToken.beginTag && currToken.tagName == scriptTag && !inViewSourceMode() && !parser->skipMode()) {
1191                 Attribute* a = 0;
1192                 scriptSrc = String();
1193                 scriptSrcCharset = String();
1194                 if (currToken.attrs && !m_fragment) {
1195                     Settings* settings = m_doc->settings();
1196                     if (settings && settings->isJavaScriptEnabled()) {
1197                         if ((a = currToken.attrs->getAttributeItem(srcAttr)))
1198                             scriptSrc = m_doc->completeURL(parseURL(a->value()));
1199                         if ((a = currToken.attrs->getAttributeItem(charsetAttr)))
1200                             scriptSrcCharset = a->value().domString().stripWhiteSpace();
1201                         if (scriptSrcCharset.isEmpty())
1202                             scriptSrcCharset = m_doc->frame()->loader()->encoding();
1203                     }
1204                 }
1205             }
1206
1207             RefPtr<Node> n = processToken();
1208             m_cBufferPos = cBufferPos;
1209             if (n) {
1210                 if ((tagName == preTag || tagName == listingTag) && !inViewSourceMode()) {
1211                     if (beginTag)
1212                         state.setDiscardLF(true); // Discard the first LF after we open a pre.
1213                 } else if (tagName == scriptTag && n) {
1214                     ASSERT(!scriptNode);
1215                     scriptNode = n;
1216                     if (beginTag) {
1217                         searchStopper = scriptEnd;
1218                         searchStopperLen = 8;
1219                         state.setInScript(true);
1220                         state = parseSpecial(src, state);
1221                     } else if (isSelfClosingScript) { // Handle <script src="foo"/>
1222                         state.setInScript(true);
1223                         state = scriptHandler(state);
1224                     }
1225                 } else if (tagName == styleTag) {
1226                     if (beginTag) {
1227                         searchStopper = styleEnd;
1228                         searchStopperLen = 7;
1229                         state.setInStyle(true);
1230                         state = parseSpecial(src, state);
1231                     }
1232                 } else if (tagName == textareaTag) {
1233                     if (beginTag) {
1234                         searchStopper = textareaEnd;
1235                         searchStopperLen = 10;
1236                         state.setInTextArea(true);
1237                         state = parseSpecial(src, state);
1238                     }
1239                 } else if (tagName == titleTag) {
1240                     if (beginTag) {
1241                         searchStopper = titleEnd;
1242                         searchStopperLen = 7;
1243                         State savedState = state;
1244                         SegmentedString savedSrc = src;
1245                         long savedLineno = lineno;
1246                         state.setInTitle(true);
1247                         state = parseSpecial(src, state);
1248                         if (state.inTitle() && src.isEmpty()) {
1249                             // We just ate the rest of the document as the title #text node!
1250                             // Reset the state then retokenize without special title handling.
1251                             // Let the parser clean up the missing </title> tag.
1252                             // FIXME: This is incorrect, because src.isEmpty() doesn't mean we're
1253                             // at the end of the document unless noMoreData is also true. We need
1254                             // to detect this case elsewhere, and save the state somewhere other
1255                             // than a local variable.
1256                             state = savedState;
1257                             src = savedSrc;
1258                             lineno = savedLineno;
1259                             scriptCodeSize = 0;
1260                         }
1261                     }
1262                 } else if (tagName == xmpTag) {
1263                     if (beginTag) {
1264                         searchStopper = xmpEnd;
1265                         searchStopperLen = 5;
1266                         state.setInXmp(true);
1267                         state = parseSpecial(src, state);
1268                     }
1269                 }
1270             }
1271             if (tagName == plaintextTag)
1272                 state.setInPlainText(beginTag);
1273             return state; // Finished parsing tag!
1274         }
1275         } // end switch
1276     }
1277     m_cBufferPos = cBufferPos;
1278     return state;
1279 }
1280
1281 inline bool HTMLTokenizer::continueProcessing(int& processedCount, double startTime, State &state)
1282 {
1283     // We don't want to be checking elapsed time with every character, so we only check after we've
1284     // processed a certain number of characters.
1285     bool allowedYield = state.allowYield();
1286     state.setAllowYield(false);
1287     if (!state.loadingExtScript() && !state.forceSynchronous() && !m_executingScript && (processedCount > TOKENIZER_CHUNK_SIZE || allowedYield)) {
1288         processedCount = 0;
1289         if (currentTime() - startTime > tokenizerTimeDelay) {
1290             /* FIXME: We'd like to yield aggressively to give stylesheets the opportunity to
1291                load, but this hurts overall performance on slower machines.  For now turn this
1292                off.
1293             || (!m_doc->haveStylesheetsLoaded() && 
1294                 (m_doc->documentElement()->id() != ID_HTML || m_doc->body()))) {*/
1295             // Schedule the timer to keep processing as soon as possible.
1296             m_timer.startOneShot(0);
1297 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1298             if (currentTime() - startTime > tokenizerTimeDelay)
1299                 printf("Deferring processing of data because 500ms elapsed away from event loop.\n");
1300 #endif
1301             return false;
1302         }
1303     }
1304     
1305     processedCount++;
1306     return true;
1307 }
1308
1309 bool HTMLTokenizer::write(const SegmentedString& str, bool appendData)
1310 {
1311 #ifdef TOKEN_DEBUG
1312     kdDebug( 6036 ) << this << " Tokenizer::write(\"" << str.toString() << "\"," << appendData << ")" << endl;
1313 #endif
1314
1315     if (!buffer)
1316         return false;
1317     
1318     if (m_parserStopped)
1319         return false;
1320
1321     SegmentedString source(str);
1322     if (m_executingScript)
1323         source.setExcludeLineNumbers();
1324
1325     if ((m_executingScript && appendData) || !pendingScripts.isEmpty()) {
1326         // don't parse; we will do this later
1327         if (currentPrependingSrc)
1328             currentPrependingSrc->append(source);
1329         else
1330             pendingSrc.append(source);
1331         return false;
1332     }
1333
1334     if (!src.isEmpty())
1335         src.append(source);
1336     else
1337         setSrc(source);
1338
1339     // Once a timer is set, it has control of when the tokenizer continues.
1340     if (m_timer.isActive())
1341         return false;
1342
1343     bool wasInWrite = inWrite;
1344     inWrite = true;
1345     
1346 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1347     if (!m_doc->ownerElement())
1348         printf("Beginning write at time %d\n", m_doc->elapsedTime());
1349 #endif
1350     
1351     int processedCount = 0;
1352     double startTime = currentTime();
1353
1354     Frame *frame = m_doc->frame();
1355
1356     State state = m_state;
1357
1358     int* lineNoPtr = lineNumberPtr();
1359
1360     while (!src.isEmpty() && (!frame || !frame->loader()->isScheduledLocationChangePending())) {
1361         if (!continueProcessing(processedCount, startTime, state))
1362             break;
1363
1364         // do we need to enlarge the buffer?
1365         checkBuffer();
1366
1367         UChar cc = *src;
1368
1369         bool wasSkipLF = state.skipLF();
1370         if (wasSkipLF)
1371             state.setSkipLF(false);
1372
1373         if (wasSkipLF && (cc == '\n'))
1374             src.advance(0);
1375         else if (state.needsSpecialWriteHandling()) {
1376             // it's important to keep needsSpecialWriteHandling with the flags this block tests
1377             if (state.hasEntityState())
1378                 state = parseEntity(src, dest, state, m_cBufferPos, false, state.hasTagState());
1379             else if (state.inPlainText())
1380                 state = parseText(src, state);
1381             else if (state.inAnySpecial())
1382                 state = parseSpecial(src, state);
1383             else if (state.inComment())
1384                 state = parseComment(src, state);
1385             else if (state.inServer())
1386                 state = parseServer(src, state);
1387             else if (state.inProcessingInstruction())
1388                 state = parseProcessingInstruction(src, state);
1389             else if (state.hasTagState())
1390                 state = parseTag(src, state);
1391             else if (state.startTag()) {
1392                 state.setStartTag(false);
1393                 
1394                 switch(cc) {
1395                 case '/':
1396                     break;
1397                 case '!': {
1398                     // <!-- comment -->
1399                     searchCount = 1; // Look for '<!--' sequence to start comment
1400                     
1401                     break;
1402                 }
1403                 case '?': {
1404                     // xml processing instruction
1405                     state.setInProcessingInstruction(true);
1406                     tquote = NoQuote;
1407                     state = parseProcessingInstruction(src, state);
1408                     continue;
1409
1410                     break;
1411                 }
1412                 case '%':
1413                     if (!brokenServer) {
1414                         // <% server stuff, handle as comment %>
1415                         state.setInServer(true);
1416                         tquote = NoQuote;
1417                         state = parseServer(src, state);
1418                         continue;
1419                     }
1420                     // else fall through
1421                 default: {
1422                     if( ((cc >= 'a') && (cc <= 'z')) || ((cc >= 'A') && (cc <= 'Z'))) {
1423                         // Start of a Start-Tag
1424                     } else {
1425                         // Invalid tag
1426                         // Add as is
1427                         *dest = '<';
1428                         dest++;
1429                         continue;
1430                     }
1431                 }
1432                 }; // end case
1433
1434                 processToken();
1435
1436                 m_cBufferPos = 0;
1437                 state.setTagState(TagName);
1438                 state = parseTag(src, state);
1439             }
1440         } else if (cc == '&' && !src.escaped()) {
1441             src.advance(lineNoPtr);
1442             state = parseEntity(src, dest, state, m_cBufferPos, true, state.hasTagState());
1443         } else if (cc == '<' && !src.escaped()) {
1444             tagStartLineno = lineno;
1445             src.advance(lineNoPtr);
1446             state.setStartTag(true);
1447         } else if (cc == '\n' || cc == '\r') {
1448             if (state.discardLF())
1449                 // Ignore this LF
1450                 state.setDiscardLF(false); // We have discarded 1 LF
1451             else {
1452                 // Process this LF
1453                 *dest++ = '\n';
1454                 if (cc == '\r' && !src.excludeLineNumbers())
1455                     lineno++;
1456             }
1457
1458             /* Check for MS-DOS CRLF sequence */
1459             if (cc == '\r')
1460                 state.setSkipLF(true);
1461             src.advance(lineNoPtr);
1462         } else {
1463             state.setDiscardLF(false);
1464             *dest++ = cc;
1465             src.advance(lineNoPtr);
1466         }
1467     }
1468     
1469 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1470     if (!m_doc->ownerElement())
1471         printf("Ending write at time %d\n", m_doc->elapsedTime());
1472 #endif
1473     
1474     inWrite = wasInWrite;
1475
1476     m_state = state;
1477
1478     if (noMoreData && !inWrite && !state.loadingExtScript() && !m_executingScript && !m_timer.isActive()) {
1479         end(); // this actually causes us to be deleted
1480         return true;
1481     }
1482     return false;
1483 }
1484
1485 void HTMLTokenizer::stopParsing()
1486 {
1487     Tokenizer::stopParsing();
1488     m_timer.stop();
1489
1490     // The part needs to know that the tokenizer has finished with its data,
1491     // regardless of whether it happened naturally or due to manual intervention.
1492     if (!m_fragment && m_doc->frame())
1493         m_doc->frame()->loader()->tokenizerProcessedData();
1494 }
1495
1496 bool HTMLTokenizer::processingData() const
1497 {
1498     return m_timer.isActive();
1499 }
1500
1501 void HTMLTokenizer::timerFired(Timer<HTMLTokenizer>*)
1502 {
1503 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1504     if (!m_doc->ownerElement())
1505         printf("Beginning timer write at time %d\n", m_doc->elapsedTime());
1506 #endif
1507
1508     if (m_doc->view() && m_doc->view()->layoutPending() && !m_doc->minimumLayoutDelay()) {
1509         // Restart the timer and let layout win.  This is basically a way of ensuring that the layout
1510         // timer has higher priority than our timer.
1511         m_timer.startOneShot(0);
1512         return;
1513     }
1514     
1515     RefPtr<Frame> frame = m_fragment ? 0 : m_doc->frame();
1516
1517     // Invoke write() as though more data came in.
1518     bool didCallEnd = write(SegmentedString(), true);
1519   
1520     // If we called end() during the write,  we need to let WebKit know that we're done processing the data.
1521     if (didCallEnd && frame)
1522         frame->loader()->tokenizerProcessedData();
1523 }
1524
1525 void HTMLTokenizer::end()
1526 {
1527     ASSERT(!m_timer.isActive());
1528     m_timer.stop(); // Only helps if assertion above fires, but do it anyway.
1529
1530     if (buffer) {
1531         // parseTag is using the buffer for different matters
1532         if (!m_state.hasTagState())
1533             processToken();
1534
1535         fastFree(scriptCode);
1536         scriptCode = 0;
1537         scriptCodeSize = scriptCodeMaxSize = scriptCodeResync = 0;
1538
1539         fastFree(buffer);
1540         buffer = 0;
1541     }
1542
1543     if (!inViewSourceMode())
1544         parser->finished();
1545     else
1546         m_doc->finishedParsing();
1547 }
1548
1549 void HTMLTokenizer::finish()
1550 {
1551     // do this as long as we don't find matching comment ends
1552     while((m_state.inComment() || m_state.inServer()) && scriptCode && scriptCodeSize) {
1553         // we've found an unmatched comment start
1554         if (m_state.inComment())
1555             brokenComments = true;
1556         else
1557             brokenServer = true;
1558         checkScriptBuffer();
1559         scriptCode[scriptCodeSize] = 0;
1560         scriptCode[scriptCodeSize + 1] = 0;
1561         int pos;
1562         String food;
1563         if (m_state.inScript() || m_state.inStyle())
1564             food = String(scriptCode, scriptCodeSize);
1565         else if (m_state.inServer()) {
1566             food = "<";
1567             food.append(String(scriptCode, scriptCodeSize));
1568         } else {
1569             pos = DeprecatedConstString(reinterpret_cast<DeprecatedChar*>(scriptCode), scriptCodeSize).string().find('>');
1570             food = String(scriptCode + pos + 1, scriptCodeSize - pos - 1);
1571         }
1572         fastFree(scriptCode);
1573         scriptCode = 0;
1574         scriptCodeSize = scriptCodeMaxSize = scriptCodeResync = 0;
1575         m_state.setInComment(false);
1576         m_state.setInServer(false);
1577         if (!food.isEmpty())
1578             write(food, true);
1579     }
1580     // this indicates we will not receive any more data... but if we are waiting on
1581     // an external script to load, we can't finish parsing until that is done
1582     noMoreData = true;
1583     if (!inWrite && !m_state.loadingExtScript() && !m_executingScript && !m_timer.isActive())
1584         end(); // this actually causes us to be deleted
1585 }
1586
1587 PassRefPtr<Node> HTMLTokenizer::processToken()
1588 {
1589     KJSProxy* jsProxy = (!m_fragment && m_doc->frame()) ? m_doc->frame()->scriptProxy() : 0;
1590     if (jsProxy)
1591         jsProxy->setEventHandlerLineno(tagStartLineno);
1592     if (dest > buffer) {
1593 #ifdef TOKEN_DEBUG
1594         if(currToken.tagName.length()) {
1595             qDebug( "unexpected token: %s, str: *%s*", currToken.tagName.deprecatedString().latin1(),DeprecatedConstString( buffer,dest-buffer ).deprecatedString().latin1() );
1596             ASSERT(0);
1597         }
1598
1599 #endif
1600         currToken.text = StringImpl::createStrippingNull(buffer, dest - buffer);
1601         if (currToken.tagName != commentAtom)
1602             currToken.tagName = textAtom;
1603     } else if (currToken.tagName == nullAtom) {
1604         currToken.reset();
1605         if (jsProxy)
1606             jsProxy->setEventHandlerLineno(lineno);
1607         return 0;
1608     }
1609
1610     dest = buffer;
1611
1612 #ifdef TOKEN_DEBUG
1613     DeprecatedString name = currToken.tagName.deprecatedString();
1614     DeprecatedString text;
1615     if(currToken.text)
1616         text = DeprecatedConstString(currToken.text->unicode(), currToken.text->length()).deprecatedString();
1617
1618     kdDebug( 6036 ) << "Token --> " << name << endl;
1619     if (currToken.flat)
1620         kdDebug( 6036 ) << "Token is FLAT!" << endl;
1621     if(!text.isNull())
1622         kdDebug( 6036 ) << "text: \"" << text << "\"" << endl;
1623     unsigned l = currToken.attrs ? currToken.attrs->length() : 0;
1624     if(l) {
1625         kdDebug( 6036 ) << "Attributes: " << l << endl;
1626         for (unsigned i = 0; i < l; ++i) {
1627             Attribute* c = currToken.attrs->attributeItem(i);
1628             kdDebug( 6036 ) << "    " << c->localName().deprecatedString()
1629                             << "=\"" << c->value().deprecatedString() << "\"" << endl;
1630         }
1631     }
1632     kdDebug( 6036 ) << endl;
1633 #endif
1634
1635     RefPtr<Node> n;
1636     
1637     if (!m_parserStopped) {
1638         if (inViewSourceMode())
1639             static_cast<HTMLViewSourceDocument*>(m_doc)->addViewSourceToken(&currToken);
1640         else
1641             // pass the token over to the parser, the parser DOES NOT delete the token
1642             n = parser->parseToken(&currToken);
1643     }
1644     currToken.reset();
1645     if (jsProxy)
1646         jsProxy->setEventHandlerLineno(0);
1647
1648     return n.release();
1649 }
1650
1651 HTMLTokenizer::~HTMLTokenizer()
1652 {
1653     ASSERT(!inWrite);
1654     reset();
1655     delete parser;
1656 }
1657
1658
1659 void HTMLTokenizer::enlargeBuffer(int len)
1660 {
1661     int newSize = max(size * 2, size + len);
1662     int oldOffset = dest - buffer;
1663     buffer = static_cast<UChar*>(fastRealloc(buffer, newSize * sizeof(UChar)));
1664     dest = buffer + oldOffset;
1665     size = newSize;
1666 }
1667
1668 void HTMLTokenizer::enlargeScriptBuffer(int len)
1669 {
1670     int newSize = max(scriptCodeMaxSize * 2, scriptCodeMaxSize + len);
1671     scriptCode = static_cast<UChar*>(fastRealloc(scriptCode, newSize * sizeof(UChar)));
1672     scriptCodeMaxSize = newSize;
1673 }
1674
1675 void HTMLTokenizer::notifyFinished(CachedResource*)
1676 {
1677 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1678     if (!m_doc->ownerElement())
1679         printf("script loaded at %d\n", m_doc->elapsedTime());
1680 #endif
1681
1682     ASSERT(!pendingScripts.isEmpty());
1683     bool finished = false;
1684     while (!finished && pendingScripts.head()->isLoaded()) {
1685 #ifdef TOKEN_DEBUG
1686         kdDebug( 6036 ) << "Finished loading an external script" << endl;
1687 #endif
1688         CachedScript* cs = pendingScripts.dequeue();
1689         ASSERT(cache()->disabled() || cs->accessCount() > 0);
1690
1691         String scriptSource = cs->script();
1692 #ifdef TOKEN_DEBUG
1693         kdDebug( 6036 ) << "External script is:" << endl << scriptSource.deprecatedString() << endl;
1694 #endif
1695         setSrc(SegmentedString());
1696
1697         // make sure we forget about the script before we execute the new one
1698         // infinite recursion might happen otherwise
1699         DeprecatedString cachedScriptUrl( cs->url().deprecatedString() );
1700         bool errorOccurred = cs->errorOccurred();
1701         cs->deref(this);
1702         RefPtr<Node> n = scriptNode.release();
1703
1704 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1705         if (!m_doc->ownerElement())
1706             printf("external script beginning execution at %d\n", m_doc->elapsedTime());
1707 #endif
1708
1709         if (errorOccurred)
1710             EventTargetNodeCast(n.get())->dispatchHTMLEvent(errorEvent, true, false);
1711         else {
1712             if (static_cast<HTMLScriptElement*>(n.get())->shouldExecuteAsJavaScript())
1713                 m_state = scriptExecution(scriptSource.deprecatedString(), m_state, cachedScriptUrl);
1714             EventTargetNodeCast(n.get())->dispatchHTMLEvent(loadEvent, false, false);
1715         }
1716
1717         // The state of pendingScripts.isEmpty() can change inside the scriptExecution()
1718         // call above, so test afterwards.
1719         finished = pendingScripts.isEmpty();
1720         if (finished) {
1721             m_state.setLoadingExtScript(false);
1722 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1723             if (!m_doc->ownerElement())
1724                 printf("external script finished execution at %d\n", m_doc->elapsedTime());
1725 #endif
1726         }
1727
1728         // 'm_requestingScript' is true when we are called synchronously from
1729         // scriptHandler(). In that case scriptHandler() will take care
1730         // of pendingSrc.
1731         if (!m_requestingScript) {
1732             SegmentedString rest = pendingSrc;
1733             pendingSrc.clear();
1734             write(rest, false);
1735             // we might be deleted at this point, do not
1736             // access any members.
1737         }
1738     }
1739 }
1740
1741 bool HTMLTokenizer::isWaitingForScripts() const
1742 {
1743     return m_state.loadingExtScript();
1744 }
1745
1746 void HTMLTokenizer::setSrc(const SegmentedString &source)
1747 {
1748     src = source;
1749 }
1750
1751 void parseHTMLDocumentFragment(const String& source, DocumentFragment* fragment)
1752 {
1753     HTMLTokenizer tok(fragment);
1754     tok.setForceSynchronous(true);
1755     tok.write(source, true);
1756     tok.finish();
1757     ASSERT(!tok.processingData());      // make sure we're done (see 3963151)
1758 }
1759
1760 UChar decodeNamedEntity(const char* name)
1761 {
1762     const Entity* e = findEntity(name, strlen(name));
1763     return e ? e->code : 0;
1764 }
1765
1766 }