#include "config.h"
#include "HTMLParser.h"
#include "CharacterNames.h"
#include "CSSPropertyNames.h"
#include "CSSValueKeywords.h"
#include "Comment.h"
#include "DocumentFragment.h"
#include "Frame.h"
#include "HTMLAnchorElement.h"
#include "HTMLBodyElement.h"
#include "HTMLDocument.h"
#include "HTMLDivElement.h"
#include "HTMLDListElement.h"
#include "HTMLElementFactory.h"
#include "HTMLFormElement.h"
#include "HTMLHeadElement.h"
#include "HTMLHRElement.h"
#include "HTMLHtmlElement.h"
#include "HTMLIsIndexElement.h"
#include "HTMLMapElement.h"
#include "HTMLNames.h"
#include "HTMLTableCellElement.h"
#include "HTMLTableRowElement.h"
#include "HTMLTableSectionElement.h"
#include "HTMLTokenizer.h"
#include "LocalizedStrings.h"
#include "Page.h"
#include "Settings.h"
#include "Text.h"
#include "WebCoreTelephoneParser.h"
namespace WebCore {
using namespace HTMLNames;
static const unsigned cMaxRedundantTagDepth = 20;
static const unsigned cResidualStyleMaxDepth = 200;
struct HTMLStackElem : Noncopyable {
HTMLStackElem(const AtomicString& t, int lvl, Node* n, bool r, HTMLStackElem* nx)
: tagName(t)
, level(lvl)
, strayTableContent(false)
, node(n)
, didRefNode(r)
, next(nx)
{
}
void derefNode()
{
if (didRefNode)
node->deref();
}
AtomicString tagName;
int level;
bool strayTableContent;
Node* node;
bool didRefNode;
HTMLStackElem* next;
};
HTMLParser::HTMLParser(HTMLDocument* doc, bool reportErrors)
: document(doc)
, current(doc)
, didRefCurrent(false)
, blockStack(0)
, head(0)
, inBody(false)
, haveContent(false)
, haveFrameSet(false)
, m_isParsingFragment(false)
, m_reportErrors(reportErrors)
, m_handlingResidualStyleAcrossBlocks(false)
, inStrayTableContent(0)
{
}
HTMLParser::HTMLParser(DocumentFragment* frag)
: document(frag->document())
, current(frag)
, didRefCurrent(true)
, blockStack(0)
, head(0)
, inBody(true)
, haveContent(false)
, haveFrameSet(false)
, m_isParsingFragment(true)
, m_reportErrors(false)
, m_handlingResidualStyleAcrossBlocks(false)
, inStrayTableContent(0)
{
if (frag)
frag->ref();
}
HTMLParser::~HTMLParser()
{
freeBlock();
if (didRefCurrent)
current->deref();
}
void HTMLParser::reset()
{
ASSERT(!m_isParsingFragment);
setCurrent(document);
freeBlock();
inBody = false;
haveFrameSet = false;
haveContent = false;
inStrayTableContent = 0;
m_currentFormElement = 0;
m_currentMapElement = 0;
head = 0;
m_isindexElement = 0;
m_skipModeTag = nullAtom;
}
void HTMLParser::setCurrent(Node* newCurrent)
{
bool didRefNewCurrent = newCurrent && newCurrent != document;
if (didRefNewCurrent)
newCurrent->ref();
if (didRefCurrent)
current->deref();
current = newCurrent;
didRefCurrent = didRefNewCurrent;
}
PassRefPtr<Node> HTMLParser::parseToken(Token* t)
{
if (!m_skipModeTag.isNull()) {
if (!t->beginTag && t->tagName == m_skipModeTag)
m_skipModeTag = nullAtom;
else if (current->localName() == t->tagName)
;
else
return 0;
}
if (t->isCloseTag(brTag) && document->inCompatMode()) {
reportError(MalformedBRError);
t->beginTag = true;
}
if (!t->beginTag) {
processCloseTag(t);
return 0;
}
if (t->tagName == textAtom && t->text) {
if (inBody && !skipMode() && current->localName() != styleTag && current->localName() != titleTag &&
current->localName() != scriptTag && !t->text->containsOnlyWhitespace())
haveContent = true;
RefPtr<Node> n;
String text = t->text.get();
unsigned charsLeft = text.length();
while (charsLeft) {
n = Text::createWithLengthLimit(document, text, charsLeft);
if (!insertNode(n.get(), t->flat))
return 0;
}
return n;
}
RefPtr<Node> n = getNode(t);
if (!n)
return 0;
if (n->isHTMLElement()) {
HTMLElement* e = static_cast<HTMLElement*>(n.get());
e->setAttributeMap(t->attrs.get());
if (e->endTagRequirement() == TagStatusOptional)
popBlock(t->tagName);
if (t->brokenXMLStyle && e->endTagRequirement() != TagStatusForbidden) {
if (t->tagName == scriptTag)
reportError(IncorrectXMLCloseScriptWarning);
else
reportError(IncorrectXMLSelfCloseError, &t->tagName);
}
}
if (!insertNode(n.get(), t->flat)) {
if (n->isElementNode()) {
Element* e = static_cast<Element*>(n.get());
e->setAttributeMap(0);
}
if (m_currentMapElement == n)
m_currentMapElement = 0;
if (m_currentFormElement == n)
m_currentFormElement = 0;
if (head == n)
head = 0;
return 0;
}
return n;
}
static bool isTableSection(Node* n)
{
return n->hasTagName(tbodyTag) || n->hasTagName(tfootTag) || n->hasTagName(theadTag);
}
static bool isTablePart(Node* n)
{
return n->hasTagName(trTag) || n->hasTagName(tdTag) || n->hasTagName(thTag) ||
isTableSection(n);
}
static bool isTableRelated(Node* n)
{
return n->hasTagName(tableTag) || isTablePart(n);
}
PassRefPtr<Text> HTMLParser::parseNextPhoneNumber(Text *inputText)
{
RefPtr<Text> outputText;
String s = inputText->toString();
unsigned len = s.length();
int phoneStartPos, phoneEndPos;
WebCoreFindTelephoneNumber(s.characters(), len, &phoneStartPos, &phoneEndPos);
if (phoneStartPos != -1 && phoneEndPos != -1){
String phone = s.substring(phoneStartPos, phoneEndPos - phoneStartPos + 1);
ExceptionCode ec = 0;
RefPtr<HTMLAnchorElement> myAnchor = static_cast<HTMLAnchorElement*>(document->createElementNS(xhtmlNamespaceURI, aTag.toString(), ec).get());
if (current->childAllowed(myAnchor.get())) {
RefPtr<Text> phoneText = (inputText)->splitText(phoneStartPos, ec);
RefPtr<Text> afterPhoneText = phoneText->splitText(phoneEndPos - phoneStartPos + 1, ec);
myAnchor->addChild(phoneText.get());
String phoneLink = "tel:";
phoneLink.append(phoneText->toString());
myAnchor->setHref(phoneLink);
current->appendChild(inputText, ec);
current->appendChild(myAnchor.get(), ec);
outputText = afterPhoneText;
}
}
return outputText.release();
}
PassRefPtr<Node> HTMLParser::parseTelephoneNumbers(Node *inputNode)
{
RefPtr<Node> outputNode = inputNode;
if (outputNode->isTextNode()) {
bool shouldParseTelephoneNumbers = true;
RefPtr<Node> parentNode = current;
do {
if (parentNode->isLink() || parentNode->isCommentNode() || parentNode->hasTagName(scriptTag) || (parentNode->isHTMLElement() && (static_cast<HTMLElement*>(parentNode.get()))->isGenericFormElement()) || parentNode->hasTagName(styleTag) || parentNode->hasTagName(ttTag) || parentNode->hasTagName(preTag) || parentNode->hasTagName(codeTag)) {
shouldParseTelephoneNumbers = false;
break;
}
parentNode = parentNode->parentNode();
} while (parentNode);
if (shouldParseTelephoneNumbers) {
if (current->isHTMLElement()) {
RefPtr<Node> linkifiedNodeRemnants;
do {
linkifiedNodeRemnants = parseNextPhoneNumber(static_cast<Text*>(outputNode.get()));
if (linkifiedNodeRemnants)
outputNode = linkifiedNodeRemnants;
} while (linkifiedNodeRemnants);
}
}
}
return outputNode.release();
}
bool HTMLParser::insertNode(Node* n, bool flat)
{
RefPtr<Node> protectNode(n);
const AtomicString& localName = n->localName();
int tagPriority = n->isHTMLElement() ? static_cast<HTMLElement*>(n)->tagPriority() : 0;
if (inStrayTableContent && localName == tableTag)
popBlock(tableTag);
bool parentAttached = current->attached();
if (parentAttached && document->isTelephoneNumberParsingEnabled()) {
protectNode = parseTelephoneNumbers(n).get();
n = protectNode.get();
}
Node* newNode = current->addChild(n);
if (!newNode)
return handleError(n, flat, localName, tagPriority);
if (tagPriority > 0 && !flat) {
if (newNode == current) {
ASSERT(localName == formTag);
reportError(FormInsideTablePartError, ¤t->localName());
} else {
pushBlock(localName, tagPriority);
ASSERT(!didRefCurrent);
newNode->ref();
current = newNode;
didRefCurrent = true;
}
if (parentAttached && !n->attached() && !m_isParsingFragment)
n->attach();
} else {
if (parentAttached && !n->attached() && !m_isParsingFragment)
n->attach();
n->finishParsingChildren();
}
return true;
}
bool HTMLParser::handleError(Node* n, bool flat, const AtomicString& localName, int tagPriority)
{
HTMLElement* e;
bool handled = false;
if (n->isHTMLElement()) {
HTMLElement* h = static_cast<HTMLElement*>(n);
if (h->hasLocalName(trTag) || h->hasLocalName(thTag) || h->hasLocalName(tdTag)) {
if (inStrayTableContent && !isTableRelated(current)) {
reportError(MisplacedTablePartError, &localName, ¤t->localName());
while (blockStack && !isTableRelated(current))
popOneBlock();
return insertNode(n);
}
} else if (h->hasLocalName(headTag)) {
if (!current->isDocumentNode() && !current->hasTagName(htmlTag)) {
reportError(MisplacedHeadError);
return false;
}
} else if (h->hasLocalName(metaTag) || h->hasLocalName(linkTag) || h->hasLocalName(baseTag)) {
bool createdHead = false;
if (!head) {
createHead();
createdHead = true;
}
if (head) {
if (!createdHead)
reportError(MisplacedHeadContentError, &localName, ¤t->localName());
if (head->addChild(n)) {
if (!n->attached() && !m_isParsingFragment)
n->attach();
return true;
} else
return false;
}
} else if (h->hasLocalName(htmlTag)) {
if (!current->isDocumentNode() ) {
if (document->documentElement()->hasTagName(htmlTag)) {
reportError(RedundantHTMLBodyError, &localName);
NamedAttrMap* map = static_cast<Element*>(n)->attributes(true);
Element* existingHTML = static_cast<Element*>(document->documentElement());
NamedAttrMap* bmap = existingHTML->attributes(false);
for (unsigned l = 0; map && l < map->length(); ++l) {
Attribute* it = map->attributeItem(l);
if (!bmap->getAttributeItem(it->name()))
existingHTML->setAttribute(it->name(), it->value());
}
}
return false;
}
} else if (h->hasLocalName(titleTag) || h->hasLocalName(styleTag)) {
bool createdHead = false;
if (!head) {
createHead();
createdHead = true;
}
if (head) {
Node* newNode = head->addChild(n);
if (!newNode) {
setSkipMode(h->tagQName());
return false;
}
if (!createdHead)
reportError(MisplacedHeadContentError, &localName, ¤t->localName());
pushBlock(localName, tagPriority);
setCurrent(newNode);
if (!n->attached() && !m_isParsingFragment)
n->attach();
return true;
}
if (inBody) {
setSkipMode(h->tagQName());
return false;
}
} else if (h->hasLocalName(bodyTag)) {
if (inBody && document->body()) {
reportError(RedundantHTMLBodyError, &localName);
NamedAttrMap* map = static_cast<Element*>(n)->attributes(true);
Element* existingBody = document->body();
NamedAttrMap* bmap = existingBody->attributes(false);
for (unsigned l = 0; map && l < map->length(); ++l) {
Attribute* it = map->attributeItem(l);
if (!bmap->getAttributeItem(it->name()))
existingBody->setAttribute(it->name(), it->value());
}
return false;
}
else if (!current->isDocumentNode())
return false;
} else if (h->hasLocalName(areaTag)) {
if (m_currentMapElement) {
reportError(MisplacedAreaError, ¤t->localName());
m_currentMapElement->addChild(n);
if (!n->attached() && !m_isParsingFragment)
n->attach();
handled = true;
return true;
}
return false;
} else if (h->hasLocalName(colgroupTag) || h->hasLocalName(captionTag)) {
if (isTableRelated(current)) {
while (blockStack && isTablePart(current))
popOneBlock();
return insertNode(n);
}
}
} else if (n->isCommentNode() && !head)
return false;
if (current->isHTMLElement()) {
HTMLElement* h = static_cast<HTMLElement*>(current);
const AtomicString& currentTagName = current->localName();
if (h->hasLocalName(htmlTag)) {
HTMLElement* elt = n->isHTMLElement() ? static_cast<HTMLElement*>(n) : 0;
if (elt && (elt->hasLocalName(scriptTag) || elt->hasLocalName(styleTag) ||
elt->hasLocalName(metaTag) || elt->hasLocalName(linkTag) ||
elt->hasLocalName(objectTag) || elt->hasLocalName(embedTag) ||
elt->hasLocalName(titleTag) || elt->hasLocalName(isindexTag) ||
elt->hasLocalName(baseTag))) {
if (!head) {
head = new HTMLHeadElement(document);
e = head;
insertNode(e);
handled = true;
}
} else {
if (n->isTextNode()) {
Text* t = static_cast<Text*>(n);
if (t->containsOnlyWhitespace())
return false;
}
if (!haveFrameSet) {
e = new HTMLBodyElement(document);
startBody();
insertNode(e);
handled = true;
} else
reportError(MisplacedFramesetContentError, &localName);
}
} else if (h->hasLocalName(headTag)) {
if (n->hasTagName(htmlTag))
return false;
else {
if (!haveFrameSet) {
popBlock(currentTagName);
e = new HTMLBodyElement(document);
startBody();
insertNode(e);
handled = true;
} else
reportError(MisplacedFramesetContentError, &localName);
}
} else if (h->hasLocalName(addressTag) || h->hasLocalName(dlTag) || h->hasLocalName(dtTag)
|| h->hasLocalName(fontTag) || h->hasLocalName(styleTag) || h->hasLocalName(titleTag)) {
reportError(MisplacedContentRetryError, &localName, ¤tTagName);
popBlock(currentTagName);
handled = true;
} else if (h->hasLocalName(captionTag)) {
reportError(MisplacedCaptionContentError, &localName);
popBlock(currentTagName);
if (isTablePart(n))
return insertNode(n, flat);
} else if (h->hasLocalName(tableTag) || h->hasLocalName(trTag) || isTableSection(h)) {
if (n->hasTagName(tableTag)) {
reportError(MisplacedTableError, ¤tTagName);
if (m_isParsingFragment && !h->hasLocalName(tableTag))
popBlock(h->localName());
popBlock(localName); handled = true; } else {
ExceptionCode ec = 0;
Node* node = current;
Node* parent = node->parentNode();
if (!parent)
return false;
Node* grandparent = parent->parentNode();
if (n->isTextNode() ||
(h->hasLocalName(trTag) &&
isTableSection(parent) && grandparent && grandparent->hasTagName(tableTag)) ||
((!n->hasTagName(tdTag) && !n->hasTagName(thTag) &&
!n->hasTagName(formTag) && !n->hasTagName(scriptTag)) && isTableSection(node) &&
parent->hasTagName(tableTag))) {
node = (node->hasTagName(tableTag)) ? node :
((node->hasTagName(trTag)) ? grandparent : parent);
if (!node)
return false;
Node* parent = node->parentNode();
if (!parent)
return false;
parent->insertBefore(n, node, ec);
if (!ec) {
reportError(StrayTableContentError, &localName, ¤tTagName);
if (n->isHTMLElement() && tagPriority > 0 &&
!flat && static_cast<HTMLElement*>(n)->endTagRequirement() != TagStatusForbidden)
{
pushBlock(localName, tagPriority);
setCurrent(n);
inStrayTableContent++;
blockStack->strayTableContent = true;
}
return true;
}
}
if (!ec) {
if (current->hasTagName(trTag)) {
reportError(TablePartRequiredError, &localName, &tdTag.localName());
e = new HTMLTableCellElement(tdTag, document);
} else if (current->hasTagName(tableTag)) {
e = new HTMLTableSectionElement(tbodyTag, document);
} else {
reportError(TablePartRequiredError, &localName, &trTag.localName());
e = new HTMLTableRowElement(document);
}
insertNode(e);
handled = true;
}
}
} else if (h->hasLocalName(objectTag)) {
reportError(MisplacedContentRetryError, &localName, ¤tTagName);
popBlock(objectTag);
handled = true;
} else if (h->hasLocalName(pTag) || isHeaderTag(currentTagName)) {
if (!isInline(n)) {
popBlock(currentTagName);
handled = true;
}
} else if (h->hasLocalName(optionTag) || h->hasLocalName(optgroupTag)) {
if (localName == optgroupTag) {
popBlock(currentTagName);
handled = true;
} else if (localName == selectTag) {
popBlock(localName);
}
} else if (h->hasLocalName(colgroupTag)) {
popBlock(currentTagName);
handled = true;
} else if (!h->hasLocalName(bodyTag)) {
if (isInline(current)) {
popInlineBlocks();
handled = true;
}
}
} else if (current->isDocumentNode()) {
if (n->isTextNode()) {
Text* t = static_cast<Text*>(n);
if (t->containsOnlyWhitespace())
return false;
}
if (!document->documentElement()) {
e = new HTMLHtmlElement(document);
insertNode(e);
handled = true;
}
}
if (!handled) {
reportError(IgnoredContentError, &localName, ¤t->localName());
return false;
}
return insertNode(n);
}
typedef bool (HTMLParser::*CreateErrorCheckFunc)(Token* t, RefPtr<Node>&);
typedef HashMap<AtomicStringImpl*, CreateErrorCheckFunc> FunctionMap;
bool HTMLParser::textCreateErrorCheck(Token* t, RefPtr<Node>& result)
{
result = new Text(document, t->text.get());
return false;
}
bool HTMLParser::commentCreateErrorCheck(Token* t, RefPtr<Node>& result)
{
result = new Comment(document, t->text.get());
return false;
}
bool HTMLParser::headCreateErrorCheck(Token* t, RefPtr<Node>& result)
{
if (!head || current->localName() == htmlTag) {
head = new HTMLHeadElement(document);
result = head;
} else
reportError(MisplacedHeadError);
return false;
}
bool HTMLParser::bodyCreateErrorCheck(Token* t, RefPtr<Node>& result)
{
if (haveFrameSet)
return false;
popBlock(headTag);
startBody();
return true;
}
bool HTMLParser::framesetCreateErrorCheck(Token* t, RefPtr<Node>& result)
{
popBlock(headTag);
if (inBody && !haveFrameSet && !haveContent) {
popBlock(bodyTag);
if (document->body())
document->body()->setAttribute(styleAttr, "display:none");
inBody = false;
}
if ((haveContent || haveFrameSet) && current->localName() == htmlTag)
return false;
haveFrameSet = true;
startBody();
return true;
}
bool HTMLParser::iframeCreateErrorCheck(Token* t, RefPtr<Node>& result)
{
setSkipMode(iframeTag);
return true;
}
bool HTMLParser::formCreateErrorCheck(Token* t, RefPtr<Node>& result)
{
if (!m_currentFormElement) {
m_currentFormElement = new HTMLFormElement(document);
result = m_currentFormElement;
}
return false;
}
bool HTMLParser::isindexCreateErrorCheck(Token* t, RefPtr<Node>& result)
{
RefPtr<Node> n = handleIsindex(t);
if (!inBody) {
m_isindexElement = n.release();
} else {
t->flat = true;
result = n.release();
}
return false;
}
bool HTMLParser::selectCreateErrorCheck(Token* t, RefPtr<Node>& result)
{
return true;
}
bool HTMLParser::ddCreateErrorCheck(Token* t, RefPtr<Node>& result)
{
popBlock(dtTag);
popBlock(ddTag);
return true;
}
bool HTMLParser::dtCreateErrorCheck(Token* t, RefPtr<Node>& result)
{
popBlock(ddTag);
popBlock(dtTag);
return true;
}
bool HTMLParser::nestedCreateErrorCheck(Token* t, RefPtr<Node>& result)
{
popBlock(t->tagName);
return true;
}
bool HTMLParser::nestedStyleCreateErrorCheck(Token* t, RefPtr<Node>& result)
{
return allowNestedRedundantTag(t->tagName);
}
bool HTMLParser::tableCellCreateErrorCheck(Token* t, RefPtr<Node>& result)
{
popBlock(tdTag);
popBlock(thTag);
return true;
}
bool HTMLParser::tableSectionCreateErrorCheck(Token* t, RefPtr<Node>& result)
{
popBlock(theadTag);
popBlock(tbodyTag);
popBlock(tfootTag);
return true;
}
bool HTMLParser::noembedCreateErrorCheck(Token* t, RefPtr<Node>& result)
{
setSkipMode(noembedTag);
return true;
}
bool HTMLParser::noframesCreateErrorCheck(Token* t, RefPtr<Node>& result)
{
setSkipMode(noframesTag);
return true;
}
bool HTMLParser::noscriptCreateErrorCheck(Token* t, RefPtr<Node>& result)
{
if (!m_isParsingFragment) {
Settings* settings = document->settings();
if (settings && settings->isJavaScriptEnabled())
setSkipMode(noscriptTag);
}
return true;
}
bool HTMLParser::mapCreateErrorCheck(Token* t, RefPtr<Node>& result)
{
m_currentMapElement = new HTMLMapElement(document);
result = m_currentMapElement;
return false;
}
PassRefPtr<Node> HTMLParser::getNode(Token* t)
{
static FunctionMap gFunctionMap;
if (gFunctionMap.isEmpty()) {
gFunctionMap.set(aTag.localName().impl(), &HTMLParser::nestedCreateErrorCheck);
gFunctionMap.set(bTag.localName().impl(), &HTMLParser::nestedStyleCreateErrorCheck);
gFunctionMap.set(bigTag.localName().impl(), &HTMLParser::nestedStyleCreateErrorCheck);
gFunctionMap.set(bodyTag.localName().impl(), &HTMLParser::bodyCreateErrorCheck);
gFunctionMap.set(buttonTag.localName().impl(), &HTMLParser::nestedCreateErrorCheck);
gFunctionMap.set(commentAtom.impl(), &HTMLParser::commentCreateErrorCheck);
gFunctionMap.set(ddTag.localName().impl(), &HTMLParser::ddCreateErrorCheck);
gFunctionMap.set(dtTag.localName().impl(), &HTMLParser::dtCreateErrorCheck);
gFunctionMap.set(formTag.localName().impl(), &HTMLParser::formCreateErrorCheck);
gFunctionMap.set(framesetTag.localName().impl(), &HTMLParser::framesetCreateErrorCheck);
gFunctionMap.set(headTag.localName().impl(), &HTMLParser::headCreateErrorCheck);
gFunctionMap.set(iTag.localName().impl(), &HTMLParser::nestedStyleCreateErrorCheck);
gFunctionMap.set(iframeTag.localName().impl(), &HTMLParser::iframeCreateErrorCheck);
gFunctionMap.set(isindexTag.localName().impl(), &HTMLParser::isindexCreateErrorCheck);
gFunctionMap.set(liTag.localName().impl(), &HTMLParser::nestedCreateErrorCheck);
gFunctionMap.set(mapTag.localName().impl(), &HTMLParser::mapCreateErrorCheck);
gFunctionMap.set(nobrTag.localName().impl(), &HTMLParser::nestedCreateErrorCheck);
gFunctionMap.set(noembedTag.localName().impl(), &HTMLParser::noembedCreateErrorCheck);
gFunctionMap.set(noframesTag.localName().impl(), &HTMLParser::noframesCreateErrorCheck);
gFunctionMap.set(noscriptTag.localName().impl(), &HTMLParser::noscriptCreateErrorCheck);
gFunctionMap.set(sTag.localName().impl(), &HTMLParser::nestedStyleCreateErrorCheck);
gFunctionMap.set(selectTag.localName().impl(), &HTMLParser::selectCreateErrorCheck);
gFunctionMap.set(smallTag.localName().impl(), &HTMLParser::nestedStyleCreateErrorCheck);
gFunctionMap.set(strikeTag.localName().impl(), &HTMLParser::nestedStyleCreateErrorCheck);
gFunctionMap.set(tbodyTag.localName().impl(), &HTMLParser::tableSectionCreateErrorCheck);
gFunctionMap.set(tdTag.localName().impl(), &HTMLParser::tableCellCreateErrorCheck);
gFunctionMap.set(textAtom.impl(), &HTMLParser::textCreateErrorCheck);
gFunctionMap.set(tfootTag.localName().impl(), &HTMLParser::tableSectionCreateErrorCheck);
gFunctionMap.set(thTag.localName().impl(), &HTMLParser::tableCellCreateErrorCheck);
gFunctionMap.set(theadTag.localName().impl(), &HTMLParser::tableSectionCreateErrorCheck);
gFunctionMap.set(trTag.localName().impl(), &HTMLParser::nestedCreateErrorCheck);
gFunctionMap.set(ttTag.localName().impl(), &HTMLParser::nestedStyleCreateErrorCheck);
gFunctionMap.set(uTag.localName().impl(), &HTMLParser::nestedStyleCreateErrorCheck);
}
bool proceed = true;
RefPtr<Node> result;
if (CreateErrorCheckFunc errorCheckFunc = gFunctionMap.get(t->tagName.impl()))
proceed = (this->*errorCheckFunc)(t, result);
if (proceed)
result = HTMLElementFactory::createHTMLElement(t->tagName, document, m_currentFormElement.get());
return result.release();
}
bool HTMLParser::allowNestedRedundantTag(const AtomicString& tagName)
{
unsigned i = 0;
for (HTMLStackElem* curr = blockStack;
i < cMaxRedundantTagDepth && curr && curr->tagName == tagName;
curr = curr->next, i++) { }
return i != cMaxRedundantTagDepth;
}
void HTMLParser::processCloseTag(Token* t)
{
if (t->tagName == htmlTag || t->tagName == bodyTag || t->tagName == commentAtom)
return;
bool checkForCloseTagErrors = true;
if (t->tagName == formTag && m_currentFormElement) {
m_currentFormElement = 0;
checkForCloseTagErrors = false;
} else if (t->tagName == mapTag)
m_currentMapElement = 0;
else if (t->tagName == pTag)
checkForCloseTagErrors = false;
HTMLStackElem* oldElem = blockStack;
popBlock(t->tagName, checkForCloseTagErrors);
if (oldElem == blockStack && t->tagName == pTag) {
t->beginTag = true;
parseToken(t);
popBlock(t->tagName);
reportError(StrayParagraphCloseError);
}
}
bool HTMLParser::isHeaderTag(const AtomicString& tagName)
{
static HashSet<AtomicStringImpl*> headerTags;
if (headerTags.isEmpty()) {
headerTags.add(h1Tag.localName().impl());
headerTags.add(h2Tag.localName().impl());
headerTags.add(h3Tag.localName().impl());
headerTags.add(h4Tag.localName().impl());
headerTags.add(h5Tag.localName().impl());
headerTags.add(h6Tag.localName().impl());
}
return headerTags.contains(tagName.impl());
}
bool HTMLParser::isInline(Node* node) const
{
if (node->isTextNode())
return true;
if (node->isHTMLElement()) {
HTMLElement* e = static_cast<HTMLElement*>(node);
if (e->hasLocalName(aTag) || e->hasLocalName(fontTag) || e->hasLocalName(ttTag) ||
e->hasLocalName(uTag) || e->hasLocalName(bTag) || e->hasLocalName(iTag) ||
e->hasLocalName(sTag) || e->hasLocalName(strikeTag) || e->hasLocalName(bigTag) ||
e->hasLocalName(smallTag) || e->hasLocalName(emTag) || e->hasLocalName(strongTag) ||
e->hasLocalName(dfnTag) || e->hasLocalName(codeTag) || e->hasLocalName(sampTag) ||
e->hasLocalName(kbdTag) || e->hasLocalName(varTag) || e->hasLocalName(citeTag) ||
e->hasLocalName(abbrTag) || e->hasLocalName(acronymTag) || e->hasLocalName(subTag) ||
e->hasLocalName(supTag) || e->hasLocalName(spanTag) || e->hasLocalName(nobrTag) ||
e->hasLocalName(noframesTag) || e->hasLocalName(nolayerTag) ||
e->hasLocalName(noembedTag))
return true;
if (e->hasLocalName(noscriptTag) && !m_isParsingFragment) {
Settings* settings = document->settings();
if (settings && settings->isJavaScriptEnabled())
return true;
}
}
return false;
}
bool HTMLParser::isResidualStyleTag(const AtomicString& tagName)
{
static HashSet<AtomicStringImpl*> residualStyleTags;
if (residualStyleTags.isEmpty()) {
residualStyleTags.add(aTag.localName().impl());
residualStyleTags.add(fontTag.localName().impl());
residualStyleTags.add(ttTag.localName().impl());
residualStyleTags.add(uTag.localName().impl());
residualStyleTags.add(bTag.localName().impl());
residualStyleTags.add(iTag.localName().impl());
residualStyleTags.add(sTag.localName().impl());
residualStyleTags.add(strikeTag.localName().impl());
residualStyleTags.add(bigTag.localName().impl());
residualStyleTags.add(smallTag.localName().impl());
residualStyleTags.add(emTag.localName().impl());
residualStyleTags.add(strongTag.localName().impl());
residualStyleTags.add(dfnTag.localName().impl());
residualStyleTags.add(codeTag.localName().impl());
residualStyleTags.add(sampTag.localName().impl());
residualStyleTags.add(kbdTag.localName().impl());
residualStyleTags.add(varTag.localName().impl());
residualStyleTags.add(nobrTag.localName().impl());
}
return residualStyleTags.contains(tagName.impl());
}
bool HTMLParser::isAffectedByResidualStyle(const AtomicString& tagName)
{
static HashSet<AtomicStringImpl*> unaffectedTags;
if (unaffectedTags.isEmpty()) {
unaffectedTags.add(bodyTag.localName().impl());
unaffectedTags.add(tableTag.localName().impl());
unaffectedTags.add(theadTag.localName().impl());
unaffectedTags.add(tbodyTag.localName().impl());
unaffectedTags.add(tfootTag.localName().impl());
unaffectedTags.add(trTag.localName().impl());
unaffectedTags.add(thTag.localName().impl());
unaffectedTags.add(tdTag.localName().impl());
unaffectedTags.add(captionTag.localName().impl());
unaffectedTags.add(colgroupTag.localName().impl());
unaffectedTags.add(colTag.localName().impl());
unaffectedTags.add(optionTag.localName().impl());
unaffectedTags.add(optgroupTag.localName().impl());
unaffectedTags.add(selectTag.localName().impl());
unaffectedTags.add(objectTag.localName().impl());
}
return !unaffectedTags.contains(tagName.impl());
}
void HTMLParser::handleResidualStyleCloseTagAcrossBlocks(HTMLStackElem* elem)
{
HTMLStackElem* maxElem = 0;
bool finished = false;
bool strayTableContent = elem->strayTableContent;
m_handlingResidualStyleAcrossBlocks = true;
while (!finished) {
ExceptionCode ec = 0;
HTMLStackElem* curr = blockStack;
HTMLStackElem* prev = 0;
HTMLStackElem* prevMaxElem = 0;
maxElem = 0;
finished = true;
while (curr && curr != elem) {
if (curr->level > elem->level) {
if (!isAffectedByResidualStyle(curr->tagName))
return;
if (maxElem)
finished = false;
maxElem = curr;
prevMaxElem = prev;
}
prev = curr;
curr = curr->next;
}
if (!curr || !maxElem)
return;
Node* residualElem = prev->node;
Node* blockElem = prevMaxElem ? prevMaxElem->node : current;
Node* parentElem = elem->node;
if (!parentElem->childAllowed(blockElem))
return;
if (maxElem->node->parentNode() != elem->node) {
HTMLStackElem* currElem = maxElem->next;
HTMLStackElem* prevElem = maxElem;
while (currElem != elem) {
HTMLStackElem* nextElem = currElem->next;
if (!isResidualStyleTag(currElem->tagName)) {
prevElem->next = nextElem;
prevElem->derefNode();
prevElem->node = currElem->node;
prevElem->didRefNode = currElem->didRefNode;
delete currElem;
}
else
prevElem = currElem;
currElem = nextElem;
}
RefPtr<Node> prevNode = 0;
currElem = maxElem;
while (currElem->node != residualElem) {
if (isResidualStyleTag(currElem->node->localName())) {
Node* currNode = currElem->node->cloneNode(false).releaseRef();
reportError(ResidualStyleError, &currNode->localName());
currElem->derefNode();
currElem->node = currNode;
currElem->didRefNode = true;
if (prevNode)
currNode->appendChild(prevNode, ec);
else parentElem = currNode;
prevNode = currNode;
}
currElem = currElem->next;
}
if (prevNode)
elem->node->appendChild(prevNode, ec); }
bool isBlockStillInTree = blockElem->parentNode();
if (isBlockStillInTree)
blockElem->parentNode()->removeChild(blockElem, ec);
Node* newNodePtr = 0;
ASSERT(finished || blockElem->firstChild());
if (blockElem->firstChild()) {
RefPtr<Node> newNode = residualElem->cloneNode(false); newNodePtr = newNode.get();
reportError(ResidualStyleError, &newNode->localName());
Node* currNode = blockElem->firstChild();
while (currNode) {
Node* nextNode = currNode->nextSibling();
newNode->appendChild(currNode, ec);
currNode = nextNode;
}
blockElem->appendChild(newNode.release(), ec);
}
if (isBlockStillInTree)
parentElem->appendChild(blockElem, ec);
HTMLStackElem* currElem = maxElem;
HTMLStackElem* prevElem = 0;
while (currElem != elem) {
prevElem = currElem;
currElem = currElem->next;
}
prevElem->next = elem->next;
prevElem->derefNode();
prevElem->node = elem->node;
prevElem->didRefNode = elem->didRefNode;
if (!finished) {
elem->next = maxElem;
elem->node = prevMaxElem->node;
elem->didRefNode = prevMaxElem->didRefNode;
elem->strayTableContent = false;
prevMaxElem->next = elem;
ASSERT(newNodePtr);
prevMaxElem->node = newNodePtr;
prevMaxElem->didRefNode = false;
} else
delete elem;
}
if (strayTableContent)
inStrayTableContent--;
HTMLStackElem* curr = blockStack;
HTMLStackElem* residualStyleStack = 0;
unsigned stackDepth = 1;
while (curr && curr != maxElem) {
if (isResidualStyleTag(curr->tagName) && stackDepth++ < cResidualStyleMaxDepth)
moveOneBlockToStack(residualStyleStack);
else
popOneBlock();
curr = blockStack;
}
reopenResidualStyleTags(residualStyleStack, 0);
m_handlingResidualStyleAcrossBlocks = false;
}
void HTMLParser::reopenResidualStyleTags(HTMLStackElem* elem, Node* malformedTableParent)
{
while (elem) {
RefPtr<Node> newNode = elem->node->cloneNode(false);
reportError(ResidualStyleError, &newNode->localName());
ExceptionCode ec = 0;
if (malformedTableParent)
malformedTableParent->insertBefore(newNode, malformedTableParent->lastChild(), ec);
else
current->appendChild(newNode, ec);
pushBlock(elem->tagName, elem->level);
blockStack->strayTableContent = malformedTableParent != 0;
if (blockStack->strayTableContent)
inStrayTableContent++;
malformedTableParent = 0;
setCurrent(newNode.get());
HTMLStackElem* next = elem->next;
elem->derefNode();
delete elem;
elem = next;
}
}
void HTMLParser::pushBlock(const AtomicString& tagName, int level)
{
current->beginParsingChildren();
blockStack = new HTMLStackElem(tagName, level, current, didRefCurrent, blockStack);
didRefCurrent = false;
}
void HTMLParser::popBlock(const AtomicString& tagName, bool reportErrors)
{
HTMLStackElem* elem = blockStack;
int maxLevel = 0;
while (elem && (elem->tagName != tagName)) {
if (maxLevel < elem->level)
maxLevel = elem->level;
elem = elem->next;
}
if (!elem) {
if (reportErrors)
reportError(StrayCloseTagError, &tagName, 0, true);
return;
}
if (maxLevel > elem->level) {
if (!isResidualStyleTag(tagName))
return;
return handleResidualStyleCloseTagAcrossBlocks(elem);
}
bool isAffectedByStyle = isAffectedByResidualStyle(elem->tagName);
HTMLStackElem* residualStyleStack = 0;
Node* malformedTableParent = 0;
elem = blockStack;
unsigned stackDepth = 1;
while (elem) {
if (elem->tagName == tagName) {
int strayTable = inStrayTableContent;
popOneBlock();
elem = 0;
if (strayTable && (inStrayTableContent < strayTable) && residualStyleStack) {
Node* curr = current;
while (curr && !curr->hasTagName(tableTag))
curr = curr->parentNode();
malformedTableParent = curr ? curr->parentNode() : 0;
}
}
else {
if (m_currentFormElement && elem->tagName == formTag)
m_currentFormElement->setMalformed(true);
if (isAffectedByStyle && isResidualStyleTag(elem->tagName) && stackDepth++ < cResidualStyleMaxDepth)
moveOneBlockToStack(residualStyleStack);
else
popOneBlock();
elem = blockStack;
}
}
reopenResidualStyleTags(residualStyleStack, malformedTableParent);
}
inline HTMLStackElem* HTMLParser::popOneBlockCommon()
{
HTMLStackElem* elem = blockStack;
if (current && elem->node != current)
current->finishParsingChildren();
blockStack = elem->next;
current = elem->node;
didRefCurrent = elem->didRefNode;
if (elem->strayTableContent)
inStrayTableContent--;
return elem;
}
void HTMLParser::popOneBlock()
{
Node* lastCurrent = current;
bool didRefLastCurrent = didRefCurrent;
delete popOneBlockCommon();
if (didRefLastCurrent)
lastCurrent->deref();
}
void HTMLParser::moveOneBlockToStack(HTMLStackElem*& head)
{
Node* lastCurrent = current;
bool didRefLastCurrent = didRefCurrent;
HTMLStackElem* elem = popOneBlockCommon();
elem->node = lastCurrent;
elem->didRefNode = didRefLastCurrent;
elem->next = head;
head = elem;
}
void HTMLParser::popInlineBlocks()
{
while (blockStack && isInline(current))
popOneBlock();
}
void HTMLParser::freeBlock()
{
while (blockStack)
popOneBlock();
}
void HTMLParser::createHead()
{
if (head || !document->documentElement())
return;
head = new HTMLHeadElement(document);
HTMLElement* body = document->body();
ExceptionCode ec = 0;
document->documentElement()->insertBefore(head, body, ec);
if (ec)
head = 0;
if (head && !body) {
pushBlock(head->localName(), head->tagPriority());
setCurrent(head);
}
}
PassRefPtr<Node> HTMLParser::handleIsindex(Token* t)
{
RefPtr<Node> n = new HTMLDivElement(document);
NamedMappedAttrMap* attrs = t->attrs.get();
RefPtr<HTMLIsIndexElement> isIndex = new HTMLIsIndexElement(document, m_currentFormElement.get());
isIndex->setAttributeMap(attrs);
isIndex->setAttribute(typeAttr, "khtml_isindex");
String text = searchableIndexIntroduction();
if (attrs) {
if (Attribute* a = attrs->getAttributeItem(promptAttr))
text = a->value().domString() + " ";
t->attrs = 0;
}
n->addChild(new HTMLHRElement(document));
n->addChild(new Text(document, text));
n->addChild(isIndex.release());
n->addChild(new HTMLHRElement(document));
return n.release();
}
void HTMLParser::startBody()
{
if (inBody)
return;
inBody = true;
if (m_isindexElement) {
insertNode(m_isindexElement.get(), true );
m_isindexElement = 0;
}
}
void HTMLParser::finished()
{
if (current && current->isDocumentNode() && !document->documentElement())
insertNode(new HTMLHtmlElement(document));
freeBlock();
setCurrent(0);
if (!m_isParsingFragment)
document->finishedParsing();
}
void HTMLParser::reportErrorToConsole(HTMLParserErrorCode errorCode, const AtomicString* tagName1, const AtomicString* tagName2, bool closeTags)
{
Frame* frame = document->frame();
if (!frame)
return;
Page* page = frame->page();
if (!page)
return;
HTMLTokenizer* htmlTokenizer = static_cast<HTMLTokenizer*>(document->tokenizer());
int lineNumber = htmlTokenizer->lineNumber() + 1;
AtomicString tag1;
AtomicString tag2;
if (tagName1) {
if (*tagName1 == "#text")
tag1 = "Text";
else if (*tagName1 == "#comment")
tag1 = "<!-- comment -->";
else
tag1 = (closeTags ? "</" : "<") + *tagName1 + ">";
}
if (tagName2) {
if (*tagName2 == "#text")
tag2 = "Text";
else if (*tagName2 == "#comment")
tag2 = "<!-- comment -->";
else
tag2 = (closeTags ? "</" : "<") + *tagName2 + ">";
}
const char* errorMsg = htmlParserErrorMessageTemplate(errorCode);
if (!errorMsg)
return;
String message;
message += errorMsg;
message.replace("%tag1", tag1);
message.replace("%tag2", tag2);
page->chrome()->addMessageToConsole(HTMLMessageSource, isWarning(errorCode) ? WarningMessageLevel: ErrorMessageLevel, message, lineNumber, document->url());
}
}