diff options
author | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2017-07-12 14:07:37 +0200 |
---|---|---|
committer | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2017-07-17 10:29:26 +0000 |
commit | ec02ee4181c49b61fce1c8fb99292dbb8139cc90 (patch) | |
tree | 25cde714b2b71eb639d1cd53f5a22e9ba76e14ef /chromium/third_party/WebKit/Source/core/xml | |
parent | bb09965444b5bb20b096a291445170876225268d (diff) |
BASELINE: Update Chromium to 59.0.3071.134
Change-Id: Id02ef6fb2204c5fd21668a1c3e6911c83b17585a
Reviewed-by: Alexandru Croitor <alexandru.croitor@qt.io>
Diffstat (limited to 'chromium/third_party/WebKit/Source/core/xml')
63 files changed, 3473 insertions, 3416 deletions
diff --git a/chromium/third_party/WebKit/Source/core/xml/DEPS b/chromium/third_party/WebKit/Source/core/xml/DEPS new file mode 100644 index 00000000000..eba58c8e277 --- /dev/null +++ b/chromium/third_party/WebKit/Source/core/xml/DEPS @@ -0,0 +1,4 @@ +include_rules = [ + # Use platform/wtf/ now (see crbug.com/691465). + "-wtf/", +] diff --git a/chromium/third_party/WebKit/Source/core/xml/DOMParser.cpp b/chromium/third_party/WebKit/Source/core/xml/DOMParser.cpp index 98a2a5bef74..865ab26c9ed 100644 --- a/chromium/third_party/WebKit/Source/core/xml/DOMParser.cpp +++ b/chromium/third_party/WebKit/Source/core/xml/DOMParser.cpp @@ -20,24 +20,28 @@ #include "core/xml/DOMParser.h" #include "core/dom/DOMImplementation.h" -#include "wtf/text/WTFString.h" +#include "platform/weborigin/SecurityOrigin.h" +#include "platform/wtf/text/WTFString.h" namespace blink { Document* DOMParser::parseFromString(const String& str, const String& type) { Document* doc = DOMImplementation::createDocument( - type, DocumentInit(KURL(), nullptr, m_contextDocument), false); - doc->setContent(str); - if (m_contextDocument) - doc->setSecurityOrigin(m_contextDocument->getSecurityOrigin()); + type, DocumentInit(KURL(), nullptr, context_document_), false); + doc->SetContent(str); + doc->SetMimeType(AtomicString(type)); + if (context_document_) { + doc->SetURL(context_document_->Url()); + doc->SetSecurityOrigin(context_document_->GetSecurityOrigin()); + } return doc; } DOMParser::DOMParser(Document& document) - : m_contextDocument(document.contextDocument()) {} + : context_document_(document.ContextDocument()) {} DEFINE_TRACE(DOMParser) { - visitor->trace(m_contextDocument); + visitor->Trace(context_document_); } } // namespace blink diff --git a/chromium/third_party/WebKit/Source/core/xml/DOMParser.h b/chromium/third_party/WebKit/Source/core/xml/DOMParser.h index d53bd8a1991..c3476260cde 100644 --- a/chromium/third_party/WebKit/Source/core/xml/DOMParser.h +++ b/chromium/third_party/WebKit/Source/core/xml/DOMParser.h @@ -22,7 +22,7 @@ #include "bindings/core/v8/ScriptWrappable.h" #include "platform/heap/Handle.h" -#include "wtf/Forward.h" +#include "platform/wtf/Forward.h" namespace blink { @@ -33,7 +33,7 @@ class DOMParser final : public GarbageCollected<DOMParser>, DEFINE_WRAPPERTYPEINFO(); public: - static DOMParser* create(Document& document) { + static DOMParser* Create(Document& document) { return new DOMParser(document); } @@ -44,7 +44,7 @@ class DOMParser final : public GarbageCollected<DOMParser>, private: explicit DOMParser(Document&); - WeakMember<Document> m_contextDocument; + WeakMember<Document> context_document_; }; } // namespace blink diff --git a/chromium/third_party/WebKit/Source/core/xml/DocumentXMLTreeViewer.cpp b/chromium/third_party/WebKit/Source/core/xml/DocumentXMLTreeViewer.cpp index c8394ee7729..9b2035918e7 100644 --- a/chromium/third_party/WebKit/Source/core/xml/DocumentXMLTreeViewer.cpp +++ b/chromium/third_party/WebKit/Source/core/xml/DocumentXMLTreeViewer.cpp @@ -15,20 +15,20 @@ namespace blink { -void transformDocumentToXMLTreeView(Document& document) { - String scriptString = loadResourceAsASCIIString("DocumentXMLTreeViewer.js"); - String cssString = loadResourceAsASCIIString("DocumentXMLTreeViewer.css"); +void TransformDocumentToXMLTreeView(Document& document) { + String script_string = LoadResourceAsASCIIString("DocumentXMLTreeViewer.js"); + String css_string = LoadResourceAsASCIIString("DocumentXMLTreeViewer.css"); HeapVector<ScriptSourceCode> sources; - sources.push_back(ScriptSourceCode(scriptString)); - v8::HandleScope handleScope(V8PerIsolateData::mainThreadIsolate()); + sources.push_back(ScriptSourceCode(script_string)); + v8::HandleScope handle_scope(V8PerIsolateData::MainThreadIsolate()); - document.frame()->script().executeScriptInIsolatedWorld( - WorldIdConstants::DocumentXMLTreeViewerWorldId, sources, nullptr); + document.GetFrame()->GetScriptController().ExecuteScriptInIsolatedWorld( + DOMWrapperWorld::kDocumentXMLTreeViewerWorldId, sources, nullptr); - Element* element = document.getElementById("xml-viewer-style"); + Element* element = document.GetElementById("xml-viewer-style"); if (element) { - element->setTextContent(cssString); + element->setTextContent(css_string); } } diff --git a/chromium/third_party/WebKit/Source/core/xml/DocumentXMLTreeViewer.h b/chromium/third_party/WebKit/Source/core/xml/DocumentXMLTreeViewer.h index 748e2baa6cb..d2c86f711b2 100644 --- a/chromium/third_party/WebKit/Source/core/xml/DocumentXMLTreeViewer.h +++ b/chromium/third_party/WebKit/Source/core/xml/DocumentXMLTreeViewer.h @@ -9,7 +9,7 @@ namespace blink { class Document; -void transformDocumentToXMLTreeView(Document&); +void TransformDocumentToXMLTreeView(Document&); } // namespace blink diff --git a/chromium/third_party/WebKit/Source/core/xml/DocumentXPathEvaluator.cpp b/chromium/third_party/WebKit/Source/core/xml/DocumentXPathEvaluator.cpp index 799a723e604..d76c397c3bb 100644 --- a/chromium/third_party/WebKit/Source/core/xml/DocumentXPathEvaluator.cpp +++ b/chromium/third_party/WebKit/Source/core/xml/DocumentXPathEvaluator.cpp @@ -34,12 +34,12 @@ namespace blink { DocumentXPathEvaluator::DocumentXPathEvaluator(Document& document) : Supplement<Document>(document) {} -DocumentXPathEvaluator& DocumentXPathEvaluator::from(Document& document) { +DocumentXPathEvaluator& DocumentXPathEvaluator::From(Document& document) { DocumentXPathEvaluator* cache = static_cast<DocumentXPathEvaluator*>( - Supplement<Document>::from(document, supplementName())); + Supplement<Document>::From(document, SupplementName())); if (!cache) { cache = new DocumentXPathEvaluator(document); - Supplement<Document>::provideTo(document, supplementName(), cache); + Supplement<Document>::ProvideTo(document, SupplementName(), cache); } return *cache; } @@ -48,39 +48,39 @@ XPathExpression* DocumentXPathEvaluator::createExpression( Document& document, const String& expression, XPathNSResolver* resolver, - ExceptionState& exceptionState) { - DocumentXPathEvaluator& suplement = from(document); - if (!suplement.m_xpathEvaluator) - suplement.m_xpathEvaluator = XPathEvaluator::create(); - return suplement.m_xpathEvaluator->createExpression(expression, resolver, - exceptionState); + ExceptionState& exception_state) { + DocumentXPathEvaluator& suplement = From(document); + if (!suplement.xpath_evaluator_) + suplement.xpath_evaluator_ = XPathEvaluator::Create(); + return suplement.xpath_evaluator_->createExpression(expression, resolver, + exception_state); } XPathNSResolver* DocumentXPathEvaluator::createNSResolver(Document& document, - Node* nodeResolver) { - DocumentXPathEvaluator& suplement = from(document); - if (!suplement.m_xpathEvaluator) - suplement.m_xpathEvaluator = XPathEvaluator::create(); - return suplement.m_xpathEvaluator->createNSResolver(nodeResolver); + Node* node_resolver) { + DocumentXPathEvaluator& suplement = From(document); + if (!suplement.xpath_evaluator_) + suplement.xpath_evaluator_ = XPathEvaluator::Create(); + return suplement.xpath_evaluator_->createNSResolver(node_resolver); } XPathResult* DocumentXPathEvaluator::evaluate(Document& document, const String& expression, - Node* contextNode, + Node* context_node, XPathNSResolver* resolver, unsigned short type, const ScriptValue&, - ExceptionState& exceptionState) { - DocumentXPathEvaluator& suplement = from(document); - if (!suplement.m_xpathEvaluator) - suplement.m_xpathEvaluator = XPathEvaluator::create(); - return suplement.m_xpathEvaluator->evaluate( - expression, contextNode, resolver, type, ScriptValue(), exceptionState); + ExceptionState& exception_state) { + DocumentXPathEvaluator& suplement = From(document); + if (!suplement.xpath_evaluator_) + suplement.xpath_evaluator_ = XPathEvaluator::Create(); + return suplement.xpath_evaluator_->evaluate( + expression, context_node, resolver, type, ScriptValue(), exception_state); } DEFINE_TRACE(DocumentXPathEvaluator) { - visitor->trace(m_xpathEvaluator); - Supplement<Document>::trace(visitor); + visitor->Trace(xpath_evaluator_); + Supplement<Document>::Trace(visitor); } } // namespace blink diff --git a/chromium/third_party/WebKit/Source/core/xml/DocumentXPathEvaluator.h b/chromium/third_party/WebKit/Source/core/xml/DocumentXPathEvaluator.h index 60ed54f42a1..e679c188b24 100644 --- a/chromium/third_party/WebKit/Source/core/xml/DocumentXPathEvaluator.h +++ b/chromium/third_party/WebKit/Source/core/xml/DocumentXPathEvaluator.h @@ -42,16 +42,16 @@ class DocumentXPathEvaluator final USING_GARBAGE_COLLECTED_MIXIN(DocumentXPathEvaluator); public: - static DocumentXPathEvaluator& from(Document&); + static DocumentXPathEvaluator& From(Document&); static XPathExpression* createExpression(Document&, const String& expression, XPathNSResolver*, ExceptionState&); - static XPathNSResolver* createNSResolver(Document&, Node* nodeResolver); + static XPathNSResolver* createNSResolver(Document&, Node* node_resolver); static XPathResult* evaluate(Document&, const String& expression, - Node* contextNode, + Node* context_node, XPathNSResolver*, unsigned short type, const ScriptValue&, @@ -62,9 +62,9 @@ class DocumentXPathEvaluator final private: explicit DocumentXPathEvaluator(Document&); - static const char* supplementName() { return "DocumentXPathEvaluator"; } + static const char* SupplementName() { return "DocumentXPathEvaluator"; } - Member<XPathEvaluator> m_xpathEvaluator; + Member<XPathEvaluator> xpath_evaluator_; }; } // namespace blink diff --git a/chromium/third_party/WebKit/Source/core/xml/DocumentXSLT.cpp b/chromium/third_party/WebKit/Source/core/xml/DocumentXSLT.cpp index a9d4eb103e2..e3bf7f5b87c 100644 --- a/chromium/third_party/WebKit/Source/core/xml/DocumentXSLT.cpp +++ b/chromium/third_party/WebKit/Source/core/xml/DocumentXSLT.cpp @@ -9,12 +9,13 @@ #include "bindings/core/v8/V8AbstractEventListener.h" #include "bindings/core/v8/V8Binding.h" #include "core/dom/Document.h" +#include "core/dom/ExecutionContext.h" #include "core/dom/Node.h" #include "core/dom/ProcessingInstruction.h" #include "core/events/Event.h" #include "core/events/EventListener.h" #include "core/frame/UseCounter.h" -#include "core/inspector/InspectorInstrumentation.h" +#include "core/probe/CoreProbes.h" #include "core/xml/XSLStyleSheet.h" #include "core/xml/XSLTProcessor.h" @@ -26,52 +27,52 @@ class DOMContentLoadedListener final USING_GARBAGE_COLLECTED_MIXIN(DOMContentLoadedListener); public: - static DOMContentLoadedListener* create(ScriptState* scriptState, + static DOMContentLoadedListener* Create(ScriptState* script_state, ProcessingInstruction* pi) { - return new DOMContentLoadedListener(scriptState, pi); + return new DOMContentLoadedListener(script_state, pi); } bool operator==(const EventListener&) const override { return true; } - virtual void handleEvent(ScriptState* scriptState, Event* event) { + virtual void HandleEvent(ScriptState* script_state, Event* event) { DCHECK(RuntimeEnabledFeatures::xsltEnabled()); DCHECK_EQ(event->type(), "DOMContentLoaded"); - ScriptState::Scope scope(scriptState); + ScriptState::Scope scope(script_state); - Document& document = *toDocument(scriptState->getExecutionContext()); - DCHECK(!document.parsing()); + Document& document = *ToDocument(ExecutionContext::From(script_state)); + DCHECK(!document.Parsing()); // Processing instruction (XML documents only). // We don't support linking to embedded CSS stylesheets, // see <https://bugs.webkit.org/show_bug.cgi?id=49281> for discussion. // Don't apply XSL transforms to already transformed documents. - if (DocumentXSLT::hasTransformSourceDocument(document)) + if (DocumentXSLT::HasTransformSourceDocument(document)) return; - ProcessingInstruction* pi = DocumentXSLT::findXSLStyleSheet(document); - if (!pi || pi != m_processingInstruction || pi->isLoading()) + ProcessingInstruction* pi = DocumentXSLT::FindXSLStyleSheet(document); + if (!pi || pi != processing_instruction_ || pi->IsLoading()) return; - DocumentXSLT::applyXSLTransform(document, pi); + DocumentXSLT::ApplyXSLTransform(document, pi); } - void detach() override { m_processingInstruction = nullptr; } + void Detach() override { processing_instruction_ = nullptr; } - EventListener* toEventListener() override { return this; } + EventListener* ToEventListener() override { return this; } DEFINE_INLINE_VIRTUAL_TRACE() { - visitor->trace(m_processingInstruction); - V8AbstractEventListener::trace(visitor); - ProcessingInstruction::DetachableEventListener::trace(visitor); + visitor->Trace(processing_instruction_); + V8AbstractEventListener::Trace(visitor); + ProcessingInstruction::DetachableEventListener::Trace(visitor); } private: - DOMContentLoadedListener(ScriptState* scriptState, ProcessingInstruction* pi) + DOMContentLoadedListener(ScriptState* script_state, ProcessingInstruction* pi) : V8AbstractEventListener(false, - scriptState->world(), - scriptState->isolate()), - m_processingInstruction(pi) {} + script_state->World(), + script_state->GetIsolate()), + processing_instruction_(pi) {} - virtual v8::Local<v8::Value> callListenerFunction(ScriptState*, + virtual v8::Local<v8::Value> CallListenerFunction(ScriptState*, v8::Local<v8::Value>, Event*) { NOTREACHED(); @@ -81,118 +82,118 @@ class DOMContentLoadedListener final // If this event listener is attached to a ProcessingInstruction, keep a // weak reference back to it. That ProcessingInstruction is responsible for // detaching itself and clear out the reference. - Member<ProcessingInstruction> m_processingInstruction; + Member<ProcessingInstruction> processing_instruction_; }; DocumentXSLT::DocumentXSLT(Document& document) - : Supplement<Document>(document), m_transformSourceDocument(nullptr) {} + : Supplement<Document>(document), transform_source_document_(nullptr) {} -void DocumentXSLT::applyXSLTransform(Document& document, +void DocumentXSLT::ApplyXSLTransform(Document& document, ProcessingInstruction* pi) { - DCHECK(!pi->isLoading()); - UseCounter::count(document, UseCounter::XSLProcessingInstruction); - XSLTProcessor* processor = XSLTProcessor::create(document); - processor->setXSLStyleSheet(toXSLStyleSheet(pi->sheet())); - String resultMIMEType; - String newSource; - String resultEncoding; - document.setParsingState(Document::Parsing); - if (!processor->transformToString(&document, resultMIMEType, newSource, - resultEncoding)) { - document.setParsingState(Document::FinishedParsing); + DCHECK(!pi->IsLoading()); + UseCounter::Count(document, UseCounter::kXSLProcessingInstruction); + XSLTProcessor* processor = XSLTProcessor::Create(document); + processor->SetXSLStyleSheet(ToXSLStyleSheet(pi->sheet())); + String result_mime_type; + String new_source; + String result_encoding; + document.SetParsingState(Document::kParsing); + if (!processor->TransformToString(&document, result_mime_type, new_source, + result_encoding)) { + document.SetParsingState(Document::kFinishedParsing); return; } // FIXME: If the transform failed we should probably report an error (like // Mozilla does). - LocalFrame* ownerFrame = document.frame(); - processor->createDocumentFromSource(newSource, resultEncoding, resultMIMEType, - &document, ownerFrame); - probe::frameDocumentUpdated(ownerFrame); - document.setParsingState(Document::FinishedParsing); + LocalFrame* owner_frame = document.GetFrame(); + processor->CreateDocumentFromSource(new_source, result_encoding, + result_mime_type, &document, owner_frame); + probe::frameDocumentUpdated(owner_frame); + document.SetParsingState(Document::kFinishedParsing); } -ProcessingInstruction* DocumentXSLT::findXSLStyleSheet(Document& document) { - for (Node* node = document.firstChild(); node; node = node->nextSibling()) { +ProcessingInstruction* DocumentXSLT::FindXSLStyleSheet(Document& document) { + for (Node* node = document.FirstChild(); node; node = node->nextSibling()) { if (node->getNodeType() != Node::kProcessingInstructionNode) continue; - ProcessingInstruction* pi = toProcessingInstruction(node); - if (pi->isXSL()) + ProcessingInstruction* pi = ToProcessingInstruction(node); + if (pi->IsXSL()) return pi; } return nullptr; } -bool DocumentXSLT::processingInstructionInsertedIntoDocument( +bool DocumentXSLT::ProcessingInstructionInsertedIntoDocument( Document& document, ProcessingInstruction* pi) { - if (!pi->isXSL()) + if (!pi->IsXSL()) return false; - if (!RuntimeEnabledFeatures::xsltEnabled() || !document.frame()) + if (!RuntimeEnabledFeatures::xsltEnabled() || !document.GetFrame()) return true; - ScriptState* scriptState = ScriptState::forMainWorld(document.frame()); - if (!scriptState) + ScriptState* script_state = ToScriptStateForMainWorld(document.GetFrame()); + if (!script_state) return false; DOMContentLoadedListener* listener = - DOMContentLoadedListener::create(scriptState, pi); + DOMContentLoadedListener::Create(script_state, pi); document.addEventListener(EventTypeNames::DOMContentLoaded, listener, false); - DCHECK(!pi->eventListenerForXSLT()); - pi->setEventListenerForXSLT(listener); + DCHECK(!pi->EventListenerForXSLT()); + pi->SetEventListenerForXSLT(listener); return true; } -bool DocumentXSLT::processingInstructionRemovedFromDocument( +bool DocumentXSLT::ProcessingInstructionRemovedFromDocument( Document& document, ProcessingInstruction* pi) { - if (!pi->isXSL()) + if (!pi->IsXSL()) return false; - if (!pi->eventListenerForXSLT()) + if (!pi->EventListenerForXSLT()) return true; DCHECK(RuntimeEnabledFeatures::xsltEnabled()); document.removeEventListener(EventTypeNames::DOMContentLoaded, - pi->eventListenerForXSLT(), false); - pi->clearEventListenerForXSLT(); + pi->EventListenerForXSLT(), false); + pi->ClearEventListenerForXSLT(); return true; } -bool DocumentXSLT::sheetLoaded(Document& document, ProcessingInstruction* pi) { - if (!pi->isXSL()) +bool DocumentXSLT::SheetLoaded(Document& document, ProcessingInstruction* pi) { + if (!pi->IsXSL()) return false; - if (RuntimeEnabledFeatures::xsltEnabled() && !document.parsing() && - !pi->isLoading() && !DocumentXSLT::hasTransformSourceDocument(document)) { - if (findXSLStyleSheet(document) == pi) - applyXSLTransform(document, pi); + if (RuntimeEnabledFeatures::xsltEnabled() && !document.Parsing() && + !pi->IsLoading() && !DocumentXSLT::HasTransformSourceDocument(document)) { + if (FindXSLStyleSheet(document) == pi) + ApplyXSLTransform(document, pi); } return true; } -const char* DocumentXSLT::supplementName() { +const char* DocumentXSLT::SupplementName() { return "DocumentXSLT"; } -bool DocumentXSLT::hasTransformSourceDocument(Document& document) { +bool DocumentXSLT::HasTransformSourceDocument(Document& document) { return static_cast<DocumentXSLT*>( - Supplement<Document>::from(document, supplementName())); + Supplement<Document>::From(document, SupplementName())); } -DocumentXSLT& DocumentXSLT::from(Document& document) { +DocumentXSLT& DocumentXSLT::From(Document& document) { DocumentXSLT* supplement = static_cast<DocumentXSLT*>( - Supplement<Document>::from(document, supplementName())); + Supplement<Document>::From(document, SupplementName())); if (!supplement) { supplement = new DocumentXSLT(document); - Supplement<Document>::provideTo(document, supplementName(), supplement); + Supplement<Document>::ProvideTo(document, SupplementName(), supplement); } return *supplement; } DEFINE_TRACE(DocumentXSLT) { - visitor->trace(m_transformSourceDocument); - Supplement<Document>::trace(visitor); + visitor->Trace(transform_source_document_); + Supplement<Document>::Trace(visitor); } } // namespace blink diff --git a/chromium/third_party/WebKit/Source/core/xml/DocumentXSLT.h b/chromium/third_party/WebKit/Source/core/xml/DocumentXSLT.h index 1b0971e61c5..527df8d7e2d 100644 --- a/chromium/third_party/WebKit/Source/core/xml/DocumentXSLT.h +++ b/chromium/third_party/WebKit/Source/core/xml/DocumentXSLT.h @@ -7,7 +7,7 @@ #include "core/dom/Document.h" #include "platform/heap/Handle.h" -#include "wtf/RefPtr.h" +#include "platform/wtf/RefPtr.h" namespace blink { @@ -20,35 +20,35 @@ class DocumentXSLT final : public GarbageCollected<DocumentXSLT>, USING_GARBAGE_COLLECTED_MIXIN(DocumentXSLT); public: - Document* transformSourceDocument() { - return m_transformSourceDocument.get(); + Document* TransformSourceDocument() { + return transform_source_document_.Get(); } - void setTransformSourceDocument(Document* document) { + void SetTransformSourceDocument(Document* document) { DCHECK(document); - m_transformSourceDocument = document; + transform_source_document_ = document; } - static DocumentXSLT& from(Document&); - static const char* supplementName(); + static DocumentXSLT& From(Document&); + static const char* SupplementName(); // The following static methods don't use any instance of DocumentXSLT. // They are just using DocumentXSLT namespace. - static void applyXSLTransform(Document&, ProcessingInstruction*); - static ProcessingInstruction* findXSLStyleSheet(Document&); - static bool processingInstructionInsertedIntoDocument(Document&, + static void ApplyXSLTransform(Document&, ProcessingInstruction*); + static ProcessingInstruction* FindXSLStyleSheet(Document&); + static bool ProcessingInstructionInsertedIntoDocument(Document&, ProcessingInstruction*); - static bool processingInstructionRemovedFromDocument(Document&, + static bool ProcessingInstructionRemovedFromDocument(Document&, ProcessingInstruction*); - static bool sheetLoaded(Document&, ProcessingInstruction*); - static bool hasTransformSourceDocument(Document&); + static bool SheetLoaded(Document&, ProcessingInstruction*); + static bool HasTransformSourceDocument(Document&); DECLARE_VIRTUAL_TRACE(); private: explicit DocumentXSLT(Document&); - Member<Document> m_transformSourceDocument; + Member<Document> transform_source_document_; }; } // namespace blink diff --git a/chromium/third_party/WebKit/Source/core/xml/NativeXPathNSResolver.cpp b/chromium/third_party/WebKit/Source/core/xml/NativeXPathNSResolver.cpp index 8b63d54cf84..6576fec9339 100644 --- a/chromium/third_party/WebKit/Source/core/xml/NativeXPathNSResolver.cpp +++ b/chromium/third_party/WebKit/Source/core/xml/NativeXPathNSResolver.cpp @@ -27,11 +27,11 @@ #include "core/XMLNames.h" #include "core/dom/Node.h" -#include "wtf/text/WTFString.h" +#include "platform/wtf/text/WTFString.h" namespace blink { -NativeXPathNSResolver::NativeXPathNSResolver(Node* node) : m_node(node) {} +NativeXPathNSResolver::NativeXPathNSResolver(Node* node) : node_(node) {} AtomicString NativeXPathNSResolver::lookupNamespaceURI(const String& prefix) { // This is not done by Node::lookupNamespaceURI as per the DOM3 Core spec, @@ -39,12 +39,12 @@ AtomicString NativeXPathNSResolver::lookupNamespaceURI(const String& prefix) { if (prefix == "xml") return XMLNames::xmlNamespaceURI; - return m_node ? m_node->lookupNamespaceURI(prefix) : nullAtom; + return node_ ? node_->lookupNamespaceURI(prefix) : g_null_atom; } DEFINE_TRACE(NativeXPathNSResolver) { - visitor->trace(m_node); - XPathNSResolver::trace(visitor); + visitor->Trace(node_); + XPathNSResolver::Trace(visitor); } } // namespace blink diff --git a/chromium/third_party/WebKit/Source/core/xml/NativeXPathNSResolver.h b/chromium/third_party/WebKit/Source/core/xml/NativeXPathNSResolver.h index 48ec3e7065e..898f64debc7 100644 --- a/chromium/third_party/WebKit/Source/core/xml/NativeXPathNSResolver.h +++ b/chromium/third_party/WebKit/Source/core/xml/NativeXPathNSResolver.h @@ -27,7 +27,7 @@ #define NativeXPathNSResolver_h #include "core/xml/XPathNSResolver.h" -#include "wtf/RefPtr.h" +#include "platform/wtf/RefPtr.h" namespace blink { @@ -35,7 +35,7 @@ class Node; class NativeXPathNSResolver final : public XPathNSResolver { public: - static NativeXPathNSResolver* create(Node* node) { + static NativeXPathNSResolver* Create(Node* node) { return new NativeXPathNSResolver(node); } @@ -46,7 +46,7 @@ class NativeXPathNSResolver final : public XPathNSResolver { private: explicit NativeXPathNSResolver(Node*); - Member<Node> m_node; + Member<Node> node_; }; } // namespace blink diff --git a/chromium/third_party/WebKit/Source/core/xml/XMLSerializer.cpp b/chromium/third_party/WebKit/Source/core/xml/XMLSerializer.cpp index 6b46ca6c5b5..c9af1ac1c53 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XMLSerializer.cpp +++ b/chromium/third_party/WebKit/Source/core/xml/XMLSerializer.cpp @@ -22,14 +22,15 @@ #include "core/xml/XMLSerializer.h" #include "core/editing/serializers/MarkupAccumulator.h" -#include "wtf/text/WTFString.h" +#include "platform/wtf/text/WTFString.h" namespace blink { String XMLSerializer::serializeToString(Node* root) { DCHECK(root); - MarkupAccumulator accumulator(DoNotResolveURLs, SerializationType::ForcedXML); - return serializeNodes<EditingStrategy>(accumulator, *root, IncludeNode); + MarkupAccumulator accumulator(kDoNotResolveURLs, + SerializationType::kForcedXML); + return SerializeNodes<EditingStrategy>(accumulator, *root, kIncludeNode); } } // namespace blink diff --git a/chromium/third_party/WebKit/Source/core/xml/XMLSerializer.h b/chromium/third_party/WebKit/Source/core/xml/XMLSerializer.h index 58ad817594b..c389f233186 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XMLSerializer.h +++ b/chromium/third_party/WebKit/Source/core/xml/XMLSerializer.h @@ -33,7 +33,7 @@ class XMLSerializer final : public GarbageCollected<XMLSerializer>, DEFINE_WRAPPERTYPEINFO(); public: - static XMLSerializer* create() { return new XMLSerializer; } + static XMLSerializer* Create() { return new XMLSerializer; } String serializeToString(Node*); diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathEvaluator.cpp b/chromium/third_party/WebKit/Source/core/xml/XPathEvaluator.cpp index 804436294e3..24fe9562c72 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XPathEvaluator.cpp +++ b/chromium/third_party/WebKit/Source/core/xml/XPathEvaluator.cpp @@ -41,34 +41,35 @@ using namespace XPath; XPathExpression* XPathEvaluator::createExpression( const String& expression, XPathNSResolver* resolver, - ExceptionState& exceptionState) { - return XPathExpression::createExpression(expression, resolver, - exceptionState); + ExceptionState& exception_state) { + return XPathExpression::CreateExpression(expression, resolver, + exception_state); } -XPathNSResolver* XPathEvaluator::createNSResolver(Node* nodeResolver) { - return NativeXPathNSResolver::create(nodeResolver); +XPathNSResolver* XPathEvaluator::createNSResolver(Node* node_resolver) { + return NativeXPathNSResolver::Create(node_resolver); } XPathResult* XPathEvaluator::evaluate(const String& expression, - Node* contextNode, + Node* context_node, XPathNSResolver* resolver, unsigned short type, const ScriptValue&, - ExceptionState& exceptionState) { - if (!isValidContextNode(contextNode)) { - exceptionState.throwDOMException( - NotSupportedError, "The node provided is '" + contextNode->nodeName() + - "', which is not a valid context node type."); + ExceptionState& exception_state) { + if (!IsValidContextNode(context_node)) { + exception_state.ThrowDOMException( + kNotSupportedError, "The node provided is '" + + context_node->nodeName() + + "', which is not a valid context node type."); return nullptr; } XPathExpression* expr = - createExpression(expression, resolver, exceptionState); - if (exceptionState.hadException()) + createExpression(expression, resolver, exception_state); + if (exception_state.HadException()) return nullptr; - return expr->evaluate(contextNode, type, ScriptValue(), exceptionState); + return expr->evaluate(context_node, type, ScriptValue(), exception_state); } } // namespace blink diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathEvaluator.h b/chromium/third_party/WebKit/Source/core/xml/XPathEvaluator.h index 313fd20377d..fe355809745 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XPathEvaluator.h +++ b/chromium/third_party/WebKit/Source/core/xml/XPathEvaluator.h @@ -44,14 +44,14 @@ class XPathEvaluator final : public GarbageCollected<XPathEvaluator>, DEFINE_WRAPPERTYPEINFO(); public: - static XPathEvaluator* create() { return new XPathEvaluator; } + static XPathEvaluator* Create() { return new XPathEvaluator; } XPathExpression* createExpression(const String& expression, XPathNSResolver*, ExceptionState&); - XPathNSResolver* createNSResolver(Node* nodeResolver); + XPathNSResolver* createNSResolver(Node* node_resolver); XPathResult* evaluate(const String& expression, - Node* contextNode, + Node* context_node, XPathNSResolver*, unsigned short type, const ScriptValue&, diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathExpression.cpp b/chromium/third_party/WebKit/Source/core/xml/XPathExpression.cpp index 5ced4e72795..7b83a38a349 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XPathExpression.cpp +++ b/chromium/third_party/WebKit/Source/core/xml/XPathExpression.cpp @@ -33,7 +33,7 @@ #include "core/xml/XPathParser.h" #include "core/xml/XPathResult.h" #include "core/xml/XPathUtil.h" -#include "wtf/text/WTFString.h" +#include "platform/wtf/text/WTFString.h" namespace blink { @@ -41,51 +41,53 @@ using namespace XPath; XPathExpression::XPathExpression() {} -XPathExpression* XPathExpression::createExpression( +XPathExpression* XPathExpression::CreateExpression( const String& expression, XPathNSResolver* resolver, - ExceptionState& exceptionState) { - XPathExpression* expr = XPathExpression::create(); + ExceptionState& exception_state) { + XPathExpression* expr = XPathExpression::Create(); Parser parser; - expr->m_topExpression = - parser.parseStatement(expression, resolver, exceptionState); - if (!expr->m_topExpression) + expr->top_expression_ = + parser.ParseStatement(expression, resolver, exception_state); + if (!expr->top_expression_) return nullptr; return expr; } DEFINE_TRACE(XPathExpression) { - visitor->trace(m_topExpression); + visitor->Trace(top_expression_); } -XPathResult* XPathExpression::evaluate(Node* contextNode, +XPathResult* XPathExpression::evaluate(Node* context_node, unsigned short type, const ScriptValue&, - ExceptionState& exceptionState) { - if (!isValidContextNode(contextNode)) { - exceptionState.throwDOMException( - NotSupportedError, "The node provided is '" + contextNode->nodeName() + - "', which is not a valid context node type."); + ExceptionState& exception_state) { + if (!IsValidContextNode(context_node)) { + exception_state.ThrowDOMException( + kNotSupportedError, "The node provided is '" + + context_node->nodeName() + + "', which is not a valid context node type."); return nullptr; } - EvaluationContext evaluationContext(*contextNode); - XPathResult* result = XPathResult::create( - evaluationContext, m_topExpression->evaluate(evaluationContext)); + EvaluationContext evaluation_context(*context_node); + XPathResult* result = XPathResult::Create( + evaluation_context, top_expression_->Evaluate(evaluation_context)); - if (evaluationContext.hadTypeConversionError) { + if (evaluation_context.had_type_conversion_error) { // It is not specified what to do if type conversion fails while evaluating // an expression. - exceptionState.throwDOMException( - SyntaxError, "Type conversion failed while evaluating the expression."); + exception_state.ThrowDOMException( + kSyntaxError, + "Type conversion failed while evaluating the expression."); return nullptr; } if (type != XPathResult::kAnyType) { - result->convertTo(type, exceptionState); - if (exceptionState.hadException()) + result->ConvertTo(type, exception_state); + if (exception_state.HadException()) return nullptr; } diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathExpression.h b/chromium/third_party/WebKit/Source/core/xml/XPathExpression.h index 2cd5daade74..5e22ca57963 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XPathExpression.h +++ b/chromium/third_party/WebKit/Source/core/xml/XPathExpression.h @@ -29,7 +29,7 @@ #include "bindings/core/v8/ScriptWrappable.h" #include "platform/heap/Handle.h" -#include "wtf/Forward.h" +#include "platform/wtf/Forward.h" namespace blink { @@ -48,12 +48,12 @@ class XPathExpression : public GarbageCollected<XPathExpression>, DEFINE_WRAPPERTYPEINFO(); public: - static XPathExpression* create() { return new XPathExpression; } + static XPathExpression* Create() { return new XPathExpression; } - static XPathExpression* createExpression(const String& expression, + static XPathExpression* CreateExpression(const String& expression, XPathNSResolver*, ExceptionState&); - XPathResult* evaluate(Node* contextNode, + XPathResult* evaluate(Node* context_node, unsigned short type, const ScriptValue&, ExceptionState&); @@ -63,7 +63,7 @@ class XPathExpression : public GarbageCollected<XPathExpression>, private: XPathExpression(); - Member<XPath::Expression> m_topExpression; + Member<XPath::Expression> top_expression_; }; } // namespace blink diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathExpressionNode.cpp b/chromium/third_party/WebKit/Source/core/xml/XPathExpressionNode.cpp index 85777e0130e..4514fae70ae 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XPathExpressionNode.cpp +++ b/chromium/third_party/WebKit/Source/core/xml/XPathExpressionNode.cpp @@ -26,24 +26,27 @@ #include "core/xml/XPathExpressionNode.h" -#include "wtf/StdLibExtras.h" +#include "platform/wtf/StdLibExtras.h" namespace blink { namespace XPath { -EvaluationContext::EvaluationContext(Node& contextNode) - : node(contextNode), size(1), position(1), hadTypeConversionError(false) {} +EvaluationContext::EvaluationContext(Node& context_node) + : node(context_node), + size(1), + position(1), + had_type_conversion_error(false) {} Expression::Expression() - : m_isContextNodeSensitive(false), - m_isContextPositionSensitive(false), - m_isContextSizeSensitive(false) {} + : is_context_node_sensitive_(false), + is_context_position_sensitive_(false), + is_context_size_sensitive_(false) {} Expression::~Expression() {} DEFINE_TRACE(Expression) { - visitor->trace(m_subExpressions); - ParseNode::trace(visitor); + visitor->Trace(sub_expressions_); + ParseNode::Trace(visitor); } } // namespace XPath diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathExpressionNode.h b/chromium/third_party/WebKit/Source/core/xml/XPathExpressionNode.h index 5892c299f6b..3fae436834d 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XPathExpressionNode.h +++ b/chromium/third_party/WebKit/Source/core/xml/XPathExpressionNode.h @@ -30,9 +30,9 @@ #include "core/CoreExport.h" #include "core/dom/Node.h" #include "core/xml/XPathValue.h" -#include "wtf/HashMap.h" -#include "wtf/Vector.h" -#include "wtf/text/StringHash.h" +#include "platform/wtf/HashMap.h" +#include "platform/wtf/Vector.h" +#include "platform/wtf/text/StringHash.h" namespace blink { @@ -47,9 +47,9 @@ struct CORE_EXPORT EvaluationContext { Member<Node> node; unsigned long size; unsigned long position; - HashMap<String, String> variableBindings; + HashMap<String, String> variable_bindings; - bool hadTypeConversionError; + bool had_type_conversion_error; }; class CORE_EXPORT ParseNode : public GarbageCollectedFinalized<ParseNode> { @@ -66,46 +66,46 @@ class CORE_EXPORT Expression : public ParseNode { ~Expression() override; DECLARE_VIRTUAL_TRACE(); - virtual Value evaluate(EvaluationContext&) const = 0; + virtual Value Evaluate(EvaluationContext&) const = 0; - void addSubExpression(Expression* expr) { - m_isContextNodeSensitive |= expr->m_isContextNodeSensitive; - m_isContextPositionSensitive |= expr->m_isContextPositionSensitive; - m_isContextSizeSensitive |= expr->m_isContextSizeSensitive; - m_subExpressions.push_back(expr); + void AddSubExpression(Expression* expr) { + is_context_node_sensitive_ |= expr->is_context_node_sensitive_; + is_context_position_sensitive_ |= expr->is_context_position_sensitive_; + is_context_size_sensitive_ |= expr->is_context_size_sensitive_; + sub_expressions_.push_back(expr); } - bool isContextNodeSensitive() const { return m_isContextNodeSensitive; } - bool isContextPositionSensitive() const { - return m_isContextPositionSensitive; + bool IsContextNodeSensitive() const { return is_context_node_sensitive_; } + bool IsContextPositionSensitive() const { + return is_context_position_sensitive_; } - bool isContextSizeSensitive() const { return m_isContextSizeSensitive; } - void setIsContextNodeSensitive(bool value) { - m_isContextNodeSensitive = value; + bool IsContextSizeSensitive() const { return is_context_size_sensitive_; } + void SetIsContextNodeSensitive(bool value) { + is_context_node_sensitive_ = value; } - void setIsContextPositionSensitive(bool value) { - m_isContextPositionSensitive = value; + void SetIsContextPositionSensitive(bool value) { + is_context_position_sensitive_ = value; } - void setIsContextSizeSensitive(bool value) { - m_isContextSizeSensitive = value; + void SetIsContextSizeSensitive(bool value) { + is_context_size_sensitive_ = value; } - virtual Value::Type resultType() const = 0; + virtual Value::Type ResultType() const = 0; protected: - unsigned subExprCount() const { return m_subExpressions.size(); } - Expression* subExpr(unsigned i) { return m_subExpressions[i].get(); } - const Expression* subExpr(unsigned i) const { - return m_subExpressions[i].get(); + unsigned SubExprCount() const { return sub_expressions_.size(); } + Expression* SubExpr(unsigned i) { return sub_expressions_[i].Get(); } + const Expression* SubExpr(unsigned i) const { + return sub_expressions_[i].Get(); } private: - HeapVector<Member<Expression>> m_subExpressions; + HeapVector<Member<Expression>> sub_expressions_; // Evaluation details that can be used for optimization. - bool m_isContextNodeSensitive; - bool m_isContextPositionSensitive; - bool m_isContextSizeSensitive; + bool is_context_node_sensitive_; + bool is_context_position_sensitive_; + bool is_context_size_sensitive_; }; } // namespace XPath diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathFunctions.cpp b/chromium/third_party/WebKit/Source/core/xml/XPathFunctions.cpp index e4cfea2e4d5..6edc970cc6c 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XPathFunctions.cpp +++ b/chromium/third_party/WebKit/Source/core/xml/XPathFunctions.cpp @@ -34,8 +34,8 @@ #include "core/dom/TreeScope.h" #include "core/xml/XPathUtil.h" #include "core/xml/XPathValue.h" -#include "wtf/MathExtras.h" -#include "wtf/text/StringBuilder.h" +#include "platform/wtf/MathExtras.h" +#include "platform/wtf/text/StringBuilder.h" #include <algorithm> #include <limits> @@ -43,218 +43,218 @@ namespace blink { namespace XPath { -static inline bool isWhitespace(UChar c) { +static inline bool IsWhitespace(UChar c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t'; } #define DEFINE_FUNCTION_CREATOR(Class) \ - static Function* create##Class() { return new Class; } + static Function* Create##Class() { return new Class; } class Interval { public: - static const int Inf = -1; + static const int kInf = -1; Interval(); Interval(int value); Interval(int min, int max); - bool contains(int value) const; + bool Contains(int value) const; private: - int m_min; - int m_max; + int min_; + int max_; }; struct FunctionRec { typedef Function* (*FactoryFn)(); - FactoryFn factoryFn; + FactoryFn factory_fn; Interval args; }; -static HashMap<String, FunctionRec>* functionMap; +static HashMap<String, FunctionRec>* g_function_map; class FunLast final : public Function { - Value evaluate(EvaluationContext&) const override; - Value::Type resultType() const override { return Value::NumberValue; } + Value Evaluate(EvaluationContext&) const override; + Value::Type ResultType() const override { return Value::kNumberValue; } public: - FunLast() { setIsContextSizeSensitive(true); } + FunLast() { SetIsContextSizeSensitive(true); } }; class FunPosition final : public Function { - Value evaluate(EvaluationContext&) const override; - Value::Type resultType() const override { return Value::NumberValue; } + Value Evaluate(EvaluationContext&) const override; + Value::Type ResultType() const override { return Value::kNumberValue; } public: - FunPosition() { setIsContextPositionSensitive(true); } + FunPosition() { SetIsContextPositionSensitive(true); } }; class FunCount final : public Function { - Value evaluate(EvaluationContext&) const override; - Value::Type resultType() const override { return Value::NumberValue; } + Value Evaluate(EvaluationContext&) const override; + Value::Type ResultType() const override { return Value::kNumberValue; } }; class FunId final : public Function { - Value evaluate(EvaluationContext&) const override; - Value::Type resultType() const override { return Value::NodeSetValue; } + Value Evaluate(EvaluationContext&) const override; + Value::Type ResultType() const override { return Value::kNodeSetValue; } }; class FunLocalName final : public Function { - Value evaluate(EvaluationContext&) const override; - Value::Type resultType() const override { return Value::StringValue; } + Value Evaluate(EvaluationContext&) const override; + Value::Type ResultType() const override { return Value::kStringValue; } public: FunLocalName() { - setIsContextNodeSensitive(true); + SetIsContextNodeSensitive(true); } // local-name() with no arguments uses context node. }; class FunNamespaceURI final : public Function { - Value evaluate(EvaluationContext&) const override; - Value::Type resultType() const override { return Value::StringValue; } + Value Evaluate(EvaluationContext&) const override; + Value::Type ResultType() const override { return Value::kStringValue; } public: FunNamespaceURI() { - setIsContextNodeSensitive(true); + SetIsContextNodeSensitive(true); } // namespace-uri() with no arguments uses context node. }; class FunName final : public Function { - Value evaluate(EvaluationContext&) const override; - Value::Type resultType() const override { return Value::StringValue; } + Value Evaluate(EvaluationContext&) const override; + Value::Type ResultType() const override { return Value::kStringValue; } public: FunName() { - setIsContextNodeSensitive(true); + SetIsContextNodeSensitive(true); } // name() with no arguments uses context node. }; class FunString final : public Function { - Value evaluate(EvaluationContext&) const override; - Value::Type resultType() const override { return Value::StringValue; } + Value Evaluate(EvaluationContext&) const override; + Value::Type ResultType() const override { return Value::kStringValue; } public: FunString() { - setIsContextNodeSensitive(true); + SetIsContextNodeSensitive(true); } // string() with no arguments uses context node. }; class FunConcat final : public Function { - Value evaluate(EvaluationContext&) const override; - Value::Type resultType() const override { return Value::StringValue; } + Value Evaluate(EvaluationContext&) const override; + Value::Type ResultType() const override { return Value::kStringValue; } }; class FunStartsWith final : public Function { - Value evaluate(EvaluationContext&) const override; - Value::Type resultType() const override { return Value::BooleanValue; } + Value Evaluate(EvaluationContext&) const override; + Value::Type ResultType() const override { return Value::kBooleanValue; } }; class FunContains final : public Function { - Value evaluate(EvaluationContext&) const override; - Value::Type resultType() const override { return Value::BooleanValue; } + Value Evaluate(EvaluationContext&) const override; + Value::Type ResultType() const override { return Value::kBooleanValue; } }; class FunSubstringBefore final : public Function { - Value evaluate(EvaluationContext&) const override; - Value::Type resultType() const override { return Value::StringValue; } + Value Evaluate(EvaluationContext&) const override; + Value::Type ResultType() const override { return Value::kStringValue; } }; class FunSubstringAfter final : public Function { - Value evaluate(EvaluationContext&) const override; - Value::Type resultType() const override { return Value::StringValue; } + Value Evaluate(EvaluationContext&) const override; + Value::Type ResultType() const override { return Value::kStringValue; } }; class FunSubstring final : public Function { - Value evaluate(EvaluationContext&) const override; - Value::Type resultType() const override { return Value::StringValue; } + Value Evaluate(EvaluationContext&) const override; + Value::Type ResultType() const override { return Value::kStringValue; } }; class FunStringLength final : public Function { - Value evaluate(EvaluationContext&) const override; - Value::Type resultType() const override { return Value::NumberValue; } + Value Evaluate(EvaluationContext&) const override; + Value::Type ResultType() const override { return Value::kNumberValue; } public: FunStringLength() { - setIsContextNodeSensitive(true); + SetIsContextNodeSensitive(true); } // string-length() with no arguments uses context node. }; class FunNormalizeSpace final : public Function { - Value evaluate(EvaluationContext&) const override; - Value::Type resultType() const override { return Value::StringValue; } + Value Evaluate(EvaluationContext&) const override; + Value::Type ResultType() const override { return Value::kStringValue; } public: FunNormalizeSpace() { - setIsContextNodeSensitive(true); + SetIsContextNodeSensitive(true); } // normalize-space() with no arguments uses context node. }; class FunTranslate final : public Function { - Value evaluate(EvaluationContext&) const override; - Value::Type resultType() const override { return Value::StringValue; } + Value Evaluate(EvaluationContext&) const override; + Value::Type ResultType() const override { return Value::kStringValue; } }; class FunBoolean final : public Function { - Value evaluate(EvaluationContext&) const override; - Value::Type resultType() const override { return Value::BooleanValue; } + Value Evaluate(EvaluationContext&) const override; + Value::Type ResultType() const override { return Value::kBooleanValue; } }; class FunNot final : public Function { - Value evaluate(EvaluationContext&) const override; - Value::Type resultType() const override { return Value::BooleanValue; } + Value Evaluate(EvaluationContext&) const override; + Value::Type ResultType() const override { return Value::kBooleanValue; } }; class FunTrue final : public Function { - Value evaluate(EvaluationContext&) const override; - Value::Type resultType() const override { return Value::BooleanValue; } + Value Evaluate(EvaluationContext&) const override; + Value::Type ResultType() const override { return Value::kBooleanValue; } }; class FunFalse final : public Function { - Value evaluate(EvaluationContext&) const override; - Value::Type resultType() const override { return Value::BooleanValue; } + Value Evaluate(EvaluationContext&) const override; + Value::Type ResultType() const override { return Value::kBooleanValue; } }; class FunLang final : public Function { - Value evaluate(EvaluationContext&) const override; - Value::Type resultType() const override { return Value::BooleanValue; } + Value Evaluate(EvaluationContext&) const override; + Value::Type ResultType() const override { return Value::kBooleanValue; } public: FunLang() { - setIsContextNodeSensitive(true); + SetIsContextNodeSensitive(true); } // lang() always works on context node. }; class FunNumber final : public Function { - Value evaluate(EvaluationContext&) const override; - Value::Type resultType() const override { return Value::NumberValue; } + Value Evaluate(EvaluationContext&) const override; + Value::Type ResultType() const override { return Value::kNumberValue; } public: FunNumber() { - setIsContextNodeSensitive(true); + SetIsContextNodeSensitive(true); } // number() with no arguments uses context node. }; class FunSum final : public Function { - Value evaluate(EvaluationContext&) const override; - Value::Type resultType() const override { return Value::NumberValue; } + Value Evaluate(EvaluationContext&) const override; + Value::Type ResultType() const override { return Value::kNumberValue; } }; class FunFloor final : public Function { - Value evaluate(EvaluationContext&) const override; - Value::Type resultType() const override { return Value::NumberValue; } + Value Evaluate(EvaluationContext&) const override; + Value::Type ResultType() const override { return Value::kNumberValue; } }; class FunCeiling final : public Function { - Value evaluate(EvaluationContext&) const override; - Value::Type resultType() const override { return Value::NumberValue; } + Value Evaluate(EvaluationContext&) const override; + Value::Type ResultType() const override { return Value::kNumberValue; } }; class FunRound final : public Function { - Value evaluate(EvaluationContext&) const override; - Value::Type resultType() const override { return Value::NumberValue; } + Value Evaluate(EvaluationContext&) const override; + Value::Type ResultType() const override { return Value::kNumberValue; } public: - static double round(double); + static double Round(double); }; DEFINE_FUNCTION_CREATOR(FunLast) @@ -290,268 +290,268 @@ DEFINE_FUNCTION_CREATOR(FunRound) #undef DEFINE_FUNCTION_CREATOR -inline Interval::Interval() : m_min(Inf), m_max(Inf) {} +inline Interval::Interval() : min_(kInf), max_(kInf) {} -inline Interval::Interval(int value) : m_min(value), m_max(value) {} +inline Interval::Interval(int value) : min_(value), max_(value) {} -inline Interval::Interval(int min, int max) : m_min(min), m_max(max) {} +inline Interval::Interval(int min, int max) : min_(min), max_(max) {} -inline bool Interval::contains(int value) const { - if (m_min == Inf && m_max == Inf) +inline bool Interval::Contains(int value) const { + if (min_ == kInf && max_ == kInf) return true; - if (m_min == Inf) - return value <= m_max; + if (min_ == kInf) + return value <= max_; - if (m_max == Inf) - return value >= m_min; + if (max_ == kInf) + return value >= min_; - return value >= m_min && value <= m_max; + return value >= min_ && value <= max_; } -void Function::setArguments(HeapVector<Member<Expression>>& args) { - DCHECK(!subExprCount()); +void Function::SetArguments(HeapVector<Member<Expression>>& args) { + DCHECK(!SubExprCount()); // Some functions use context node as implicit argument, so when explicit // arguments are added, they may no longer be context node sensitive. - if (m_name != "lang" && !args.isEmpty()) - setIsContextNodeSensitive(false); + if (name_ != "lang" && !args.IsEmpty()) + SetIsContextNodeSensitive(false); for (Expression* arg : args) - addSubExpression(arg); + AddSubExpression(arg); } -Value FunLast::evaluate(EvaluationContext& context) const { +Value FunLast::Evaluate(EvaluationContext& context) const { return context.size; } -Value FunPosition::evaluate(EvaluationContext& context) const { +Value FunPosition::Evaluate(EvaluationContext& context) const { return context.position; } -Value FunId::evaluate(EvaluationContext& context) const { - Value a = arg(0)->evaluate(context); - StringBuilder idList; // A whitespace-separated list of IDs +Value FunId::Evaluate(EvaluationContext& context) const { + Value a = Arg(0)->Evaluate(context); + StringBuilder id_list; // A whitespace-separated list of IDs - if (a.isNodeSet()) { - for (const auto& node : a.toNodeSet(&context)) { - idList.append(stringValue(node)); - idList.append(' '); + if (a.IsNodeSet()) { + for (const auto& node : a.ToNodeSet(&context)) { + id_list.Append(StringValue(node)); + id_list.Append(' '); } } else { - idList.append(a.toString()); + id_list.Append(a.ToString()); } - TreeScope& contextScope = context.node->treeScope(); - NodeSet* result(NodeSet::create()); - HeapHashSet<Member<Node>> resultSet; + TreeScope& context_scope = context.node->GetTreeScope(); + NodeSet* result(NodeSet::Create()); + HeapHashSet<Member<Node>> result_set; - unsigned startPos = 0; - unsigned length = idList.length(); + unsigned start_pos = 0; + unsigned length = id_list.length(); while (true) { - while (startPos < length && isWhitespace(idList[startPos])) - ++startPos; + while (start_pos < length && IsWhitespace(id_list[start_pos])) + ++start_pos; - if (startPos == length) + if (start_pos == length) break; - size_t endPos = startPos; - while (endPos < length && !isWhitespace(idList[endPos])) - ++endPos; + size_t end_pos = start_pos; + while (end_pos < length && !IsWhitespace(id_list[end_pos])) + ++end_pos; // If there are several nodes with the same id, id() should return the first // one. In WebKit, getElementById behaves so, too, although its behavior in // this case is formally undefined. - Node* node = contextScope.getElementById( - AtomicString(idList.substring(startPos, endPos - startPos))); - if (node && resultSet.insert(node).isNewEntry) - result->append(node); + Node* node = context_scope.GetElementById( + AtomicString(id_list.Substring(start_pos, end_pos - start_pos))); + if (node && result_set.insert(node).is_new_entry) + result->Append(node); - startPos = endPos; + start_pos = end_pos; } - result->markSorted(false); + result->MarkSorted(false); - return Value(result, Value::adopt); + return Value(result, Value::kAdopt); } -static inline String expandedNameLocalPart(Node* node) { +static inline String ExpandedNameLocalPart(Node* node) { // The local part of an XPath expanded-name matches DOM local name for most // node types, except for namespace nodes and processing instruction nodes. // But note that Blink does not support namespace nodes. switch (node->getNodeType()) { case Node::kElementNode: - return toElement(node)->localName(); + return ToElement(node)->localName(); case Node::kAttributeNode: - return toAttr(node)->localName(); + return ToAttr(node)->localName(); case Node::kProcessingInstructionNode: - return toProcessingInstruction(node)->target(); + return ToProcessingInstruction(node)->target(); default: return String(); } } -static inline String expandedNamespaceURI(Node* node) { +static inline String ExpandedNamespaceURI(Node* node) { switch (node->getNodeType()) { case Node::kElementNode: - return toElement(node)->namespaceURI(); + return ToElement(node)->namespaceURI(); case Node::kAttributeNode: - return toAttr(node)->namespaceURI(); + return ToAttr(node)->namespaceURI(); default: return String(); } } -static inline String expandedName(Node* node) { +static inline String ExpandedName(Node* node) { AtomicString prefix; switch (node->getNodeType()) { case Node::kElementNode: - prefix = toElement(node)->prefix(); + prefix = ToElement(node)->prefix(); break; case Node::kAttributeNode: - prefix = toAttr(node)->prefix(); + prefix = ToAttr(node)->prefix(); break; default: break; } - return prefix.isEmpty() ? expandedNameLocalPart(node) - : prefix + ":" + expandedNameLocalPart(node); + return prefix.IsEmpty() ? ExpandedNameLocalPart(node) + : prefix + ":" + ExpandedNameLocalPart(node); } -Value FunLocalName::evaluate(EvaluationContext& context) const { - if (argCount() > 0) { - Value a = arg(0)->evaluate(context); - if (!a.isNodeSet()) +Value FunLocalName::Evaluate(EvaluationContext& context) const { + if (ArgCount() > 0) { + Value a = Arg(0)->Evaluate(context); + if (!a.IsNodeSet()) return ""; - Node* node = a.toNodeSet(&context).firstNode(); - return node ? expandedNameLocalPart(node) : ""; + Node* node = a.ToNodeSet(&context).FirstNode(); + return node ? ExpandedNameLocalPart(node) : ""; } - return expandedNameLocalPart(context.node.get()); + return ExpandedNameLocalPart(context.node.Get()); } -Value FunNamespaceURI::evaluate(EvaluationContext& context) const { - if (argCount() > 0) { - Value a = arg(0)->evaluate(context); - if (!a.isNodeSet()) +Value FunNamespaceURI::Evaluate(EvaluationContext& context) const { + if (ArgCount() > 0) { + Value a = Arg(0)->Evaluate(context); + if (!a.IsNodeSet()) return ""; - Node* node = a.toNodeSet(&context).firstNode(); - return node ? expandedNamespaceURI(node) : ""; + Node* node = a.ToNodeSet(&context).FirstNode(); + return node ? ExpandedNamespaceURI(node) : ""; } - return expandedNamespaceURI(context.node.get()); + return ExpandedNamespaceURI(context.node.Get()); } -Value FunName::evaluate(EvaluationContext& context) const { - if (argCount() > 0) { - Value a = arg(0)->evaluate(context); - if (!a.isNodeSet()) +Value FunName::Evaluate(EvaluationContext& context) const { + if (ArgCount() > 0) { + Value a = Arg(0)->Evaluate(context); + if (!a.IsNodeSet()) return ""; - Node* node = a.toNodeSet(&context).firstNode(); - return node ? expandedName(node) : ""; + Node* node = a.ToNodeSet(&context).FirstNode(); + return node ? ExpandedName(node) : ""; } - return expandedName(context.node.get()); + return ExpandedName(context.node.Get()); } -Value FunCount::evaluate(EvaluationContext& context) const { - Value a = arg(0)->evaluate(context); +Value FunCount::Evaluate(EvaluationContext& context) const { + Value a = Arg(0)->Evaluate(context); - return double(a.toNodeSet(&context).size()); + return double(a.ToNodeSet(&context).size()); } -Value FunString::evaluate(EvaluationContext& context) const { - if (!argCount()) - return Value(context.node.get()).toString(); - return arg(0)->evaluate(context).toString(); +Value FunString::Evaluate(EvaluationContext& context) const { + if (!ArgCount()) + return Value(context.node.Get()).ToString(); + return Arg(0)->Evaluate(context).ToString(); } -Value FunConcat::evaluate(EvaluationContext& context) const { +Value FunConcat::Evaluate(EvaluationContext& context) const { StringBuilder result; - result.reserveCapacity(1024); + result.ReserveCapacity(1024); - unsigned count = argCount(); + unsigned count = ArgCount(); for (unsigned i = 0; i < count; ++i) { - String str(arg(i)->evaluate(context).toString()); - result.append(str); + String str(Arg(i)->Evaluate(context).ToString()); + result.Append(str); } - return result.toString(); + return result.ToString(); } -Value FunStartsWith::evaluate(EvaluationContext& context) const { - String s1 = arg(0)->evaluate(context).toString(); - String s2 = arg(1)->evaluate(context).toString(); +Value FunStartsWith::Evaluate(EvaluationContext& context) const { + String s1 = Arg(0)->Evaluate(context).ToString(); + String s2 = Arg(1)->Evaluate(context).ToString(); - if (s2.isEmpty()) + if (s2.IsEmpty()) return true; - return s1.startsWith(s2); + return s1.StartsWith(s2); } -Value FunContains::evaluate(EvaluationContext& context) const { - String s1 = arg(0)->evaluate(context).toString(); - String s2 = arg(1)->evaluate(context).toString(); +Value FunContains::Evaluate(EvaluationContext& context) const { + String s1 = Arg(0)->Evaluate(context).ToString(); + String s2 = Arg(1)->Evaluate(context).ToString(); - if (s2.isEmpty()) + if (s2.IsEmpty()) return true; - return s1.contains(s2) != 0; + return s1.Contains(s2) != 0; } -Value FunSubstringBefore::evaluate(EvaluationContext& context) const { - String s1 = arg(0)->evaluate(context).toString(); - String s2 = arg(1)->evaluate(context).toString(); +Value FunSubstringBefore::Evaluate(EvaluationContext& context) const { + String s1 = Arg(0)->Evaluate(context).ToString(); + String s2 = Arg(1)->Evaluate(context).ToString(); - if (s2.isEmpty()) + if (s2.IsEmpty()) return ""; - size_t i = s1.find(s2); + size_t i = s1.Find(s2); if (i == kNotFound) return ""; - return s1.left(i); + return s1.Left(i); } -Value FunSubstringAfter::evaluate(EvaluationContext& context) const { - String s1 = arg(0)->evaluate(context).toString(); - String s2 = arg(1)->evaluate(context).toString(); +Value FunSubstringAfter::Evaluate(EvaluationContext& context) const { + String s1 = Arg(0)->Evaluate(context).ToString(); + String s2 = Arg(1)->Evaluate(context).ToString(); - size_t i = s1.find(s2); + size_t i = s1.Find(s2); if (i == kNotFound) return ""; - return s1.substring(i + s2.length()); + return s1.Substring(i + s2.length()); } // Returns |value| clamped to the range [lo, hi]. // TODO(dominicc): Replace with std::clamp when C++17 is allowed // per <https://chromium-cpp.appspot.com/> -static double clamp(const double value, const double lo, const double hi) { +static double Clamp(const double value, const double lo, const double hi) { return std::min(hi, std::max(lo, value)); } // Computes the 1-based start and end (exclusive) string indices for // substring. This is all the positions [1, maxLen (inclusive)] where // start <= position < start + len -static std::pair<unsigned, unsigned> computeSubstringStartEnd(double start, +static std::pair<unsigned, unsigned> ComputeSubstringStartEnd(double start, double len, - double maxLen) { - DCHECK(std::isfinite(maxLen)); + double max_len) { + DCHECK(std::isfinite(max_len)); const double end = start + len; if (std::isnan(start) || std::isnan(end)) return std::make_pair(1, 1); // Neither start nor end are NaN, but may still be +/- Inf - const double clampedStart = clamp(start, 1, maxLen + 1); - const double clampedEnd = clamp(end, clampedStart, maxLen + 1); - return std::make_pair(static_cast<unsigned>(clampedStart), - static_cast<unsigned>(clampedEnd)); + const double clamped_start = Clamp(start, 1, max_len + 1); + const double clamped_end = Clamp(end, clamped_start, max_len + 1); + return std::make_pair(static_cast<unsigned>(clamped_start), + static_cast<unsigned>(clamped_end)); } // substring(string, number pos, number? len) @@ -561,134 +561,136 @@ static std::pair<unsigned, unsigned> computeSubstringStartEnd(double start, // XPath's bespoke rounding function, round. // // <https://www.w3.org/TR/xpath/#function-substring> -Value FunSubstring::evaluate(EvaluationContext& context) const { - String sourceString = arg(0)->evaluate(context).toString(); - const double pos = FunRound::round(arg(1)->evaluate(context).toNumber()); - const double len = argCount() == 3 - ? FunRound::round(arg(2)->evaluate(context).toNumber()) +Value FunSubstring::Evaluate(EvaluationContext& context) const { + String source_string = Arg(0)->Evaluate(context).ToString(); + const double pos = FunRound::Round(Arg(1)->Evaluate(context).ToNumber()); + const double len = ArgCount() == 3 + ? FunRound::Round(Arg(2)->Evaluate(context).ToNumber()) : std::numeric_limits<double>::infinity(); - const auto bounds = computeSubstringStartEnd(pos, len, sourceString.length()); + const auto bounds = + ComputeSubstringStartEnd(pos, len, source_string.length()); if (bounds.second <= bounds.first) return ""; - return sourceString.substring(bounds.first - 1, bounds.second - bounds.first); + return source_string.Substring(bounds.first - 1, + bounds.second - bounds.first); } -Value FunStringLength::evaluate(EvaluationContext& context) const { - if (!argCount()) - return Value(context.node.get()).toString().length(); - return arg(0)->evaluate(context).toString().length(); +Value FunStringLength::Evaluate(EvaluationContext& context) const { + if (!ArgCount()) + return Value(context.node.Get()).ToString().length(); + return Arg(0)->Evaluate(context).ToString().length(); } -Value FunNormalizeSpace::evaluate(EvaluationContext& context) const { - if (!argCount()) { - String s = Value(context.node.get()).toString(); - return s.simplifyWhiteSpace(); +Value FunNormalizeSpace::Evaluate(EvaluationContext& context) const { + if (!ArgCount()) { + String s = Value(context.node.Get()).ToString(); + return s.SimplifyWhiteSpace(); } - String s = arg(0)->evaluate(context).toString(); - return s.simplifyWhiteSpace(); + String s = Arg(0)->Evaluate(context).ToString(); + return s.SimplifyWhiteSpace(); } -Value FunTranslate::evaluate(EvaluationContext& context) const { - String s1 = arg(0)->evaluate(context).toString(); - String s2 = arg(1)->evaluate(context).toString(); - String s3 = arg(2)->evaluate(context).toString(); +Value FunTranslate::Evaluate(EvaluationContext& context) const { + String s1 = Arg(0)->Evaluate(context).ToString(); + String s2 = Arg(1)->Evaluate(context).ToString(); + String s3 = Arg(2)->Evaluate(context).ToString(); StringBuilder result; for (unsigned i1 = 0; i1 < s1.length(); ++i1) { UChar ch = s1[i1]; - size_t i2 = s2.find(ch); + size_t i2 = s2.Find(ch); if (i2 == kNotFound) - result.append(ch); + result.Append(ch); else if (i2 < s3.length()) - result.append(s3[i2]); + result.Append(s3[i2]); } - return result.toString(); + return result.ToString(); } -Value FunBoolean::evaluate(EvaluationContext& context) const { - return arg(0)->evaluate(context).toBoolean(); +Value FunBoolean::Evaluate(EvaluationContext& context) const { + return Arg(0)->Evaluate(context).ToBoolean(); } -Value FunNot::evaluate(EvaluationContext& context) const { - return !arg(0)->evaluate(context).toBoolean(); +Value FunNot::Evaluate(EvaluationContext& context) const { + return !Arg(0)->Evaluate(context).ToBoolean(); } -Value FunTrue::evaluate(EvaluationContext&) const { +Value FunTrue::Evaluate(EvaluationContext&) const { return true; } -Value FunLang::evaluate(EvaluationContext& context) const { - String lang = arg(0)->evaluate(context).toString(); +Value FunLang::Evaluate(EvaluationContext& context) const { + String lang = Arg(0)->Evaluate(context).ToString(); - const Attribute* languageAttribute = nullptr; - Node* node = context.node.get(); + const Attribute* language_attribute = nullptr; + Node* node = context.node.Get(); while (node) { - if (node->isElementNode()) { - Element* element = toElement(node); - languageAttribute = element->attributes().find(XMLNames::langAttr); + if (node->IsElementNode()) { + Element* element = ToElement(node); + language_attribute = element->Attributes().Find(XMLNames::langAttr); } - if (languageAttribute) + if (language_attribute) break; node = node->parentNode(); } - if (!languageAttribute) + if (!language_attribute) return false; - String langValue = languageAttribute->value(); + String lang_value = language_attribute->Value(); while (true) { - if (equalIgnoringCase(langValue, lang)) + if (DeprecatedEqualIgnoringCase(lang_value, lang)) return true; // Remove suffixes one by one. - size_t index = langValue.reverseFind('-'); + size_t index = lang_value.ReverseFind('-'); if (index == kNotFound) break; - langValue = langValue.left(index); + lang_value = lang_value.Left(index); } return false; } -Value FunFalse::evaluate(EvaluationContext&) const { +Value FunFalse::Evaluate(EvaluationContext&) const { return false; } -Value FunNumber::evaluate(EvaluationContext& context) const { - if (!argCount()) - return Value(context.node.get()).toNumber(); - return arg(0)->evaluate(context).toNumber(); +Value FunNumber::Evaluate(EvaluationContext& context) const { + if (!ArgCount()) + return Value(context.node.Get()).ToNumber(); + return Arg(0)->Evaluate(context).ToNumber(); } -Value FunSum::evaluate(EvaluationContext& context) const { - Value a = arg(0)->evaluate(context); - if (!a.isNodeSet()) +Value FunSum::Evaluate(EvaluationContext& context) const { + Value a = Arg(0)->Evaluate(context); + if (!a.IsNodeSet()) return 0.0; double sum = 0.0; - const NodeSet& nodes = a.toNodeSet(&context); + const NodeSet& nodes = a.ToNodeSet(&context); // To be really compliant, we should sort the node-set, as floating point // addition is not associative. However, this is unlikely to ever become a // practical issue, and sorting is slow. for (const auto& node : nodes) - sum += Value(stringValue(node)).toNumber(); + sum += Value(StringValue(node)).ToNumber(); return sum; } -Value FunFloor::evaluate(EvaluationContext& context) const { - return floor(arg(0)->evaluate(context).toNumber()); +Value FunFloor::Evaluate(EvaluationContext& context) const { + return floor(Arg(0)->Evaluate(context).ToNumber()); } -Value FunCeiling::evaluate(EvaluationContext& context) const { - return ceil(arg(0)->evaluate(context).toNumber()); +Value FunCeiling::Evaluate(EvaluationContext& context) const { + return ceil(Arg(0)->Evaluate(context).ToNumber()); } -double FunRound::round(double val) { +double FunRound::Round(double val) { if (!std::isnan(val) && !std::isinf(val)) { if (std::signbit(val) && val >= -0.5) val *= 0; // negative zero @@ -698,8 +700,8 @@ double FunRound::round(double val) { return val; } -Value FunRound::evaluate(EvaluationContext& context) const { - return round(arg(0)->evaluate(context).toNumber()); +Value FunRound::Evaluate(EvaluationContext& context) const { + return Round(Arg(0)->Evaluate(context).ToNumber()); } struct FunctionMapping { @@ -707,64 +709,64 @@ struct FunctionMapping { FunctionRec function; }; -static void createFunctionMap() { - DCHECK(!functionMap); +static void CreateFunctionMap() { + DCHECK(!g_function_map); const FunctionMapping functions[] = { - {"boolean", {&createFunBoolean, 1}}, - {"ceiling", {&createFunCeiling, 1}}, - {"concat", {&createFunConcat, Interval(2, Interval::Inf)}}, - {"contains", {&createFunContains, 2}}, - {"count", {&createFunCount, 1}}, - {"false", {&createFunFalse, 0}}, - {"floor", {&createFunFloor, 1}}, - {"id", {&createFunId, 1}}, - {"lang", {&createFunLang, 1}}, - {"last", {&createFunLast, 0}}, - {"local-name", {&createFunLocalName, Interval(0, 1)}}, - {"name", {&createFunName, Interval(0, 1)}}, - {"namespace-uri", {&createFunNamespaceURI, Interval(0, 1)}}, - {"normalize-space", {&createFunNormalizeSpace, Interval(0, 1)}}, - {"not", {&createFunNot, 1}}, - {"number", {&createFunNumber, Interval(0, 1)}}, - {"position", {&createFunPosition, 0}}, - {"round", {&createFunRound, 1}}, - {"starts-with", {&createFunStartsWith, 2}}, - {"string", {&createFunString, Interval(0, 1)}}, - {"string-length", {&createFunStringLength, Interval(0, 1)}}, - {"substring", {&createFunSubstring, Interval(2, 3)}}, - {"substring-after", {&createFunSubstringAfter, 2}}, - {"substring-before", {&createFunSubstringBefore, 2}}, - {"sum", {&createFunSum, 1}}, - {"translate", {&createFunTranslate, 3}}, - {"true", {&createFunTrue, 0}}, + {"boolean", {&CreateFunBoolean, 1}}, + {"ceiling", {&CreateFunCeiling, 1}}, + {"concat", {&CreateFunConcat, Interval(2, Interval::kInf)}}, + {"contains", {&CreateFunContains, 2}}, + {"count", {&CreateFunCount, 1}}, + {"false", {&CreateFunFalse, 0}}, + {"floor", {&CreateFunFloor, 1}}, + {"id", {&CreateFunId, 1}}, + {"lang", {&CreateFunLang, 1}}, + {"last", {&CreateFunLast, 0}}, + {"local-name", {&CreateFunLocalName, Interval(0, 1)}}, + {"name", {&CreateFunName, Interval(0, 1)}}, + {"namespace-uri", {&CreateFunNamespaceURI, Interval(0, 1)}}, + {"normalize-space", {&CreateFunNormalizeSpace, Interval(0, 1)}}, + {"not", {&CreateFunNot, 1}}, + {"number", {&CreateFunNumber, Interval(0, 1)}}, + {"position", {&CreateFunPosition, 0}}, + {"round", {&CreateFunRound, 1}}, + {"starts-with", {&CreateFunStartsWith, 2}}, + {"string", {&CreateFunString, Interval(0, 1)}}, + {"string-length", {&CreateFunStringLength, Interval(0, 1)}}, + {"substring", {&CreateFunSubstring, Interval(2, 3)}}, + {"substring-after", {&CreateFunSubstringAfter, 2}}, + {"substring-before", {&CreateFunSubstringBefore, 2}}, + {"sum", {&CreateFunSum, 1}}, + {"translate", {&CreateFunTranslate, 3}}, + {"true", {&CreateFunTrue, 0}}, }; - functionMap = new HashMap<String, FunctionRec>; + g_function_map = new HashMap<String, FunctionRec>; for (size_t i = 0; i < WTF_ARRAY_LENGTH(functions); ++i) - functionMap->set(functions[i].name, functions[i].function); + g_function_map->Set(functions[i].name, functions[i].function); } -Function* createFunction(const String& name) { +Function* CreateFunction(const String& name) { HeapVector<Member<Expression>> args; - return createFunction(name, args); + return CreateFunction(name, args); } -Function* createFunction(const String& name, +Function* CreateFunction(const String& name, HeapVector<Member<Expression>>& args) { - if (!functionMap) - createFunctionMap(); + if (!g_function_map) + CreateFunctionMap(); - HashMap<String, FunctionRec>::iterator functionMapIter = - functionMap->find(name); - FunctionRec* functionRec = nullptr; + HashMap<String, FunctionRec>::iterator function_map_iter = + g_function_map->Find(name); + FunctionRec* function_rec = nullptr; - if (functionMapIter == functionMap->end() || - !(functionRec = &functionMapIter->value)->args.contains(args.size())) + if (function_map_iter == g_function_map->end() || + !(function_rec = &function_map_iter->value)->args.Contains(args.size())) return nullptr; - Function* function = functionRec->factoryFn(); - function->setArguments(args); - function->setName(name); + Function* function = function_rec->factory_fn(); + function->SetArguments(args); + function->SetName(name); return function; } diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathFunctions.h b/chromium/third_party/WebKit/Source/core/xml/XPathFunctions.h index d00de20d7f5..0d0a36888d0 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XPathFunctions.h +++ b/chromium/third_party/WebKit/Source/core/xml/XPathFunctions.h @@ -36,21 +36,21 @@ namespace XPath { class CORE_EXPORT Function : public Expression { public: - void setArguments(HeapVector<Member<Expression>>&); - void setName(const String& name) { m_name = name; } + void SetArguments(HeapVector<Member<Expression>>&); + void SetName(const String& name) { name_ = name; } protected: - Expression* arg(int pos) { return subExpr(pos); } - const Expression* arg(int pos) const { return subExpr(pos); } - unsigned argCount() const { return subExprCount(); } - String name() const { return m_name; } + Expression* Arg(int pos) { return SubExpr(pos); } + const Expression* Arg(int pos) const { return SubExpr(pos); } + unsigned ArgCount() const { return SubExprCount(); } + String GetName() const { return name_; } private: - String m_name; + String name_; }; -Function* createFunction(const String& name); -CORE_EXPORT Function* createFunction(const String& name, +Function* CreateFunction(const String& name); +CORE_EXPORT Function* CreateFunction(const String& name, HeapVector<Member<Expression>>&); } // namespace XPath diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathFunctionsTest.cpp b/chromium/third_party/WebKit/Source/core/xml/XPathFunctionsTest.cpp index ef59c278ee7..92be30b60a3 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XPathFunctionsTest.cpp +++ b/chromium/third_party/WebKit/Source/core/xml/XPathFunctionsTest.cpp @@ -9,8 +9,8 @@ #include "core/xml/XPathPredicate.h" // Number, StringExpression #include "core/xml/XPathValue.h" #include "platform/heap/Handle.h" // HeapVector, Member, etc. +#include "platform/wtf/Allocator.h" #include "testing/gtest/include/gtest/gtest.h" -#include "wtf/Allocator.h" #include <cmath> #include <limits> @@ -23,102 +23,102 @@ class XPathContext { STACK_ALLOCATED(); public: - XPathContext() : m_document(Document::create()), m_context(*m_document) {} + XPathContext() : document_(Document::Create()), context_(*document_) {} - XPath::EvaluationContext& context() { return m_context; } - Document& document() { return *m_document; } + XPath::EvaluationContext& Context() { return context_; } + Document& GetDocument() { return *document_; } private: - const Member<Document> m_document; - XPath::EvaluationContext m_context; + const Member<Document> document_; + XPath::EvaluationContext context_; }; using XPathArguments = HeapVector<Member<XPath::Expression>>; -static String substring(XPathArguments& args) { +static String Substring(XPathArguments& args) { XPathContext xpath; - XPath::Expression* call = XPath::createFunction("substring", args); - XPath::Value result = call->evaluate(xpath.context()); - return result.toString(); + XPath::Expression* call = XPath::CreateFunction("substring", args); + XPath::Value result = call->Evaluate(xpath.Context()); + return result.ToString(); } -static String substring(const char* string, double pos) { +static String Substring(const char* string, double pos) { XPathArguments args; args.push_back(new XPath::StringExpression(string)); args.push_back(new XPath::Number(pos)); - return substring(args); + return Substring(args); } -static String substring(const char* string, double pos, double len) { +static String Substring(const char* string, double pos, double len) { XPathArguments args; args.push_back(new XPath::StringExpression(string)); args.push_back(new XPath::Number(pos)); args.push_back(new XPath::Number(len)); - return substring(args); + return Substring(args); } } // namespace TEST(XPathFunctionsTest, substring_specExamples) { - EXPECT_EQ(" car", substring("motor car", 6.0)) + EXPECT_EQ(" car", Substring("motor car", 6.0)) << "should select characters staring at position 6 to the end"; - EXPECT_EQ("ada", substring("metadata", 4.0, 3.0)) + EXPECT_EQ("ada", Substring("metadata", 4.0, 3.0)) << "should select characters at 4 <= position < 7"; - EXPECT_EQ("234", substring("123456", 1.5, 2.6)) + EXPECT_EQ("234", Substring("123456", 1.5, 2.6)) << "should select characters at 2 <= position < 5"; - EXPECT_EQ("12", substring("12345", 0.0, 3.0)) + EXPECT_EQ("12", Substring("12345", 0.0, 3.0)) << "should select characters at 0 <= position < 3; note the first " "position is 1 so this is characters in position 1 and 2"; - EXPECT_EQ("", substring("12345", 5.0, -3.0)) + EXPECT_EQ("", Substring("12345", 5.0, -3.0)) << "no characters should have 5 <= position < 2"; - EXPECT_EQ("1", substring("12345", -3.0, 5.0)) + EXPECT_EQ("1", Substring("12345", -3.0, 5.0)) << "should select characters at -3 <= position < 2; since the first " "position is 1, this is the character at position 1"; - EXPECT_EQ("", substring("12345", NAN, 3.0)) + EXPECT_EQ("", Substring("12345", NAN, 3.0)) << "should select no characters since NaN <= position is always false"; - EXPECT_EQ("", substring("12345", 1.0, NAN)) + EXPECT_EQ("", Substring("12345", 1.0, NAN)) << "should select no characters since position < 1. + NaN is always " "false"; EXPECT_EQ("12345", - substring("12345", -42, std::numeric_limits<double>::infinity())) + Substring("12345", -42, std::numeric_limits<double>::infinity())) << "should select characters at -42 <= position < Infinity, which is all " "of them"; - EXPECT_EQ("", substring("12345", -std::numeric_limits<double>::infinity(), + EXPECT_EQ("", Substring("12345", -std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity())) << "since -Inf+Inf is NaN, should select no characters since position " "< NaN is always false"; } TEST(XPathFunctionsTest, substring_emptyString) { - EXPECT_EQ("", substring("", 0.0, 1.0)) + EXPECT_EQ("", Substring("", 0.0, 1.0)) << "substring of an empty string should be the empty string"; } TEST(XPathFunctionsTest, substring) { - EXPECT_EQ("hello", substring("well hello there", 6.0, 5.0)); + EXPECT_EQ("hello", Substring("well hello there", 6.0, 5.0)); } TEST(XPathFunctionsTest, substring_negativePosition) { - EXPECT_EQ("hello", substring("hello, world!", -4.0, 10.0)) + EXPECT_EQ("hello", Substring("hello, world!", -4.0, 10.0)) << "negative start positions should impinge on the result length"; // Try to underflow the length adjustment for negative positions. - EXPECT_EQ("", substring("hello", std::numeric_limits<long>::min() + 1, 1.0)); + EXPECT_EQ("", Substring("hello", std::numeric_limits<long>::min() + 1, 1.0)); } TEST(XPathFunctionsTest, substring_negativeLength) { - EXPECT_EQ("", substring("hello, world!", 1.0, -3.0)) + EXPECT_EQ("", Substring("hello, world!", 1.0, -3.0)) << "negative lengths should result in an empty string"; - EXPECT_EQ("", substring("foo", std::numeric_limits<long>::min(), 1.0)) + EXPECT_EQ("", Substring("foo", std::numeric_limits<long>::min(), 1.0)) << "large (but long representable) negative position should result in " << "an empty string"; } TEST(XPathFunctionsTest, substring_extremePositionLength) { - EXPECT_EQ("", substring("no way", 1e100, 7.0)) + EXPECT_EQ("", Substring("no way", 1e100, 7.0)) << "extremely large positions should result in the empty string"; - EXPECT_EQ("no way", substring("no way", -1e200, 1e300)) + EXPECT_EQ("no way", Substring("no way", -1e200, 1e300)) << "although these indices are not representable as long, this should " << "produce the string because indices are computed as doubles"; } diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathGrammar.y b/chromium/third_party/WebKit/Source/core/xml/XPathGrammar.y index 28d326b48ac..461cd66fdf8 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XPathGrammar.y +++ b/chromium/third_party/WebKit/Source/core/xml/XPathGrammar.y @@ -34,15 +34,15 @@ #include "core/xml/XPathPredicate.h" #include "core/xml/XPathStep.h" #include "core/xml/XPathVariableReference.h" -#include "wtf/allocator/Partitions.h" +#include "platform/wtf/allocator/Partitions.h" void* yyFastMalloc(size_t size) { - return WTF::Partitions::fastMalloc(size, nullptr); + return WTF::Partitions::FastMalloc(size, nullptr); } #define YYMALLOC yyFastMalloc -#define YYFREE WTF::Partitions::fastFree +#define YYFREE WTF::Partitions::FastFree #define YYENABLE_NLS 0 #define YYLTYPE_IS_TRIVIAL 1 @@ -73,7 +73,7 @@ using namespace XPath; %{ -static int xpathyylex(YYSTYPE* yylval) { return Parser::current()->lex(yylval); } +static int xpathyylex(YYSTYPE* yylval) { return Parser::Current()->Lex(yylval); } static void xpathyyerror(void*, const char*) { } %} @@ -121,19 +121,19 @@ static void xpathyyerror(void*, const char*) { } Expr: OrExpr { - parser->m_topExpr = $1; + parser->top_expr_ = $1; } ; LocationPath: RelativeLocationPath { - $$->setAbsolute(false); + $$->SetAbsolute(false); } | AbsoluteLocationPath { - $$->setAbsolute(true); + $$->SetAbsolute(true); } ; @@ -151,7 +151,7 @@ AbsoluteLocationPath: DescendantOrSelf RelativeLocationPath { $$ = $2; - $$->insertFirstStep($1); + $$->InsertFirstStep($1); } ; @@ -159,18 +159,18 @@ RelativeLocationPath: Step { $$ = new LocationPath; - $$->appendStep($1); + $$->AppendStep($1); } | RelativeLocationPath '/' Step { - $$->appendStep($3); + $$->AppendStep($3); } | RelativeLocationPath DescendantOrSelf Step { - $$->appendStep($2); - $$->appendStep($3); + $$->AppendStep($2); + $$->AppendStep($3); } ; @@ -178,25 +178,25 @@ Step: NodeTest OptionalPredicateList { if ($2) - $$ = new Step(Step::ChildAxis, *$1, *$2); + $$ = new Step(Step::kChildAxis, *$1, *$2); else - $$ = new Step(Step::ChildAxis, *$1); + $$ = new Step(Step::kChildAxis, *$1); } | NAMETEST OptionalPredicateList { AtomicString localName; AtomicString namespaceURI; - if (!parser->expandQName(*$1, localName, namespaceURI)) { - parser->m_gotNamespaceError = true; + if (!parser->ExpandQName(*$1, localName, namespaceURI)) { + parser->got_namespace_error_ = true; YYABORT; } if ($2) - $$ = new Step(Step::ChildAxis, Step::NodeTest(Step::NodeTest::NameTest, localName, namespaceURI), *$2); + $$ = new Step(Step::kChildAxis, Step::NodeTest(Step::NodeTest::kNameTest, localName, namespaceURI), *$2); else - $$ = new Step(Step::ChildAxis, Step::NodeTest(Step::NodeTest::NameTest, localName, namespaceURI)); - parser->deleteString($1); + $$ = new Step(Step::kChildAxis, Step::NodeTest(Step::NodeTest::kNameTest, localName, namespaceURI)); + parser->DeleteString($1); } | AxisSpecifier NodeTest OptionalPredicateList @@ -211,16 +211,16 @@ Step: { AtomicString localName; AtomicString namespaceURI; - if (!parser->expandQName(*$2, localName, namespaceURI)) { - parser->m_gotNamespaceError = true; + if (!parser->ExpandQName(*$2, localName, namespaceURI)) { + parser->got_namespace_error_ = true; YYABORT; } if ($3) - $$ = new Step($1, Step::NodeTest(Step::NodeTest::NameTest, localName, namespaceURI), *$3); + $$ = new Step($1, Step::NodeTest(Step::NodeTest::kNameTest, localName, namespaceURI), *$3); else - $$ = new Step($1, Step::NodeTest(Step::NodeTest::NameTest, localName, namespaceURI)); - parser->deleteString($2); + $$ = new Step($1, Step::NodeTest(Step::NodeTest::kNameTest, localName, namespaceURI)); + parser->DeleteString($2); } | AbbreviatedStep @@ -231,7 +231,7 @@ AxisSpecifier: | '@' { - $$ = Step::AttributeAxis; + $$ = Step::kAttributeAxis; } ; @@ -239,26 +239,26 @@ NodeTest: NODETYPE '(' ')' { if (*$1 == "node") - $$ = new Step::NodeTest(Step::NodeTest::AnyNodeTest); + $$ = new Step::NodeTest(Step::NodeTest::kAnyNodeTest); else if (*$1 == "text") - $$ = new Step::NodeTest(Step::NodeTest::TextNodeTest); + $$ = new Step::NodeTest(Step::NodeTest::kTextNodeTest); else if (*$1 == "comment") - $$ = new Step::NodeTest(Step::NodeTest::CommentNodeTest); + $$ = new Step::NodeTest(Step::NodeTest::kCommentNodeTest); - parser->deleteString($1); + parser->DeleteString($1); } | PI '(' ')' { - $$ = new Step::NodeTest(Step::NodeTest::ProcessingInstructionNodeTest); - parser->deleteString($1); + $$ = new Step::NodeTest(Step::NodeTest::kProcessingInstructionNodeTest); + parser->DeleteString($1); } | PI '(' LITERAL ')' { - $$ = new Step::NodeTest(Step::NodeTest::ProcessingInstructionNodeTest, $3->stripWhiteSpace()); - parser->deleteString($1); - parser->deleteString($3); + $$ = new Step::NodeTest(Step::NodeTest::kProcessingInstructionNodeTest, $3->StripWhiteSpace()); + parser->DeleteString($1); + parser->DeleteString($3); } ; @@ -294,19 +294,19 @@ Predicate: DescendantOrSelf: SLASHSLASH { - $$ = new Step(Step::DescendantOrSelfAxis, Step::NodeTest(Step::NodeTest::AnyNodeTest)); + $$ = new Step(Step::kDescendantOrSelfAxis, Step::NodeTest(Step::NodeTest::kAnyNodeTest)); } ; AbbreviatedStep: '.' { - $$ = new Step(Step::SelfAxis, Step::NodeTest(Step::NodeTest::AnyNodeTest)); + $$ = new Step(Step::kSelfAxis, Step::NodeTest(Step::NodeTest::kAnyNodeTest)); } | DOTDOT { - $$ = new Step(Step::ParentAxis, Step::NodeTest(Step::NodeTest::AnyNodeTest)); + $$ = new Step(Step::kParentAxis, Step::NodeTest(Step::NodeTest::kAnyNodeTest)); } ; @@ -314,7 +314,7 @@ PrimaryExpr: VARIABLEREFERENCE { $$ = new VariableReference(*$1); - parser->deleteString($1); + parser->DeleteString($1); } | '(' Expr ')' @@ -325,13 +325,13 @@ PrimaryExpr: LITERAL { $$ = new StringExpression(*$1); - parser->deleteString($1); + parser->DeleteString($1); } | NUMBER { - $$ = new Number($1->toDouble()); - parser->deleteString($1); + $$ = new Number($1->ToDouble()); + parser->DeleteString($1); } | FunctionCall @@ -340,18 +340,18 @@ PrimaryExpr: FunctionCall: FUNCTIONNAME '(' ')' { - $$ = createFunction(*$1); + $$ = CreateFunction(*$1); if (!$$) YYABORT; - parser->deleteString($1); + parser->DeleteString($1); } | FUNCTIONNAME '(' ArgumentList ')' { - $$ = createFunction(*$1, *$3); + $$ = CreateFunction(*$1, *$3); if (!$$) YYABORT; - parser->deleteString($1); + parser->DeleteString($1); } ; @@ -378,8 +378,8 @@ UnionExpr: UnionExpr '|' PathExpr { $$ = new Union; - $$->addSubExpression($1); - $$->addSubExpression($3); + $$->AddSubExpression($1); + $$->AddSubExpression($3); } ; @@ -393,14 +393,14 @@ PathExpr: | FilterExpr '/' RelativeLocationPath { - $3->setAbsolute(true); + $3->SetAbsolute(true); $$ = new blink::XPath::Path($1, $3); } | FilterExpr DescendantOrSelf RelativeLocationPath { - $3->insertFirstStep($2); - $3->setAbsolute(true); + $3->InsertFirstStep($2); + $3->SetAbsolute(true); $$ = new blink::XPath::Path($1, $3); } ; @@ -419,7 +419,7 @@ OrExpr: | OrExpr OR AndExpr { - $$ = new LogicalOp(LogicalOp::OP_Or, $1, $3); + $$ = new LogicalOp(LogicalOp::kOP_Or, $1, $3); } ; @@ -428,7 +428,7 @@ AndExpr: | AndExpr AND EqualityExpr { - $$ = new LogicalOp(LogicalOp::OP_And, $1, $3); + $$ = new LogicalOp(LogicalOp::kOP_And, $1, $3); } ; @@ -455,12 +455,12 @@ AdditiveExpr: | AdditiveExpr PLUS MultiplicativeExpr { - $$ = new NumericOp(NumericOp::OP_Add, $1, $3); + $$ = new NumericOp(NumericOp::kOP_Add, $1, $3); } | AdditiveExpr MINUS MultiplicativeExpr { - $$ = new NumericOp(NumericOp::OP_Sub, $1, $3); + $$ = new NumericOp(NumericOp::kOP_Sub, $1, $3); } ; @@ -479,7 +479,7 @@ UnaryExpr: MINUS UnaryExpr { $$ = new Negative; - $$->addSubExpression($2); + $$->AddSubExpression($2); } ; diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathNSResolver.h b/chromium/third_party/WebKit/Source/core/xml/XPathNSResolver.h index a4bd84d0550..b90e519b16e 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XPathNSResolver.h +++ b/chromium/third_party/WebKit/Source/core/xml/XPathNSResolver.h @@ -29,7 +29,7 @@ #include "bindings/core/v8/ScriptWrappable.h" #include "platform/heap/Handle.h" -#include "wtf/Forward.h" +#include "platform/wtf/Forward.h" namespace blink { diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathNodeSet.cpp b/chromium/third_party/WebKit/Source/core/xml/XPathNodeSet.cpp index 9d3ad8691ad..b649af23d60 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XPathNodeSet.cpp +++ b/chromium/third_party/WebKit/Source/core/xml/XPathNodeSet.cpp @@ -36,88 +36,89 @@ namespace XPath { // When a node set is large, sorting it by traversing the whole document is // better (we can assume that we aren't dealing with documents that we cannot // even traverse in reasonable time). -const unsigned traversalSortCutoff = 10000; +const unsigned kTraversalSortCutoff = 10000; typedef HeapVector<Member<Node>> NodeSetVector; -NodeSet* NodeSet::create(const NodeSet& other) { - NodeSet* nodeSet = NodeSet::create(); - nodeSet->m_isSorted = other.m_isSorted; - nodeSet->m_subtreesAreDisjoint = other.m_subtreesAreDisjoint; - nodeSet->m_nodes.appendVector(other.m_nodes); - return nodeSet; +NodeSet* NodeSet::Create(const NodeSet& other) { + NodeSet* node_set = NodeSet::Create(); + node_set->is_sorted_ = other.is_sorted_; + node_set->subtrees_are_disjoint_ = other.subtrees_are_disjoint_; + node_set->nodes_.AppendVector(other.nodes_); + return node_set; } -static inline Node* parentWithDepth(unsigned depth, +static inline Node* ParentWithDepth(unsigned depth, const NodeSetVector& parents) { DCHECK_GE(parents.size(), depth + 1); return parents[parents.size() - 1 - depth]; } -static void sortBlock(unsigned from, +static void SortBlock(unsigned from, unsigned to, - HeapVector<NodeSetVector>& parentMatrix, - bool mayContainAttributeNodes) { + HeapVector<NodeSetVector>& parent_matrix, + bool may_contain_attribute_nodes) { // Should not call this function with less that two nodes to sort. DCHECK_LT(from + 1, to); - unsigned minDepth = UINT_MAX; + unsigned min_depth = UINT_MAX; for (unsigned i = from; i < to; ++i) { - unsigned depth = parentMatrix[i].size() - 1; - if (minDepth > depth) - minDepth = depth; + unsigned depth = parent_matrix[i].size() - 1; + if (min_depth > depth) + min_depth = depth; } // Find the common ancestor. - unsigned commonAncestorDepth = minDepth; - Node* commonAncestor; + unsigned common_ancestor_depth = min_depth; + Node* common_ancestor; while (true) { - commonAncestor = parentWithDepth(commonAncestorDepth, parentMatrix[from]); - if (commonAncestorDepth == 0) + common_ancestor = + ParentWithDepth(common_ancestor_depth, parent_matrix[from]); + if (common_ancestor_depth == 0) break; - bool allEqual = true; + bool all_equal = true; for (unsigned i = from + 1; i < to; ++i) { - if (commonAncestor != - parentWithDepth(commonAncestorDepth, parentMatrix[i])) { - allEqual = false; + if (common_ancestor != + ParentWithDepth(common_ancestor_depth, parent_matrix[i])) { + all_equal = false; break; } } - if (allEqual) + if (all_equal) break; - --commonAncestorDepth; + --common_ancestor_depth; } - if (commonAncestorDepth == minDepth) { + if (common_ancestor_depth == min_depth) { // One of the nodes is the common ancestor => it is the first in // document order. Find it and move it to the beginning. for (unsigned i = from; i < to; ++i) { - if (commonAncestor == parentMatrix[i][0]) { - parentMatrix[i].swap(parentMatrix[from]); + if (common_ancestor == parent_matrix[i][0]) { + parent_matrix[i].Swap(parent_matrix[from]); if (from + 2 < to) - sortBlock(from + 1, to, parentMatrix, mayContainAttributeNodes); + SortBlock(from + 1, to, parent_matrix, may_contain_attribute_nodes); return; } } } - if (mayContainAttributeNodes && commonAncestor->isElementNode()) { + if (may_contain_attribute_nodes && common_ancestor->IsElementNode()) { // The attribute nodes and namespace nodes of an element occur before // the children of the element. The namespace nodes are defined to occur // before the attribute nodes. The relative order of namespace nodes is // implementation-dependent. The relative order of attribute nodes is // implementation-dependent. - unsigned sortedEnd = from; + unsigned sorted_end = from; // FIXME: namespace nodes are not implemented. - for (unsigned i = sortedEnd; i < to; ++i) { - Node* n = parentMatrix[i][0]; - if (n->isAttributeNode() && toAttr(n)->ownerElement() == commonAncestor) - parentMatrix[i].swap(parentMatrix[sortedEnd++]); + for (unsigned i = sorted_end; i < to; ++i) { + Node* n = parent_matrix[i][0]; + if (n->IsAttributeNode() && ToAttr(n)->ownerElement() == common_ancestor) + parent_matrix[i].Swap(parent_matrix[sorted_end++]); } - if (sortedEnd != from) { - if (to - sortedEnd > 1) - sortBlock(sortedEnd, to, parentMatrix, mayContainAttributeNodes); + if (sorted_end != from) { + if (to - sorted_end > 1) + SortBlock(sorted_end, to, parent_matrix, may_contain_attribute_nodes); return; } } @@ -125,84 +126,84 @@ static void sortBlock(unsigned from, // Children nodes of the common ancestor induce a subdivision of our // node-set. Sort it according to this subdivision, and recursively sort // each group. - HeapHashSet<Member<Node>> parentNodes; + HeapHashSet<Member<Node>> parent_nodes; for (unsigned i = from; i < to; ++i) - parentNodes.insert( - parentWithDepth(commonAncestorDepth + 1, parentMatrix[i])); + parent_nodes.insert( + ParentWithDepth(common_ancestor_depth + 1, parent_matrix[i])); - unsigned previousGroupEnd = from; - unsigned groupEnd = from; - for (Node* n = commonAncestor->firstChild(); n; n = n->nextSibling()) { + unsigned previous_group_end = from; + unsigned group_end = from; + for (Node* n = common_ancestor->firstChild(); n; n = n->nextSibling()) { // If parentNodes contains the node, perform a linear search to move its // children in the node-set to the beginning. - if (parentNodes.contains(n)) { - for (unsigned i = groupEnd; i < to; ++i) { - if (parentWithDepth(commonAncestorDepth + 1, parentMatrix[i]) == n) - parentMatrix[i].swap(parentMatrix[groupEnd++]); + if (parent_nodes.Contains(n)) { + for (unsigned i = group_end; i < to; ++i) { + if (ParentWithDepth(common_ancestor_depth + 1, parent_matrix[i]) == n) + parent_matrix[i].Swap(parent_matrix[group_end++]); } - if (groupEnd - previousGroupEnd > 1) - sortBlock(previousGroupEnd, groupEnd, parentMatrix, - mayContainAttributeNodes); + if (group_end - previous_group_end > 1) + SortBlock(previous_group_end, group_end, parent_matrix, + may_contain_attribute_nodes); - DCHECK_NE(previousGroupEnd, groupEnd); - previousGroupEnd = groupEnd; + DCHECK_NE(previous_group_end, group_end); + previous_group_end = group_end; #if DCHECK_IS_ON() - parentNodes.erase(n); + parent_nodes.erase(n); #endif } } - DCHECK(parentNodes.isEmpty()); + DCHECK(parent_nodes.IsEmpty()); } -void NodeSet::sort() const { - if (m_isSorted) +void NodeSet::Sort() const { + if (is_sorted_) return; - unsigned nodeCount = m_nodes.size(); - if (nodeCount < 2) { - const_cast<bool&>(m_isSorted) = true; + unsigned node_count = nodes_.size(); + if (node_count < 2) { + const_cast<bool&>(is_sorted_) = true; return; } - if (nodeCount > traversalSortCutoff) { - traversalSort(); + if (node_count > kTraversalSortCutoff) { + TraversalSort(); return; } - bool containsAttributeNodes = false; - - HeapVector<NodeSetVector> parentMatrix(nodeCount); - for (unsigned i = 0; i < nodeCount; ++i) { - NodeSetVector& parentsVector = parentMatrix[i]; - Node* n = m_nodes[i].get(); - parentsVector.push_back(n); - if (n->isAttributeNode()) { - n = toAttr(n)->ownerElement(); - parentsVector.push_back(n); - containsAttributeNodes = true; + bool contains_attribute_nodes = false; + + HeapVector<NodeSetVector> parent_matrix(node_count); + for (unsigned i = 0; i < node_count; ++i) { + NodeSetVector& parents_vector = parent_matrix[i]; + Node* n = nodes_[i].Get(); + parents_vector.push_back(n); + if (n->IsAttributeNode()) { + n = ToAttr(n)->ownerElement(); + parents_vector.push_back(n); + contains_attribute_nodes = true; } for (n = n->parentNode(); n; n = n->parentNode()) - parentsVector.push_back(n); + parents_vector.push_back(n); } - sortBlock(0, nodeCount, parentMatrix, containsAttributeNodes); + SortBlock(0, node_count, parent_matrix, contains_attribute_nodes); // It is not possible to just assign the result to m_nodes, because some // nodes may get dereferenced and destroyed. - HeapVector<Member<Node>> sortedNodes; - sortedNodes.reserveInitialCapacity(nodeCount); - for (unsigned i = 0; i < nodeCount; ++i) - sortedNodes.push_back(parentMatrix[i][0]); + HeapVector<Member<Node>> sorted_nodes; + sorted_nodes.ReserveInitialCapacity(node_count); + for (unsigned i = 0; i < node_count; ++i) + sorted_nodes.push_back(parent_matrix[i][0]); - const_cast<HeapVector<Member<Node>>&>(m_nodes).swap(sortedNodes); + const_cast<HeapVector<Member<Node>>&>(nodes_).Swap(sorted_nodes); } -static Node* findRootNode(Node* node) { - if (node->isAttributeNode()) - node = toAttr(node)->ownerElement(); +static Node* FindRootNode(Node* node) { + if (node->IsAttributeNode()) + node = ToAttr(node)->ownerElement(); if (node->isConnected()) { - node = &node->document(); + node = &node->GetDocument(); } else { while (Node* parent = node->parentNode()) node = parent; @@ -210,70 +211,70 @@ static Node* findRootNode(Node* node) { return node; } -void NodeSet::traversalSort() const { +void NodeSet::TraversalSort() const { HeapHashSet<Member<Node>> nodes; - bool containsAttributeNodes = false; + bool contains_attribute_nodes = false; - unsigned nodeCount = m_nodes.size(); - DCHECK_GT(nodeCount, 1u); - for (unsigned i = 0; i < nodeCount; ++i) { - Node* node = m_nodes[i].get(); + unsigned node_count = nodes_.size(); + DCHECK_GT(node_count, 1u); + for (unsigned i = 0; i < node_count; ++i) { + Node* node = nodes_[i].Get(); nodes.insert(node); - if (node->isAttributeNode()) - containsAttributeNodes = true; + if (node->IsAttributeNode()) + contains_attribute_nodes = true; } - HeapVector<Member<Node>> sortedNodes; - sortedNodes.reserveInitialCapacity(nodeCount); + HeapVector<Member<Node>> sorted_nodes; + sorted_nodes.ReserveInitialCapacity(node_count); - for (Node& n : NodeTraversal::startsAt(*findRootNode(m_nodes.front()))) { - if (nodes.contains(&n)) - sortedNodes.push_back(&n); + for (Node& n : NodeTraversal::StartsAt(*FindRootNode(nodes_.front()))) { + if (nodes.Contains(&n)) + sorted_nodes.push_back(&n); - if (!containsAttributeNodes || !n.isElementNode()) + if (!contains_attribute_nodes || !n.IsElementNode()) continue; - Element* element = toElement(&n); - AttributeCollection attributes = element->attributes(); + Element* element = ToElement(&n); + AttributeCollection attributes = element->Attributes(); for (auto& attribute : attributes) { - Attr* attr = element->attrIfExists(attribute.name()); - if (attr && nodes.contains(attr)) - sortedNodes.push_back(attr); + Attr* attr = element->AttrIfExists(attribute.GetName()); + if (attr && nodes.Contains(attr)) + sorted_nodes.push_back(attr); } } - DCHECK_EQ(sortedNodes.size(), nodeCount); - const_cast<HeapVector<Member<Node>>&>(m_nodes).swap(sortedNodes); + DCHECK_EQ(sorted_nodes.size(), node_count); + const_cast<HeapVector<Member<Node>>&>(nodes_).Swap(sorted_nodes); } -void NodeSet::reverse() { - if (m_nodes.isEmpty()) +void NodeSet::Reverse() { + if (nodes_.IsEmpty()) return; unsigned from = 0; - unsigned to = m_nodes.size() - 1; + unsigned to = nodes_.size() - 1; while (from < to) { - m_nodes[from].swap(m_nodes[to]); + nodes_[from].Swap(nodes_[to]); ++from; --to; } } -Node* NodeSet::firstNode() const { - if (isEmpty()) +Node* NodeSet::FirstNode() const { + if (IsEmpty()) return nullptr; // FIXME: fully sorting the node-set just to find its first node is // wasteful. - sort(); - return m_nodes.at(0).get(); + Sort(); + return nodes_.at(0).Get(); } -Node* NodeSet::anyNode() const { - if (isEmpty()) +Node* NodeSet::AnyNode() const { + if (IsEmpty()) return nullptr; - return m_nodes.at(0).get(); + return nodes_.at(0).Get(); } } // namespace XPath diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathNodeSet.h b/chromium/third_party/WebKit/Source/core/xml/XPathNodeSet.h index 5ec9d7781a2..e2cdf75d702 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XPathNodeSet.h +++ b/chromium/third_party/WebKit/Source/core/xml/XPathNodeSet.h @@ -27,8 +27,8 @@ #define XPathNodeSet_h #include "core/dom/Node.h" -#include "wtf/Forward.h" -#include "wtf/Vector.h" +#include "platform/wtf/Forward.h" +#include "platform/wtf/Vector.h" namespace blink { @@ -36,62 +36,64 @@ namespace XPath { class NodeSet final : public GarbageCollected<NodeSet> { public: - static NodeSet* create() { return new NodeSet; } - static NodeSet* create(const NodeSet&); - DEFINE_INLINE_TRACE() { visitor->trace(m_nodes); } - - size_t size() const { return m_nodes.size(); } - bool isEmpty() const { return !m_nodes.size(); } - Node* operator[](unsigned i) const { return m_nodes.at(i).get(); } - HeapVector<Member<Node>>::iterator begin() { return m_nodes.begin(); } - HeapVector<Member<Node>>::iterator end() { return m_nodes.end(); } + static NodeSet* Create() { return new NodeSet; } + static NodeSet* Create(const NodeSet&); + DEFINE_INLINE_TRACE() { visitor->Trace(nodes_); } + + size_t size() const { return nodes_.size(); } + bool IsEmpty() const { return !nodes_.size(); } + Node* operator[](unsigned i) const { return nodes_.at(i).Get(); } + HeapVector<Member<Node>>::iterator begin() { return nodes_.begin(); } + HeapVector<Member<Node>>::iterator end() { return nodes_.end(); } HeapVector<Member<Node>>::const_iterator begin() const { - return m_nodes.begin(); + return nodes_.begin(); } - HeapVector<Member<Node>>::const_iterator end() const { return m_nodes.end(); } - void reserveCapacity(size_t newCapacity) { - m_nodes.reserveCapacity(newCapacity); + HeapVector<Member<Node>>::const_iterator end() const { return nodes_.end(); } + void ReserveCapacity(size_t new_capacity) { + nodes_.ReserveCapacity(new_capacity); } - void clear() { m_nodes.clear(); } - void swap(NodeSet& other) { - std::swap(m_isSorted, other.m_isSorted); - std::swap(m_subtreesAreDisjoint, other.m_subtreesAreDisjoint); - m_nodes.swap(other.m_nodes); + void Clear() { nodes_.Clear(); } + void Swap(NodeSet& other) { + std::swap(is_sorted_, other.is_sorted_); + std::swap(subtrees_are_disjoint_, other.subtrees_are_disjoint_); + nodes_.Swap(other.nodes_); } // NodeSet itself does not verify that nodes in it are unique. - void append(Node* node) { m_nodes.push_back(node); } - void append(const NodeSet& nodeSet) { m_nodes.appendVector(nodeSet.m_nodes); } + void Append(Node* node) { nodes_.push_back(node); } + void Append(const NodeSet& node_set) { nodes_.AppendVector(node_set.nodes_); } // Returns the set's first node in document order, or 0 if the set is empty. - Node* firstNode() const; + Node* FirstNode() const; // Returns 0 if the set is empty. - Node* anyNode() const; + Node* AnyNode() const; // NodeSet itself doesn't check if it contains nodes in document order - the // caller should tell it if it does not. - void markSorted(bool isSorted) { m_isSorted = isSorted; } - bool isSorted() const { return m_isSorted || m_nodes.size() < 2; } + void MarkSorted(bool is_sorted) { is_sorted_ = is_sorted; } + bool IsSorted() const { return is_sorted_ || nodes_.size() < 2; } - void sort() const; + void Sort() const; // No node in the set is ancestor of another. Unlike m_isSorted, this is // assumed to be false, unless the caller sets it to true. - void markSubtreesDisjoint(bool disjoint) { m_subtreesAreDisjoint = disjoint; } - bool subtreesAreDisjoint() const { - return m_subtreesAreDisjoint || m_nodes.size() < 2; + void MarkSubtreesDisjoint(bool disjoint) { + subtrees_are_disjoint_ = disjoint; + } + bool SubtreesAreDisjoint() const { + return subtrees_are_disjoint_ || nodes_.size() < 2; } - void reverse(); + void Reverse(); private: - NodeSet() : m_isSorted(true), m_subtreesAreDisjoint(false) {} - void traversalSort() const; + NodeSet() : is_sorted_(true), subtrees_are_disjoint_(false) {} + void TraversalSort() const; - bool m_isSorted; - bool m_subtreesAreDisjoint; - HeapVector<Member<Node>> m_nodes; + bool is_sorted_; + bool subtrees_are_disjoint_; + HeapVector<Member<Node>> nodes_; }; } // namespace XPath diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathParser.cpp b/chromium/third_party/WebKit/Source/core/xml/XPathParser.cpp index 0d8f070b0d7..ee16515927c 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XPathParser.cpp +++ b/chromium/third_party/WebKit/Source/core/xml/XPathParser.cpp @@ -33,9 +33,9 @@ #include "core/xml/XPathEvaluator.h" #include "core/xml/XPathNSResolver.h" #include "core/xml/XPathPath.h" -#include "wtf/PtrUtil.h" -#include "wtf/StdLibExtras.h" -#include "wtf/text/StringHash.h" +#include "platform/wtf/PtrUtil.h" +#include "platform/wtf/StdLibExtras.h" +#include "platform/wtf/text/StringHash.h" namespace blink { @@ -43,80 +43,80 @@ using namespace WTF; using namespace Unicode; using namespace XPath; -Parser* Parser::currentParser = nullptr; +Parser* Parser::current_parser_ = nullptr; -enum XMLCat { NameStart, NameCont, NotPartOfName }; +enum XMLCat { kNameStart, kNameCont, kNotPartOfName }; typedef HashMap<String, Step::Axis> AxisNamesMap; -static XMLCat charCat(UChar aChar) { +static XMLCat CharCat(UChar a_char) { // might need to add some special cases from the XML spec. - if (aChar == '_') - return NameStart; - - if (aChar == '.' || aChar == '-') - return NameCont; - CharCategory category = Unicode::category(aChar); - if (category & (Letter_Uppercase | Letter_Lowercase | Letter_Other | - Letter_Titlecase | Number_Letter)) - return NameStart; - if (category & (Mark_NonSpacing | Mark_SpacingCombining | Mark_Enclosing | - Letter_Modifier | Number_DecimalDigit)) - return NameCont; - return NotPartOfName; + if (a_char == '_') + return kNameStart; + + if (a_char == '.' || a_char == '-') + return kNameCont; + CharCategory category = Unicode::Category(a_char); + if (category & (kLetter_Uppercase | kLetter_Lowercase | kLetter_Other | + kLetter_Titlecase | kNumber_Letter)) + return kNameStart; + if (category & (kMark_NonSpacing | kMark_SpacingCombining | kMark_Enclosing | + kLetter_Modifier | kNumber_DecimalDigit)) + return kNameCont; + return kNotPartOfName; } -static void setUpAxisNamesMap(AxisNamesMap& axisNames) { +static void SetUpAxisNamesMap(AxisNamesMap& axis_names) { struct AxisName { const char* name; Step::Axis axis; }; - const AxisName axisNameList[] = { - {"ancestor", Step::AncestorAxis}, - {"ancestor-or-self", Step::AncestorOrSelfAxis}, - {"attribute", Step::AttributeAxis}, - {"child", Step::ChildAxis}, - {"descendant", Step::DescendantAxis}, - {"descendant-or-self", Step::DescendantOrSelfAxis}, - {"following", Step::FollowingAxis}, - {"following-sibling", Step::FollowingSiblingAxis}, - {"namespace", Step::NamespaceAxis}, - {"parent", Step::ParentAxis}, - {"preceding", Step::PrecedingAxis}, - {"preceding-sibling", Step::PrecedingSiblingAxis}, - {"self", Step::SelfAxis}}; - for (const auto& axisName : axisNameList) - axisNames.set(axisName.name, axisName.axis); + const AxisName kAxisNameList[] = { + {"ancestor", Step::kAncestorAxis}, + {"ancestor-or-self", Step::kAncestorOrSelfAxis}, + {"attribute", Step::kAttributeAxis}, + {"child", Step::kChildAxis}, + {"descendant", Step::kDescendantAxis}, + {"descendant-or-self", Step::kDescendantOrSelfAxis}, + {"following", Step::kFollowingAxis}, + {"following-sibling", Step::kFollowingSiblingAxis}, + {"namespace", Step::kNamespaceAxis}, + {"parent", Step::kParentAxis}, + {"preceding", Step::kPrecedingAxis}, + {"preceding-sibling", Step::kPrecedingSiblingAxis}, + {"self", Step::kSelfAxis}}; + for (const auto& axis_name : kAxisNameList) + axis_names.Set(axis_name.name, axis_name.axis); } -static bool isAxisName(const String& name, Step::Axis& type) { - DEFINE_STATIC_LOCAL(AxisNamesMap, axisNames, ()); +static bool IsAxisName(const String& name, Step::Axis& type) { + DEFINE_STATIC_LOCAL(AxisNamesMap, axis_names, ()); - if (axisNames.isEmpty()) - setUpAxisNamesMap(axisNames); + if (axis_names.IsEmpty()) + SetUpAxisNamesMap(axis_names); - AxisNamesMap::iterator it = axisNames.find(name); - if (it == axisNames.end()) + AxisNamesMap::iterator it = axis_names.Find(name); + if (it == axis_names.end()) return false; type = it->value; return true; } -static bool isNodeTypeName(const String& name) { - DEFINE_STATIC_LOCAL(HashSet<String>, nodeTypeNames, +static bool IsNodeTypeName(const String& name) { + DEFINE_STATIC_LOCAL(HashSet<String>, node_type_names, ({ "comment", "text", "processing-instruction", "node", })); - return nodeTypeNames.contains(name); + return node_type_names.Contains(name); } // Returns whether the current token can possibly be a binary operator, given // the previous token. Necessary to disambiguate some of the operators // (* (multiply), div, and, or, mod) in the [32] Operator rule // (check http://www.w3.org/TR/xpath#exprlex). -bool Parser::isBinaryOperatorContext() const { - switch (m_lastTokenType) { +bool Parser::IsBinaryOperatorContext() const { + switch (last_token_type_) { case 0: case '@': case AXISNAME: @@ -139,57 +139,57 @@ bool Parser::isBinaryOperatorContext() const { } } -void Parser::skipWS() { - while (m_nextPos < m_data.length() && isSpaceOrNewline(m_data[m_nextPos])) - ++m_nextPos; +void Parser::SkipWS() { + while (next_pos_ < data_.length() && IsSpaceOrNewline(data_[next_pos_])) + ++next_pos_; } -Token Parser::makeTokenAndAdvance(int code, int advance) { - m_nextPos += advance; +Token Parser::MakeTokenAndAdvance(int code, int advance) { + next_pos_ += advance; return Token(code); } -Token Parser::makeTokenAndAdvance(int code, +Token Parser::MakeTokenAndAdvance(int code, NumericOp::Opcode val, int advance) { - m_nextPos += advance; + next_pos_ += advance; return Token(code, val); } -Token Parser::makeTokenAndAdvance(int code, EqTestOp::Opcode val, int advance) { - m_nextPos += advance; +Token Parser::MakeTokenAndAdvance(int code, EqTestOp::Opcode val, int advance) { + next_pos_ += advance; return Token(code, val); } // Returns next char if it's there and interesting, 0 otherwise -char Parser::peekAheadHelper() { - if (m_nextPos + 1 >= m_data.length()) +char Parser::PeekAheadHelper() { + if (next_pos_ + 1 >= data_.length()) return 0; - UChar next = m_data[m_nextPos + 1]; + UChar next = data_[next_pos_ + 1]; if (next >= 0xff) return 0; return next; } -char Parser::peekCurHelper() { - if (m_nextPos >= m_data.length()) +char Parser::PeekCurHelper() { + if (next_pos_ >= data_.length()) return 0; - UChar next = m_data[m_nextPos]; + UChar next = data_[next_pos_]; if (next >= 0xff) return 0; return next; } -Token Parser::lexString() { - UChar delimiter = m_data[m_nextPos]; - int startPos = m_nextPos + 1; +Token Parser::LexString() { + UChar delimiter = data_[next_pos_]; + int start_pos = next_pos_ + 1; - for (m_nextPos = startPos; m_nextPos < m_data.length(); ++m_nextPos) { - if (m_data[m_nextPos] == delimiter) { - String value = m_data.substring(startPos, m_nextPos - startPos); - if (value.isNull()) + for (next_pos_ = start_pos; next_pos_ < data_.length(); ++next_pos_) { + if (data_[next_pos_] == delimiter) { + String value = data_.Substring(start_pos, next_pos_ - start_pos); + if (value.IsNull()) value = ""; - ++m_nextPos; // Consume the char. + ++next_pos_; // Consume the char. return Token(LITERAL, value); } } @@ -198,74 +198,74 @@ Token Parser::lexString() { return Token(XPATH_ERROR); } -Token Parser::lexNumber() { - int startPos = m_nextPos; - bool seenDot = false; +Token Parser::LexNumber() { + int start_pos = next_pos_; + bool seen_dot = false; // Go until end or a non-digits character. - for (; m_nextPos < m_data.length(); ++m_nextPos) { - UChar aChar = m_data[m_nextPos]; - if (aChar >= 0xff) + for (; next_pos_ < data_.length(); ++next_pos_) { + UChar a_char = data_[next_pos_]; + if (a_char >= 0xff) break; - if (aChar < '0' || aChar > '9') { - if (aChar == '.' && !seenDot) - seenDot = true; + if (a_char < '0' || a_char > '9') { + if (a_char == '.' && !seen_dot) + seen_dot = true; else break; } } - return Token(NUMBER, m_data.substring(startPos, m_nextPos - startPos)); + return Token(NUMBER, data_.Substring(start_pos, next_pos_ - start_pos)); } -bool Parser::lexNCName(String& name) { - int startPos = m_nextPos; - if (m_nextPos >= m_data.length()) +bool Parser::LexNCName(String& name) { + int start_pos = next_pos_; + if (next_pos_ >= data_.length()) return false; - if (charCat(m_data[m_nextPos]) != NameStart) + if (CharCat(data_[next_pos_]) != kNameStart) return false; // Keep going until we get a character that's not good for names. - for (; m_nextPos < m_data.length(); ++m_nextPos) { - if (charCat(m_data[m_nextPos]) == NotPartOfName) + for (; next_pos_ < data_.length(); ++next_pos_) { + if (CharCat(data_[next_pos_]) == kNotPartOfName) break; } - name = m_data.substring(startPos, m_nextPos - startPos); + name = data_.Substring(start_pos, next_pos_ - start_pos); return true; } -bool Parser::lexQName(String& name) { +bool Parser::LexQName(String& name) { String n1; - if (!lexNCName(n1)) + if (!LexNCName(n1)) return false; - skipWS(); + SkipWS(); // If the next character is :, what we just got it the prefix, if not, // it's the whole thing. - if (peekAheadHelper() != ':') { + if (PeekAheadHelper() != ':') { name = n1; return true; } String n2; - if (!lexNCName(n2)) + if (!LexNCName(n2)) return false; name = n1 + ":" + n2; return true; } -Token Parser::nextTokenInternal() { - skipWS(); +Token Parser::NextTokenInternal() { + SkipWS(); - if (m_nextPos >= m_data.length()) + if (next_pos_ >= data_.length()) return Token(0); - char code = peekCurHelper(); + char code = PeekCurHelper(); switch (code) { case '(': case ')': @@ -274,10 +274,10 @@ Token Parser::nextTokenInternal() { case '@': case ',': case '|': - return makeTokenAndAdvance(code); + return MakeTokenAndAdvance(code); case '\'': case '\"': - return lexString(); + return LexString(); case '0': case '1': case '2': @@ -288,78 +288,78 @@ Token Parser::nextTokenInternal() { case '7': case '8': case '9': - return lexNumber(); + return LexNumber(); case '.': { - char next = peekAheadHelper(); + char next = PeekAheadHelper(); if (next == '.') - return makeTokenAndAdvance(DOTDOT, 2); + return MakeTokenAndAdvance(DOTDOT, 2); if (next >= '0' && next <= '9') - return lexNumber(); - return makeTokenAndAdvance('.'); + return LexNumber(); + return MakeTokenAndAdvance('.'); } case '/': - if (peekAheadHelper() == '/') - return makeTokenAndAdvance(SLASHSLASH, 2); - return makeTokenAndAdvance('/'); + if (PeekAheadHelper() == '/') + return MakeTokenAndAdvance(SLASHSLASH, 2); + return MakeTokenAndAdvance('/'); case '+': - return makeTokenAndAdvance(PLUS); + return MakeTokenAndAdvance(PLUS); case '-': - return makeTokenAndAdvance(MINUS); + return MakeTokenAndAdvance(MINUS); case '=': - return makeTokenAndAdvance(EQOP, EqTestOp::OpcodeEqual); + return MakeTokenAndAdvance(EQOP, EqTestOp::kOpcodeEqual); case '!': - if (peekAheadHelper() == '=') - return makeTokenAndAdvance(EQOP, EqTestOp::OpcodeNotEqual, 2); + if (PeekAheadHelper() == '=') + return MakeTokenAndAdvance(EQOP, EqTestOp::kOpcodeNotEqual, 2); return Token(XPATH_ERROR); case '<': - if (peekAheadHelper() == '=') - return makeTokenAndAdvance(RELOP, EqTestOp::OpcodeLessOrEqual, 2); - return makeTokenAndAdvance(RELOP, EqTestOp::OpcodeLessThan); + if (PeekAheadHelper() == '=') + return MakeTokenAndAdvance(RELOP, EqTestOp::kOpcodeLessOrEqual, 2); + return MakeTokenAndAdvance(RELOP, EqTestOp::kOpcodeLessThan); case '>': - if (peekAheadHelper() == '=') - return makeTokenAndAdvance(RELOP, EqTestOp::OpcodeGreaterOrEqual, 2); - return makeTokenAndAdvance(RELOP, EqTestOp::OpcodeGreaterThan); + if (PeekAheadHelper() == '=') + return MakeTokenAndAdvance(RELOP, EqTestOp::kOpcodeGreaterOrEqual, 2); + return MakeTokenAndAdvance(RELOP, EqTestOp::kOpcodeGreaterThan); case '*': - if (isBinaryOperatorContext()) - return makeTokenAndAdvance(MULOP, NumericOp::OP_Mul); - ++m_nextPos; + if (IsBinaryOperatorContext()) + return MakeTokenAndAdvance(MULOP, NumericOp::kOP_Mul); + ++next_pos_; return Token(NAMETEST, "*"); case '$': { // $ QName - m_nextPos++; + next_pos_++; String name; - if (!lexQName(name)) + if (!LexQName(name)) return Token(XPATH_ERROR); return Token(VARIABLEREFERENCE, name); } } String name; - if (!lexNCName(name)) + if (!LexNCName(name)) return Token(XPATH_ERROR); - skipWS(); + SkipWS(); // If we're in an operator context, check for any operator names - if (isBinaryOperatorContext()) { + if (IsBinaryOperatorContext()) { if (name == "and") // ### hash? return Token(AND); if (name == "or") return Token(OR); if (name == "mod") - return Token(MULOP, NumericOp::OP_Mod); + return Token(MULOP, NumericOp::kOP_Mod); if (name == "div") - return Token(MULOP, NumericOp::OP_Div); + return Token(MULOP, NumericOp::kOP_Div); } // See whether we are at a : - if (peekCurHelper() == ':') { - m_nextPos++; + if (PeekCurHelper() == ':') { + next_pos_++; // Any chance it's an axis name? - if (peekCurHelper() == ':') { - m_nextPos++; + if (PeekCurHelper() == ':') { + next_pos_++; // It might be an axis name. Step::Axis axis; - if (isAxisName(name, axis)) + if (IsAxisName(name, axis)) return Token(AXISNAME, axis); // Ugh, :: is only valid in axis names -> error return Token(XPATH_ERROR); @@ -367,26 +367,26 @@ Token Parser::nextTokenInternal() { // Seems like this is a fully qualified qname, or perhaps the * modified // one from NameTest - skipWS(); - if (peekCurHelper() == '*') { - m_nextPos++; + SkipWS(); + if (PeekCurHelper() == '*') { + next_pos_++; return Token(NAMETEST, name + ":*"); } // Make a full qname. String n2; - if (!lexNCName(n2)) + if (!LexNCName(n2)) return Token(XPATH_ERROR); name = name + ":" + n2; } - skipWS(); - if (peekCurHelper() == '(') { + SkipWS(); + if (PeekCurHelper() == '(') { // Note: we don't swallow the ( here! // Either node type of function name - if (isNodeTypeName(name)) { + if (IsNodeTypeName(name)) { if (name == "processing-instruction") return Token(PI, name); @@ -400,30 +400,30 @@ Token Parser::nextTokenInternal() { return Token(NAMETEST, name); } -Token Parser::nextToken() { - Token toRet = nextTokenInternal(); - m_lastTokenType = toRet.type; - return toRet; +Token Parser::NextToken() { + Token to_ret = NextTokenInternal(); + last_token_type_ = to_ret.type; + return to_ret; } Parser::Parser() { - reset(String()); + Reset(String()); } Parser::~Parser() {} -void Parser::reset(const String& data) { - m_nextPos = 0; - m_data = data; - m_lastTokenType = 0; +void Parser::Reset(const String& data) { + next_pos_ = 0; + data_ = data; + last_token_type_ = 0; - m_topExpr = nullptr; - m_gotNamespaceError = false; + top_expr_ = nullptr; + got_namespace_error_ = false; } -int Parser::lex(void* data) { +int Parser::Lex(void* data) { YYSTYPE* yylval = static_cast<YYSTYPE*>(data); - Token tok = nextToken(); + Token tok = NextToken(); switch (tok.type) { case AXISNAME: @@ -444,79 +444,79 @@ int Parser::lex(void* data) { case NUMBER: case NAMETEST: yylval->str = new String(tok.str); - registerString(yylval->str); + RegisterString(yylval->str); break; } return tok.type; } -bool Parser::expandQName(const String& qName, - AtomicString& localName, - AtomicString& namespaceURI) { - size_t colon = qName.find(':'); +bool Parser::ExpandQName(const String& q_name, + AtomicString& local_name, + AtomicString& namespace_uri) { + size_t colon = q_name.Find(':'); if (colon != kNotFound) { - if (!m_resolver) + if (!resolver_) return false; - namespaceURI = m_resolver->lookupNamespaceURI(qName.left(colon)); - if (namespaceURI.isNull()) + namespace_uri = resolver_->lookupNamespaceURI(q_name.Left(colon)); + if (namespace_uri.IsNull()) return false; - localName = AtomicString(qName.substring(colon + 1)); + local_name = AtomicString(q_name.Substring(colon + 1)); } else { - localName = AtomicString(qName); + local_name = AtomicString(q_name); } return true; } -Expression* Parser::parseStatement(const String& statement, +Expression* Parser::ParseStatement(const String& statement, XPathNSResolver* resolver, - ExceptionState& exceptionState) { - reset(statement); + ExceptionState& exception_state) { + Reset(statement); - m_resolver = resolver; + resolver_ = resolver; - Parser* oldParser = currentParser; - currentParser = this; - int parseError = xpathyyparse(this); - currentParser = oldParser; + Parser* old_parser = current_parser_; + current_parser_ = this; + int parse_error = xpathyyparse(this); + current_parser_ = old_parser; - if (parseError) { - m_strings.clear(); + if (parse_error) { + strings_.Clear(); - m_topExpr = nullptr; + top_expr_ = nullptr; - if (m_gotNamespaceError) - exceptionState.throwDOMException( - NamespaceError, + if (got_namespace_error_) + exception_state.ThrowDOMException( + kNamespaceError, "The string '" + statement + "' contains unresolvable namespaces."); else - exceptionState.throwDOMException( - SyntaxError, + exception_state.ThrowDOMException( + kSyntaxError, "The string '" + statement + "' is not a valid XPath expression."); return nullptr; } - DCHECK_EQ(m_strings.size(), 0u); - Expression* result = m_topExpr; - m_topExpr = nullptr; + DCHECK_EQ(strings_.size(), 0u); + Expression* result = top_expr_; + top_expr_ = nullptr; return result; } -void Parser::registerString(String* s) { +void Parser::RegisterString(String* s) { if (!s) return; - DCHECK(!m_strings.contains(s)); - m_strings.insert(WTF::wrapUnique(s)); + DCHECK(!strings_.Contains(s)); + strings_.insert(WTF::WrapUnique(s)); } -void Parser::deleteString(String* s) { +void Parser::DeleteString(String* s) { if (!s) return; - DCHECK(m_strings.contains(s)); - m_strings.erase(s); + DCHECK(strings_.Contains(s)); + strings_.erase(s); } } // namespace blink diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathParser.h b/chromium/third_party/WebKit/Source/core/xml/XPathParser.h index 6cbae73483e..5670b82955d 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XPathParser.h +++ b/chromium/third_party/WebKit/Source/core/xml/XPathParser.h @@ -27,10 +27,10 @@ #ifndef XPathParser_h #define XPathParser_h +#include <memory> #include "core/xml/XPathPredicate.h" #include "core/xml/XPathStep.h" -#include "wtf/Allocator.h" -#include <memory> +#include "platform/wtf/Allocator.h" namespace blink { @@ -66,53 +66,53 @@ class Parser { Parser(); ~Parser(); - XPathNSResolver* resolver() const { return m_resolver.get(); } - bool expandQName(const String& qName, - AtomicString& localName, - AtomicString& namespaceURI); + XPathNSResolver* Resolver() const { return resolver_.Get(); } + bool ExpandQName(const String& q_name, + AtomicString& local_name, + AtomicString& namespace_uri); - Expression* parseStatement(const String& statement, + Expression* ParseStatement(const String& statement, XPathNSResolver*, ExceptionState&); - static Parser* current() { return currentParser; } + static Parser* Current() { return current_parser_; } - int lex(void* yylval); + int Lex(void* yylval); - Member<Expression> m_topExpr; - bool m_gotNamespaceError; + Member<Expression> top_expr_; + bool got_namespace_error_; - void registerString(String*); - void deleteString(String*); + void RegisterString(String*); + void DeleteString(String*); private: - bool isBinaryOperatorContext() const; + bool IsBinaryOperatorContext() const; - void skipWS(); - Token makeTokenAndAdvance(int type, int advance = 1); - Token makeTokenAndAdvance(int type, NumericOp::Opcode, int advance = 1); - Token makeTokenAndAdvance(int type, EqTestOp::Opcode, int advance = 1); - char peekAheadHelper(); - char peekCurHelper(); + void SkipWS(); + Token MakeTokenAndAdvance(int type, int advance = 1); + Token MakeTokenAndAdvance(int type, NumericOp::Opcode, int advance = 1); + Token MakeTokenAndAdvance(int type, EqTestOp::Opcode, int advance = 1); + char PeekAheadHelper(); + char PeekCurHelper(); - Token lexString(); - Token lexNumber(); - bool lexNCName(String&); - bool lexQName(String&); + Token LexString(); + Token LexNumber(); + bool LexNCName(String&); + bool LexQName(String&); - Token nextToken(); - Token nextTokenInternal(); + Token NextToken(); + Token NextTokenInternal(); - void reset(const String& data); + void Reset(const String& data); - static Parser* currentParser; + static Parser* current_parser_; - unsigned m_nextPos; - String m_data; - int m_lastTokenType; - Member<XPathNSResolver> m_resolver; + unsigned next_pos_; + String data_; + int last_token_type_; + Member<XPathNSResolver> resolver_; - HashSet<std::unique_ptr<String>> m_strings; + HashSet<std::unique_ptr<String>> strings_; }; } // namespace XPath diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathPath.cpp b/chromium/third_party/WebKit/Source/core/xml/XPathPath.cpp index 6960e729077..4a4332f097b 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XPathPath.cpp +++ b/chromium/third_party/WebKit/Source/core/xml/XPathPath.cpp @@ -37,58 +37,58 @@ namespace blink { namespace XPath { Filter::Filter(Expression* expr, HeapVector<Member<Predicate>>& predicates) - : m_expr(expr) { - m_predicates.swap(predicates); - setIsContextNodeSensitive(m_expr->isContextNodeSensitive()); - setIsContextPositionSensitive(m_expr->isContextPositionSensitive()); - setIsContextSizeSensitive(m_expr->isContextSizeSensitive()); + : expr_(expr) { + predicates_.Swap(predicates); + SetIsContextNodeSensitive(expr_->IsContextNodeSensitive()); + SetIsContextPositionSensitive(expr_->IsContextPositionSensitive()); + SetIsContextSizeSensitive(expr_->IsContextSizeSensitive()); } Filter::~Filter() {} DEFINE_TRACE(Filter) { - visitor->trace(m_expr); - visitor->trace(m_predicates); - Expression::trace(visitor); + visitor->Trace(expr_); + visitor->Trace(predicates_); + Expression::Trace(visitor); } -Value Filter::evaluate(EvaluationContext& evaluationContext) const { - Value v = m_expr->evaluate(evaluationContext); +Value Filter::Evaluate(EvaluationContext& evaluation_context) const { + Value v = expr_->Evaluate(evaluation_context); - NodeSet& nodes = v.modifiableNodeSet(evaluationContext); - nodes.sort(); + NodeSet& nodes = v.ModifiableNodeSet(evaluation_context); + nodes.Sort(); - for (const auto& predicate : m_predicates) { - NodeSet* newNodes = NodeSet::create(); - evaluationContext.size = nodes.size(); - evaluationContext.position = 0; + for (const auto& predicate : predicates_) { + NodeSet* new_nodes = NodeSet::Create(); + evaluation_context.size = nodes.size(); + evaluation_context.position = 0; for (const auto& node : nodes) { - evaluationContext.node = node; - ++evaluationContext.position; + evaluation_context.node = node; + ++evaluation_context.position; - if (predicate->evaluate(evaluationContext)) - newNodes->append(node); + if (predicate->Evaluate(evaluation_context)) + new_nodes->Append(node); } - nodes.swap(*newNodes); + nodes.Swap(*new_nodes); } return v; } -LocationPath::LocationPath() : m_absolute(false) { - setIsContextNodeSensitive(true); +LocationPath::LocationPath() : absolute_(false) { + SetIsContextNodeSensitive(true); } LocationPath::~LocationPath() {} DEFINE_TRACE(LocationPath) { - visitor->trace(m_steps); - Expression::trace(visitor); + visitor->Trace(steps_); + Expression::Trace(visitor); } -Value LocationPath::evaluate(EvaluationContext& evaluationContext) const { - EvaluationContext clonedContext = evaluationContext; +Value LocationPath::Evaluate(EvaluationContext& evaluation_context) const { + EvaluationContext cloned_context = evaluation_context; // http://www.w3.org/TR/xpath/ // Section 2, Location Paths: // "/ selects the document root (which is always the parent of the document @@ -99,101 +99,101 @@ Value LocationPath::evaluate(EvaluationContext& evaluationContext) const { // the spec and treat / as the root node of the detached tree. // This is for compatibility with Firefox, and also seems like a more // logical treatment of where you would expect the "root" to be. - Node* context = evaluationContext.node.get(); - if (m_absolute && context->getNodeType() != Node::kDocumentNode) { + Node* context = evaluation_context.node.Get(); + if (absolute_ && context->getNodeType() != Node::kDocumentNode) { if (context->isConnected()) context = context->ownerDocument(); else - context = &NodeTraversal::highestAncestorOrSelf(*context); + context = &NodeTraversal::HighestAncestorOrSelf(*context); } - NodeSet* nodes = NodeSet::create(); - nodes->append(context); - evaluate(clonedContext, *nodes); + NodeSet* nodes = NodeSet::Create(); + nodes->Append(context); + Evaluate(cloned_context, *nodes); - return Value(nodes, Value::adopt); + return Value(nodes, Value::kAdopt); } -void LocationPath::evaluate(EvaluationContext& context, NodeSet& nodes) const { - bool resultIsSorted = nodes.isSorted(); +void LocationPath::Evaluate(EvaluationContext& context, NodeSet& nodes) const { + bool result_is_sorted = nodes.IsSorted(); - for (const auto& step : m_steps) { - NodeSet* newNodes = NodeSet::create(); - HeapHashSet<Member<Node>> newNodesSet; + for (const auto& step : steps_) { + NodeSet* new_nodes = NodeSet::Create(); + HeapHashSet<Member<Node>> new_nodes_set; - bool needToCheckForDuplicateNodes = - !nodes.subtreesAreDisjoint() || - (step->getAxis() != Step::ChildAxis && - step->getAxis() != Step::SelfAxis && - step->getAxis() != Step::DescendantAxis && - step->getAxis() != Step::DescendantOrSelfAxis && - step->getAxis() != Step::AttributeAxis); + bool need_to_check_for_duplicate_nodes = + !nodes.SubtreesAreDisjoint() || + (step->GetAxis() != Step::kChildAxis && + step->GetAxis() != Step::kSelfAxis && + step->GetAxis() != Step::kDescendantAxis && + step->GetAxis() != Step::kDescendantOrSelfAxis && + step->GetAxis() != Step::kAttributeAxis); - if (needToCheckForDuplicateNodes) - resultIsSorted = false; + if (need_to_check_for_duplicate_nodes) + result_is_sorted = false; // This is a simplified check that can be improved to handle more cases. - if (nodes.subtreesAreDisjoint() && (step->getAxis() == Step::ChildAxis || - step->getAxis() == Step::SelfAxis)) - newNodes->markSubtreesDisjoint(true); + if (nodes.SubtreesAreDisjoint() && (step->GetAxis() == Step::kChildAxis || + step->GetAxis() == Step::kSelfAxis)) + new_nodes->MarkSubtreesDisjoint(true); - for (const auto& inputNode : nodes) { - NodeSet* matches = NodeSet::create(); - step->evaluate(context, inputNode, *matches); + for (const auto& input_node : nodes) { + NodeSet* matches = NodeSet::Create(); + step->Evaluate(context, input_node, *matches); - if (!matches->isSorted()) - resultIsSorted = false; + if (!matches->IsSorted()) + result_is_sorted = false; for (const auto& node : *matches) { - if (!needToCheckForDuplicateNodes || - newNodesSet.insert(node).isNewEntry) - newNodes->append(node); + if (!need_to_check_for_duplicate_nodes || + new_nodes_set.insert(node).is_new_entry) + new_nodes->Append(node); } } - nodes.swap(*newNodes); + nodes.Swap(*new_nodes); } - nodes.markSorted(resultIsSorted); + nodes.MarkSorted(result_is_sorted); } -void LocationPath::appendStep(Step* step) { - unsigned stepCount = m_steps.size(); - if (stepCount && optimizeStepPair(m_steps[stepCount - 1], step)) +void LocationPath::AppendStep(Step* step) { + unsigned step_count = steps_.size(); + if (step_count && OptimizeStepPair(steps_[step_count - 1], step)) return; - step->optimize(); - m_steps.push_back(step); + step->Optimize(); + steps_.push_back(step); } -void LocationPath::insertFirstStep(Step* step) { - if (m_steps.size() && optimizeStepPair(step, m_steps[0])) { - m_steps[0] = step; +void LocationPath::InsertFirstStep(Step* step) { + if (steps_.size() && OptimizeStepPair(step, steps_[0])) { + steps_[0] = step; return; } - step->optimize(); - m_steps.insert(0, step); + step->Optimize(); + steps_.insert(0, step); } Path::Path(Expression* filter, LocationPath* path) - : m_filter(filter), m_path(path) { - setIsContextNodeSensitive(filter->isContextNodeSensitive()); - setIsContextPositionSensitive(filter->isContextPositionSensitive()); - setIsContextSizeSensitive(filter->isContextSizeSensitive()); + : filter_(filter), path_(path) { + SetIsContextNodeSensitive(filter->IsContextNodeSensitive()); + SetIsContextPositionSensitive(filter->IsContextPositionSensitive()); + SetIsContextSizeSensitive(filter->IsContextSizeSensitive()); } Path::~Path() {} DEFINE_TRACE(Path) { - visitor->trace(m_filter); - visitor->trace(m_path); - Expression::trace(visitor); + visitor->Trace(filter_); + visitor->Trace(path_); + Expression::Trace(visitor); } -Value Path::evaluate(EvaluationContext& context) const { - Value v = m_filter->evaluate(context); +Value Path::Evaluate(EvaluationContext& context) const { + Value v = filter_->Evaluate(context); - NodeSet& nodes = v.modifiableNodeSet(context); - m_path->evaluate(context, nodes); + NodeSet& nodes = v.ModifiableNodeSet(context); + path_->Evaluate(context, nodes); return v; } diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathPath.h b/chromium/third_party/WebKit/Source/core/xml/XPathPath.h index 2737653a59f..7b8cd36143a 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XPathPath.h +++ b/chromium/third_party/WebKit/Source/core/xml/XPathPath.h @@ -43,13 +43,13 @@ class Filter final : public Expression { ~Filter() override; DECLARE_VIRTUAL_TRACE(); - Value evaluate(EvaluationContext&) const override; + Value Evaluate(EvaluationContext&) const override; private: - Value::Type resultType() const override { return Value::NodeSetValue; } + Value::Type ResultType() const override { return Value::kNodeSetValue; } - Member<Expression> m_expr; - HeapVector<Member<Predicate>> m_predicates; + Member<Expression> expr_; + HeapVector<Member<Predicate>> predicates_; }; class LocationPath final : public Expression { @@ -58,21 +58,21 @@ class LocationPath final : public Expression { ~LocationPath() override; DECLARE_VIRTUAL_TRACE(); - Value evaluate(EvaluationContext&) const override; - void setAbsolute(bool value) { - m_absolute = value; - setIsContextNodeSensitive(!m_absolute); + Value Evaluate(EvaluationContext&) const override; + void SetAbsolute(bool value) { + absolute_ = value; + SetIsContextNodeSensitive(!absolute_); } - void evaluate(EvaluationContext&, + void Evaluate(EvaluationContext&, NodeSet&) const; // nodes is an input/output parameter - void appendStep(Step*); - void insertFirstStep(Step*); + void AppendStep(Step*); + void InsertFirstStep(Step*); private: - Value::Type resultType() const override { return Value::NodeSetValue; } + Value::Type ResultType() const override { return Value::kNodeSetValue; } - HeapVector<Member<Step>> m_steps; - bool m_absolute; + HeapVector<Member<Step>> steps_; + bool absolute_; }; class Path final : public Expression { @@ -81,13 +81,13 @@ class Path final : public Expression { ~Path() override; DECLARE_VIRTUAL_TRACE(); - Value evaluate(EvaluationContext&) const override; + Value Evaluate(EvaluationContext&) const override; private: - Value::Type resultType() const override { return Value::NodeSetValue; } + Value::Type ResultType() const override { return Value::kNodeSetValue; } - Member<Expression> m_filter; - Member<LocationPath> m_path; + Member<Expression> filter_; + Member<LocationPath> path_; }; } // namespace XPath diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathPredicate.cpp b/chromium/third_party/WebKit/Source/core/xml/XPathPredicate.cpp index 0b8137b6632..b017f7b2ce6 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XPathPredicate.cpp +++ b/chromium/third_party/WebKit/Source/core/xml/XPathPredicate.cpp @@ -27,252 +27,252 @@ #include "core/xml/XPathPredicate.h" +#include <math.h> #include "core/xml/XPathFunctions.h" #include "core/xml/XPathUtil.h" -#include "wtf/MathExtras.h" -#include <math.h> +#include "platform/wtf/MathExtras.h" namespace blink { namespace XPath { -Number::Number(double value) : m_value(value) {} +Number::Number(double value) : value_(value) {} DEFINE_TRACE(Number) { - visitor->trace(m_value); - Expression::trace(visitor); + visitor->Trace(value_); + Expression::Trace(visitor); } -Value Number::evaluate(EvaluationContext&) const { - return m_value; +Value Number::Evaluate(EvaluationContext&) const { + return value_; } -StringExpression::StringExpression(const String& value) : m_value(value) {} +StringExpression::StringExpression(const String& value) : value_(value) {} DEFINE_TRACE(StringExpression) { - visitor->trace(m_value); - Expression::trace(visitor); + visitor->Trace(value_); + Expression::Trace(visitor); } -Value StringExpression::evaluate(EvaluationContext&) const { - return m_value; +Value StringExpression::Evaluate(EvaluationContext&) const { + return value_; } -Value Negative::evaluate(EvaluationContext& context) const { - Value p(subExpr(0)->evaluate(context)); - return -p.toNumber(); +Value Negative::Evaluate(EvaluationContext& context) const { + Value p(SubExpr(0)->Evaluate(context)); + return -p.ToNumber(); } NumericOp::NumericOp(Opcode opcode, Expression* lhs, Expression* rhs) - : m_opcode(opcode) { - addSubExpression(lhs); - addSubExpression(rhs); + : opcode_(opcode) { + AddSubExpression(lhs); + AddSubExpression(rhs); } -Value NumericOp::evaluate(EvaluationContext& context) const { - Value lhs(subExpr(0)->evaluate(context)); - Value rhs(subExpr(1)->evaluate(context)); - - double leftVal = lhs.toNumber(); - double rightVal = rhs.toNumber(); - - switch (m_opcode) { - case OP_Add: - return leftVal + rightVal; - case OP_Sub: - return leftVal - rightVal; - case OP_Mul: - return leftVal * rightVal; - case OP_Div: - return leftVal / rightVal; - case OP_Mod: - return fmod(leftVal, rightVal); +Value NumericOp::Evaluate(EvaluationContext& context) const { + Value lhs(SubExpr(0)->Evaluate(context)); + Value rhs(SubExpr(1)->Evaluate(context)); + + double left_val = lhs.ToNumber(); + double right_val = rhs.ToNumber(); + + switch (opcode_) { + case kOP_Add: + return left_val + right_val; + case kOP_Sub: + return left_val - right_val; + case kOP_Mul: + return left_val * right_val; + case kOP_Div: + return left_val / right_val; + case kOP_Mod: + return fmod(left_val, right_val); } NOTREACHED(); return 0.0; } EqTestOp::EqTestOp(Opcode opcode, Expression* lhs, Expression* rhs) - : m_opcode(opcode) { - addSubExpression(lhs); - addSubExpression(rhs); + : opcode_(opcode) { + AddSubExpression(lhs); + AddSubExpression(rhs); } -bool EqTestOp::compare(EvaluationContext& context, +bool EqTestOp::Compare(EvaluationContext& context, const Value& lhs, const Value& rhs) const { - if (lhs.isNodeSet()) { - const NodeSet& lhsSet = lhs.toNodeSet(&context); - if (rhs.isNodeSet()) { + if (lhs.IsNodeSet()) { + const NodeSet& lhs_set = lhs.ToNodeSet(&context); + if (rhs.IsNodeSet()) { // If both objects to be compared are node-sets, then the comparison // will be true if and only if there is a node in the first node-set // and a node in the second node-set such that the result of // performing the comparison on the string-values of the two nodes // is true. - const NodeSet& rhsSet = rhs.toNodeSet(&context); - for (const auto& leftNode : lhsSet) { - for (const auto& rightNode : rhsSet) { - if (compare(context, stringValue(leftNode), stringValue(rightNode))) + const NodeSet& rhs_set = rhs.ToNodeSet(&context); + for (const auto& left_node : lhs_set) { + for (const auto& right_node : rhs_set) { + if (Compare(context, StringValue(left_node), StringValue(right_node))) return true; } } return false; } - if (rhs.isNumber()) { + if (rhs.IsNumber()) { // If one object to be compared is a node-set and the other is a // number, then the comparison will be true if and only if there is // a node in the node-set such that the result of performing the // comparison on the number to be compared and on the result of // converting the string-value of that node to a number using the // number function is true. - for (const auto& leftNode : lhsSet) { - if (compare(context, Value(stringValue(leftNode)).toNumber(), rhs)) + for (const auto& left_node : lhs_set) { + if (Compare(context, Value(StringValue(left_node)).ToNumber(), rhs)) return true; } return false; } - if (rhs.isString()) { + if (rhs.IsString()) { // If one object to be compared is a node-set and the other is a // string, then the comparison will be true if and only if there is // a node in the node-set such that the result of performing the // comparison on the string-value of the node and the other string // is true. - for (const auto& leftNode : lhsSet) { - if (compare(context, stringValue(leftNode), rhs)) + for (const auto& left_node : lhs_set) { + if (Compare(context, StringValue(left_node), rhs)) return true; } return false; } - if (rhs.isBoolean()) { + if (rhs.IsBoolean()) { // If one object to be compared is a node-set and the other is a // boolean, then the comparison will be true if and only if the // result of performing the comparison on the boolean and on the // result of converting the node-set to a boolean using the boolean // function is true. - return compare(context, lhs.toBoolean(), rhs); + return Compare(context, lhs.ToBoolean(), rhs); } NOTREACHED(); } - if (rhs.isNodeSet()) { - const NodeSet& rhsSet = rhs.toNodeSet(&context); - if (lhs.isNumber()) { - for (const auto& rightNode : rhsSet) { - if (compare(context, lhs, Value(stringValue(rightNode)).toNumber())) + if (rhs.IsNodeSet()) { + const NodeSet& rhs_set = rhs.ToNodeSet(&context); + if (lhs.IsNumber()) { + for (const auto& right_node : rhs_set) { + if (Compare(context, lhs, Value(StringValue(right_node)).ToNumber())) return true; } return false; } - if (lhs.isString()) { - for (const auto& rightNode : rhsSet) { - if (compare(context, lhs, stringValue(rightNode))) + if (lhs.IsString()) { + for (const auto& right_node : rhs_set) { + if (Compare(context, lhs, StringValue(right_node))) return true; } return false; } - if (lhs.isBoolean()) - return compare(context, lhs, rhs.toBoolean()); + if (lhs.IsBoolean()) + return Compare(context, lhs, rhs.ToBoolean()); NOTREACHED(); } // Neither side is a NodeSet. - switch (m_opcode) { - case OpcodeEqual: - case OpcodeNotEqual: + switch (opcode_) { + case kOpcodeEqual: + case kOpcodeNotEqual: bool equal; - if (lhs.isBoolean() || rhs.isBoolean()) - equal = lhs.toBoolean() == rhs.toBoolean(); - else if (lhs.isNumber() || rhs.isNumber()) - equal = lhs.toNumber() == rhs.toNumber(); + if (lhs.IsBoolean() || rhs.IsBoolean()) + equal = lhs.ToBoolean() == rhs.ToBoolean(); + else if (lhs.IsNumber() || rhs.IsNumber()) + equal = lhs.ToNumber() == rhs.ToNumber(); else - equal = lhs.toString() == rhs.toString(); + equal = lhs.ToString() == rhs.ToString(); - if (m_opcode == OpcodeEqual) + if (opcode_ == kOpcodeEqual) return equal; return !equal; - case OpcodeGreaterThan: - return lhs.toNumber() > rhs.toNumber(); - case OpcodeGreaterOrEqual: - return lhs.toNumber() >= rhs.toNumber(); - case OpcodeLessThan: - return lhs.toNumber() < rhs.toNumber(); - case OpcodeLessOrEqual: - return lhs.toNumber() <= rhs.toNumber(); + case kOpcodeGreaterThan: + return lhs.ToNumber() > rhs.ToNumber(); + case kOpcodeGreaterOrEqual: + return lhs.ToNumber() >= rhs.ToNumber(); + case kOpcodeLessThan: + return lhs.ToNumber() < rhs.ToNumber(); + case kOpcodeLessOrEqual: + return lhs.ToNumber() <= rhs.ToNumber(); } NOTREACHED(); return false; } -Value EqTestOp::evaluate(EvaluationContext& context) const { - Value lhs(subExpr(0)->evaluate(context)); - Value rhs(subExpr(1)->evaluate(context)); +Value EqTestOp::Evaluate(EvaluationContext& context) const { + Value lhs(SubExpr(0)->Evaluate(context)); + Value rhs(SubExpr(1)->Evaluate(context)); - return compare(context, lhs, rhs); + return Compare(context, lhs, rhs); } LogicalOp::LogicalOp(Opcode opcode, Expression* lhs, Expression* rhs) - : m_opcode(opcode) { - addSubExpression(lhs); - addSubExpression(rhs); + : opcode_(opcode) { + AddSubExpression(lhs); + AddSubExpression(rhs); } -bool LogicalOp::shortCircuitOn() const { - return m_opcode != OP_And; +bool LogicalOp::ShortCircuitOn() const { + return opcode_ != kOP_And; } -Value LogicalOp::evaluate(EvaluationContext& context) const { - Value lhs(subExpr(0)->evaluate(context)); +Value LogicalOp::Evaluate(EvaluationContext& context) const { + Value lhs(SubExpr(0)->Evaluate(context)); // This is not only an optimization, http://www.w3.org/TR/xpath // dictates that we must do short-circuit evaluation - bool lhsBool = lhs.toBoolean(); - if (lhsBool == shortCircuitOn()) - return lhsBool; + bool lhs_bool = lhs.ToBoolean(); + if (lhs_bool == ShortCircuitOn()) + return lhs_bool; - return subExpr(1)->evaluate(context).toBoolean(); + return SubExpr(1)->Evaluate(context).ToBoolean(); } -Value Union::evaluate(EvaluationContext& context) const { - Value lhsResult = subExpr(0)->evaluate(context); - Value rhs = subExpr(1)->evaluate(context); +Value Union::Evaluate(EvaluationContext& context) const { + Value lhs_result = SubExpr(0)->Evaluate(context); + Value rhs = SubExpr(1)->Evaluate(context); - NodeSet& resultSet = lhsResult.modifiableNodeSet(context); - const NodeSet& rhsNodes = rhs.toNodeSet(&context); + NodeSet& result_set = lhs_result.ModifiableNodeSet(context); + const NodeSet& rhs_nodes = rhs.ToNodeSet(&context); HeapHashSet<Member<Node>> nodes; - for (const auto& node : resultSet) + for (const auto& node : result_set) nodes.insert(node); - for (const auto& node : rhsNodes) { - if (nodes.insert(node).isNewEntry) - resultSet.append(node); + for (const auto& node : rhs_nodes) { + if (nodes.insert(node).is_new_entry) + result_set.Append(node); } // It is also possible to use merge sort to avoid making the result // unsorted; but this would waste the time in cases when order is not // important. - resultSet.markSorted(false); - return lhsResult; + result_set.MarkSorted(false); + return lhs_result; } -Predicate::Predicate(Expression* expr) : m_expr(expr) {} +Predicate::Predicate(Expression* expr) : expr_(expr) {} DEFINE_TRACE(Predicate) { - visitor->trace(m_expr); + visitor->Trace(expr_); } -bool Predicate::evaluate(EvaluationContext& context) const { - DCHECK(m_expr); +bool Predicate::Evaluate(EvaluationContext& context) const { + DCHECK(expr_); - Value result(m_expr->evaluate(context)); + Value result(expr_->Evaluate(context)); // foo[3] means foo[position()=3] - if (result.isNumber()) - return EqTestOp(EqTestOp::OpcodeEqual, createFunction("position"), - new Number(result.toNumber())) - .evaluate(context) - .toBoolean(); + if (result.IsNumber()) + return EqTestOp(EqTestOp::kOpcodeEqual, CreateFunction("position"), + new Number(result.ToNumber())) + .Evaluate(context) + .ToBoolean(); - return result.toBoolean(); + return result.ToBoolean(); } } // namespace XPath diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathPredicate.h b/chromium/third_party/WebKit/Source/core/xml/XPathPredicate.h index da44c9bfe2d..68e697e4b3b 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XPathPredicate.h +++ b/chromium/third_party/WebKit/Source/core/xml/XPathPredicate.h @@ -41,10 +41,10 @@ class CORE_EXPORT Number final : public Expression { DECLARE_VIRTUAL_TRACE(); private: - Value evaluate(EvaluationContext&) const override; - Value::Type resultType() const override { return Value::NumberValue; } + Value Evaluate(EvaluationContext&) const override; + Value::Type ResultType() const override { return Value::kNumberValue; } - Value m_value; + Value value_; }; class CORE_EXPORT StringExpression final : public Expression { @@ -53,67 +53,67 @@ class CORE_EXPORT StringExpression final : public Expression { DECLARE_VIRTUAL_TRACE(); private: - Value evaluate(EvaluationContext&) const override; - Value::Type resultType() const override { return Value::StringValue; } + Value Evaluate(EvaluationContext&) const override; + Value::Type ResultType() const override { return Value::kStringValue; } - Value m_value; + Value value_; }; class Negative final : public Expression { private: - Value evaluate(EvaluationContext&) const override; - Value::Type resultType() const override { return Value::NumberValue; } + Value Evaluate(EvaluationContext&) const override; + Value::Type ResultType() const override { return Value::kNumberValue; } }; class NumericOp final : public Expression { public: - enum Opcode { OP_Add, OP_Sub, OP_Mul, OP_Div, OP_Mod }; + enum Opcode { kOP_Add, kOP_Sub, kOP_Mul, kOP_Div, kOP_Mod }; NumericOp(Opcode, Expression* lhs, Expression* rhs); private: - Value evaluate(EvaluationContext&) const override; - Value::Type resultType() const override { return Value::NumberValue; } + Value Evaluate(EvaluationContext&) const override; + Value::Type ResultType() const override { return Value::kNumberValue; } - Opcode m_opcode; + Opcode opcode_; }; class EqTestOp final : public Expression { public: enum Opcode { - OpcodeEqual, - OpcodeNotEqual, - OpcodeGreaterThan, - OpcodeLessThan, - OpcodeGreaterOrEqual, - OpcodeLessOrEqual + kOpcodeEqual, + kOpcodeNotEqual, + kOpcodeGreaterThan, + kOpcodeLessThan, + kOpcodeGreaterOrEqual, + kOpcodeLessOrEqual }; EqTestOp(Opcode, Expression* lhs, Expression* rhs); - Value evaluate(EvaluationContext&) const override; + Value Evaluate(EvaluationContext&) const override; private: - Value::Type resultType() const override { return Value::BooleanValue; } - bool compare(EvaluationContext&, const Value&, const Value&) const; + Value::Type ResultType() const override { return Value::kBooleanValue; } + bool Compare(EvaluationContext&, const Value&, const Value&) const; - Opcode m_opcode; + Opcode opcode_; }; class LogicalOp final : public Expression { public: - enum Opcode { OP_And, OP_Or }; + enum Opcode { kOP_And, kOP_Or }; LogicalOp(Opcode, Expression* lhs, Expression* rhs); private: - Value::Type resultType() const override { return Value::BooleanValue; } - bool shortCircuitOn() const; - Value evaluate(EvaluationContext&) const override; + Value::Type ResultType() const override { return Value::kBooleanValue; } + bool ShortCircuitOn() const; + Value Evaluate(EvaluationContext&) const override; - Opcode m_opcode; + Opcode opcode_; }; class Union final : public Expression { private: - Value evaluate(EvaluationContext&) const override; - Value::Type resultType() const override { return Value::NodeSetValue; } + Value Evaluate(EvaluationContext&) const override; + Value::Type ResultType() const override { return Value::kNodeSetValue; } }; class Predicate final : public GarbageCollected<Predicate> { @@ -123,17 +123,17 @@ class Predicate final : public GarbageCollected<Predicate> { explicit Predicate(Expression*); DECLARE_TRACE(); - bool evaluate(EvaluationContext&) const; - bool isContextPositionSensitive() const { - return m_expr->isContextPositionSensitive() || - m_expr->resultType() == Value::NumberValue; + bool Evaluate(EvaluationContext&) const; + bool IsContextPositionSensitive() const { + return expr_->IsContextPositionSensitive() || + expr_->ResultType() == Value::kNumberValue; } - bool isContextSizeSensitive() const { - return m_expr->isContextSizeSensitive(); + bool IsContextSizeSensitive() const { + return expr_->IsContextSizeSensitive(); } private: - Member<Expression> m_expr; + Member<Expression> expr_; }; } // namespace XPath diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathResult.cpp b/chromium/third_party/WebKit/Source/core/xml/XPathResult.cpp index c827f67c1bb..be13417a65a 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XPathResult.cpp +++ b/chromium/third_party/WebKit/Source/core/xml/XPathResult.cpp @@ -37,126 +37,126 @@ namespace blink { using namespace XPath; XPathResult::XPathResult(EvaluationContext& context, const Value& value) - : m_value(value), m_nodeSetPosition(0), m_domTreeVersion(0) { - switch (m_value.getType()) { - case Value::BooleanValue: - m_resultType = kBooleanType; + : value_(value), node_set_position_(0), dom_tree_version_(0) { + switch (value_.GetType()) { + case Value::kBooleanValue: + result_type_ = kBooleanType; return; - case Value::NumberValue: - m_resultType = kNumberType; + case Value::kNumberValue: + result_type_ = kNumberType; return; - case Value::StringValue: - m_resultType = kStringType; + case Value::kStringValue: + result_type_ = kStringType; return; - case Value::NodeSetValue: - m_resultType = kUnorderedNodeIteratorType; - m_nodeSetPosition = 0; - m_nodeSet = NodeSet::create(m_value.toNodeSet(&context)); - m_document = &context.node->document(); - m_domTreeVersion = m_document->domTreeVersion(); + case Value::kNodeSetValue: + result_type_ = kUnorderedNodeIteratorType; + node_set_position_ = 0; + node_set_ = NodeSet::Create(value_.ToNodeSet(&context)); + document_ = &context.node->GetDocument(); + dom_tree_version_ = document_->DomTreeVersion(); return; } NOTREACHED(); } DEFINE_TRACE(XPathResult) { - visitor->trace(m_value); - visitor->trace(m_nodeSet); - visitor->trace(m_document); + visitor->Trace(value_); + visitor->Trace(node_set_); + visitor->Trace(document_); } -void XPathResult::convertTo(unsigned short type, - ExceptionState& exceptionState) { +void XPathResult::ConvertTo(unsigned short type, + ExceptionState& exception_state) { switch (type) { case kAnyType: break; case kNumberType: - m_resultType = type; - m_value = m_value.toNumber(); + result_type_ = type; + value_ = value_.ToNumber(); break; case kStringType: - m_resultType = type; - m_value = m_value.toString(); + result_type_ = type; + value_ = value_.ToString(); break; case kBooleanType: - m_resultType = type; - m_value = m_value.toBoolean(); + result_type_ = type; + value_ = value_.ToBoolean(); break; case kUnorderedNodeIteratorType: case kUnorderedNodeSnapshotType: case kAnyUnorderedNodeType: // This is correct - singleNodeValue() will take care of ordering. case kFirstOrderedNodeType: - if (!m_value.isNodeSet()) { - exceptionState.throwTypeError( + if (!value_.IsNodeSet()) { + exception_state.ThrowTypeError( "The result is not a node set, and therefore cannot be converted " "to the desired type."); return; } - m_resultType = type; + result_type_ = type; break; case kOrderedNodeIteratorType: - if (!m_value.isNodeSet()) { - exceptionState.throwTypeError( + if (!value_.IsNodeSet()) { + exception_state.ThrowTypeError( "The result is not a node set, and therefore cannot be converted " "to the desired type."); return; } - nodeSet().sort(); - m_resultType = type; + GetNodeSet().Sort(); + result_type_ = type; break; case kOrderedNodeSnapshotType: - if (!m_value.isNodeSet()) { - exceptionState.throwTypeError( + if (!value_.IsNodeSet()) { + exception_state.ThrowTypeError( "The result is not a node set, and therefore cannot be converted " "to the desired type."); return; } - m_value.toNodeSet(0).sort(); - m_resultType = type; + value_.ToNodeSet(0).Sort(); + result_type_ = type; break; } } unsigned short XPathResult::resultType() const { - return m_resultType; + return result_type_; } -double XPathResult::numberValue(ExceptionState& exceptionState) const { +double XPathResult::numberValue(ExceptionState& exception_state) const { if (resultType() != kNumberType) { - exceptionState.throwTypeError("The result type is not a number."); + exception_state.ThrowTypeError("The result type is not a number."); return 0.0; } - return m_value.toNumber(); + return value_.ToNumber(); } -String XPathResult::stringValue(ExceptionState& exceptionState) const { +String XPathResult::stringValue(ExceptionState& exception_state) const { if (resultType() != kStringType) { - exceptionState.throwTypeError("The result type is not a string."); + exception_state.ThrowTypeError("The result type is not a string."); return String(); } - return m_value.toString(); + return value_.ToString(); } -bool XPathResult::booleanValue(ExceptionState& exceptionState) const { +bool XPathResult::booleanValue(ExceptionState& exception_state) const { if (resultType() != kBooleanType) { - exceptionState.throwTypeError("The result type is not a boolean."); + exception_state.ThrowTypeError("The result type is not a boolean."); return false; } - return m_value.toBoolean(); + return value_.ToBoolean(); } -Node* XPathResult::singleNodeValue(ExceptionState& exceptionState) const { +Node* XPathResult::singleNodeValue(ExceptionState& exception_state) const { if (resultType() != kAnyUnorderedNodeType && resultType() != kFirstOrderedNodeType) { - exceptionState.throwTypeError("The result type is not a single node."); + exception_state.ThrowTypeError("The result type is not a single node."); return nullptr; } - const NodeSet& nodes = m_value.toNodeSet(0); + const NodeSet& nodes = value_.ToNodeSet(0); if (resultType() == kFirstOrderedNodeType) - return nodes.firstNode(); - return nodes.anyNode(); + return nodes.FirstNode(); + return nodes.AnyNode(); } bool XPathResult::invalidIteratorState() const { @@ -164,53 +164,53 @@ bool XPathResult::invalidIteratorState() const { resultType() != kOrderedNodeIteratorType) return false; - DCHECK(m_document); - return m_document->domTreeVersion() != m_domTreeVersion; + DCHECK(document_); + return document_->DomTreeVersion() != dom_tree_version_; } -unsigned XPathResult::snapshotLength(ExceptionState& exceptionState) const { +unsigned XPathResult::snapshotLength(ExceptionState& exception_state) const { if (resultType() != kUnorderedNodeSnapshotType && resultType() != kOrderedNodeSnapshotType) { - exceptionState.throwTypeError("The result type is not a snapshot."); + exception_state.ThrowTypeError("The result type is not a snapshot."); return 0; } - return m_value.toNodeSet(0).size(); + return value_.ToNodeSet(0).size(); } -Node* XPathResult::iterateNext(ExceptionState& exceptionState) { +Node* XPathResult::iterateNext(ExceptionState& exception_state) { if (resultType() != kUnorderedNodeIteratorType && resultType() != kOrderedNodeIteratorType) { - exceptionState.throwTypeError("The result type is not an iterator."); + exception_state.ThrowTypeError("The result type is not an iterator."); return nullptr; } if (invalidIteratorState()) { - exceptionState.throwDOMException( - InvalidStateError, + exception_state.ThrowDOMException( + kInvalidStateError, "The document has mutated since the result was returned."); return nullptr; } - if (m_nodeSetPosition + 1 > nodeSet().size()) + if (node_set_position_ + 1 > GetNodeSet().size()) return nullptr; - Node* node = nodeSet()[m_nodeSetPosition]; + Node* node = GetNodeSet()[node_set_position_]; - m_nodeSetPosition++; + node_set_position_++; return node; } Node* XPathResult::snapshotItem(unsigned index, - ExceptionState& exceptionState) { + ExceptionState& exception_state) { if (resultType() != kUnorderedNodeSnapshotType && resultType() != kOrderedNodeSnapshotType) { - exceptionState.throwTypeError("The result type is not a snapshot."); + exception_state.ThrowTypeError("The result type is not a snapshot."); return nullptr; } - const NodeSet& nodes = m_value.toNodeSet(0); + const NodeSet& nodes = value_.ToNodeSet(0); if (index >= nodes.size()) return nullptr; diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathResult.h b/chromium/third_party/WebKit/Source/core/xml/XPathResult.h index 2785d2b58c0..4a27b35e54d 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XPathResult.h +++ b/chromium/third_party/WebKit/Source/core/xml/XPathResult.h @@ -30,7 +30,7 @@ #include "bindings/core/v8/ScriptWrappable.h" #include "core/xml/XPathValue.h" #include "platform/heap/Handle.h" -#include "wtf/Forward.h" +#include "platform/wtf/Forward.h" namespace blink { @@ -60,12 +60,12 @@ class XPathResult final : public GarbageCollected<XPathResult>, kFirstOrderedNodeType = 9 }; - static XPathResult* create(XPath::EvaluationContext& context, + static XPathResult* Create(XPath::EvaluationContext& context, const XPath::Value& value) { return new XPathResult(context, value); } - void convertTo(unsigned short type, ExceptionState&); + void ConvertTo(unsigned short type, ExceptionState&); unsigned short resultType() const; @@ -79,21 +79,21 @@ class XPathResult final : public GarbageCollected<XPathResult>, Node* iterateNext(ExceptionState&); Node* snapshotItem(unsigned index, ExceptionState&); - const XPath::Value& value() const { return m_value; } + const XPath::Value& GetValue() const { return value_; } DECLARE_TRACE(); private: XPathResult(XPath::EvaluationContext&, const XPath::Value&); - XPath::NodeSet& nodeSet() { return *m_nodeSet; } + XPath::NodeSet& GetNodeSet() { return *node_set_; } - XPath::Value m_value; - unsigned m_nodeSetPosition; + XPath::Value value_; + unsigned node_set_position_; Member<XPath::NodeSet> - m_nodeSet; // FIXME: why duplicate the node set stored in m_value? - unsigned short m_resultType; - Member<Document> m_document; - uint64_t m_domTreeVersion; + node_set_; // FIXME: why duplicate the node set stored in m_value? + unsigned short result_type_; + Member<Document> document_; + uint64_t dom_tree_version_; }; } // namespace blink diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathStep.cpp b/chromium/third_party/WebKit/Source/core/xml/XPathStep.cpp index b9c8d6ab4e7..68a1d1d9d5e 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XPathStep.cpp +++ b/chromium/third_party/WebKit/Source/core/xml/XPathStep.cpp @@ -38,25 +38,25 @@ namespace blink { namespace XPath { -Step::Step(Axis axis, const NodeTest& nodeTest) - : m_axis(axis), m_nodeTest(new NodeTest(nodeTest)) {} +Step::Step(Axis axis, const NodeTest& node_test) + : axis_(axis), node_test_(new NodeTest(node_test)) {} Step::Step(Axis axis, - const NodeTest& nodeTest, + const NodeTest& node_test, HeapVector<Member<Predicate>>& predicates) - : m_axis(axis), m_nodeTest(new NodeTest(nodeTest)) { - m_predicates.swap(predicates); + : axis_(axis), node_test_(new NodeTest(node_test)) { + predicates_.Swap(predicates); } Step::~Step() {} DEFINE_TRACE(Step) { - visitor->trace(m_nodeTest); - visitor->trace(m_predicates); - ParseNode::trace(visitor); + visitor->Trace(node_test_); + visitor->Trace(predicates_); + ParseNode::Trace(visitor); } -void Step::optimize() { +void Step::Optimize() { // Evaluate predicates as part of node test if possible to avoid building // unnecessary NodeSets. // E.g., there is no need to build a set of all "foo" nodes to evaluate @@ -64,92 +64,93 @@ void Step::optimize() { // This optimization can be applied to predicates that are not context node // list sensitive, or to first predicate that is only context position // sensitive, e.g. foo[position() mod 2 = 0]. - HeapVector<Member<Predicate>> remainingPredicates; - for (const auto& predicate : m_predicates) { - if ((!predicate->isContextPositionSensitive() || - nodeTest().mergedPredicates().isEmpty()) && - !predicate->isContextSizeSensitive() && remainingPredicates.isEmpty()) { - nodeTest().mergedPredicates().push_back(predicate); + HeapVector<Member<Predicate>> remaining_predicates; + for (const auto& predicate : predicates_) { + if ((!predicate->IsContextPositionSensitive() || + GetNodeTest().MergedPredicates().IsEmpty()) && + !predicate->IsContextSizeSensitive() && + remaining_predicates.IsEmpty()) { + GetNodeTest().MergedPredicates().push_back(predicate); } else { - remainingPredicates.push_back(predicate); + remaining_predicates.push_back(predicate); } } - swap(remainingPredicates, m_predicates); + swap(remaining_predicates, predicates_); } -bool optimizeStepPair(Step* first, Step* second) { - if (first->m_axis == Step::DescendantOrSelfAxis && - first->nodeTest().getKind() == Step::NodeTest::AnyNodeTest && - !first->m_predicates.size() && - !first->nodeTest().mergedPredicates().size()) { - DCHECK(first->nodeTest().data().isEmpty()); - DCHECK(first->nodeTest().namespaceURI().isEmpty()); +bool OptimizeStepPair(Step* first, Step* second) { + if (first->axis_ == Step::kDescendantOrSelfAxis && + first->GetNodeTest().GetKind() == Step::NodeTest::kAnyNodeTest && + !first->predicates_.size() && + !first->GetNodeTest().MergedPredicates().size()) { + DCHECK(first->GetNodeTest().Data().IsEmpty()); + DCHECK(first->GetNodeTest().NamespaceURI().IsEmpty()); // Optimize the common case of "//" AKA // /descendant-or-self::node()/child::NodeTest to /descendant::NodeTest. - if (second->m_axis == Step::ChildAxis && - second->predicatesAreContextListInsensitive()) { - first->m_axis = Step::DescendantAxis; - first->nodeTest() = Step::NodeTest(second->nodeTest().getKind(), - second->nodeTest().data(), - second->nodeTest().namespaceURI()); - swap(second->nodeTest().mergedPredicates(), - first->nodeTest().mergedPredicates()); - swap(second->m_predicates, first->m_predicates); - first->optimize(); + if (second->axis_ == Step::kChildAxis && + second->PredicatesAreContextListInsensitive()) { + first->axis_ = Step::kDescendantAxis; + first->GetNodeTest() = Step::NodeTest( + second->GetNodeTest().GetKind(), second->GetNodeTest().Data(), + second->GetNodeTest().NamespaceURI()); + swap(second->GetNodeTest().MergedPredicates(), + first->GetNodeTest().MergedPredicates()); + swap(second->predicates_, first->predicates_); + first->Optimize(); return true; } } return false; } -bool Step::predicatesAreContextListInsensitive() const { - for (const auto& predicate : m_predicates) { - if (predicate->isContextPositionSensitive() || - predicate->isContextSizeSensitive()) +bool Step::PredicatesAreContextListInsensitive() const { + for (const auto& predicate : predicates_) { + if (predicate->IsContextPositionSensitive() || + predicate->IsContextSizeSensitive()) return false; } - for (const auto& predicate : nodeTest().mergedPredicates()) { - if (predicate->isContextPositionSensitive() || - predicate->isContextSizeSensitive()) + for (const auto& predicate : GetNodeTest().MergedPredicates()) { + if (predicate->IsContextPositionSensitive() || + predicate->IsContextSizeSensitive()) return false; } return true; } -void Step::evaluate(EvaluationContext& evaluationContext, +void Step::Evaluate(EvaluationContext& evaluation_context, Node* context, NodeSet& nodes) const { - evaluationContext.position = 0; + evaluation_context.position = 0; - nodesInAxis(evaluationContext, context, nodes); + NodesInAxis(evaluation_context, context, nodes); // Check predicates that couldn't be merged into node test. - for (const auto& predicate : m_predicates) { - NodeSet* newNodes = NodeSet::create(); - if (!nodes.isSorted()) - newNodes->markSorted(false); + for (const auto& predicate : predicates_) { + NodeSet* new_nodes = NodeSet::Create(); + if (!nodes.IsSorted()) + new_nodes->MarkSorted(false); for (unsigned j = 0; j < nodes.size(); j++) { Node* node = nodes[j]; - evaluationContext.node = node; - evaluationContext.size = nodes.size(); - evaluationContext.position = j + 1; - if (predicate->evaluate(evaluationContext)) - newNodes->append(node); + evaluation_context.node = node; + evaluation_context.size = nodes.size(); + evaluation_context.position = j + 1; + if (predicate->Evaluate(evaluation_context)) + new_nodes->Append(node); } - nodes.swap(*newNodes); + nodes.Swap(*new_nodes); } } #if DCHECK_IS_ON() -static inline Node::NodeType primaryNodeType(Step::Axis axis) { +static inline Node::NodeType PrimaryNodeType(Step::Axis axis) { switch (axis) { - case Step::AttributeAxis: + case Step::kAttributeAxis: return Node::kAttributeNode; default: return Node::kElementNode; @@ -158,94 +159,97 @@ static inline Node::NodeType primaryNodeType(Step::Axis axis) { #endif // Evaluate NodeTest without considering merged predicates. -static inline bool nodeMatchesBasicTest(Node* node, +static inline bool NodeMatchesBasicTest(Node* node, Step::Axis axis, - const Step::NodeTest& nodeTest) { - switch (nodeTest.getKind()) { - case Step::NodeTest::TextNodeTest: { + const Step::NodeTest& node_test) { + switch (node_test.GetKind()) { + case Step::NodeTest::kTextNodeTest: { Node::NodeType type = node->getNodeType(); return type == Node::kTextNode || type == Node::kCdataSectionNode; } - case Step::NodeTest::CommentNodeTest: + case Step::NodeTest::kCommentNodeTest: return node->getNodeType() == Node::kCommentNode; - case Step::NodeTest::ProcessingInstructionNodeTest: { - const AtomicString& name = nodeTest.data(); + case Step::NodeTest::kProcessingInstructionNodeTest: { + const AtomicString& name = node_test.Data(); return node->getNodeType() == Node::kProcessingInstructionNode && - (name.isEmpty() || node->nodeName() == name); + (name.IsEmpty() || node->nodeName() == name); } - case Step::NodeTest::AnyNodeTest: + case Step::NodeTest::kAnyNodeTest: return true; - case Step::NodeTest::NameTest: { - const AtomicString& name = nodeTest.data(); - const AtomicString& namespaceURI = nodeTest.namespaceURI(); + case Step::NodeTest::kNameTest: { + const AtomicString& name = node_test.Data(); + const AtomicString& namespace_uri = node_test.NamespaceURI(); - if (axis == Step::AttributeAxis) { - Attr* attr = toAttr(node); + if (axis == Step::kAttributeAxis) { + Attr* attr = ToAttr(node); // In XPath land, namespace nodes are not accessible on the // attribute axis. if (attr->namespaceURI() == XMLNSNames::xmlnsNamespaceURI) return false; - if (name == starAtom) - return namespaceURI.isEmpty() || attr->namespaceURI() == namespaceURI; + if (name == g_star_atom) + return namespace_uri.IsEmpty() || + attr->namespaceURI() == namespace_uri; return attr->localName() == name && - attr->namespaceURI() == namespaceURI; + attr->namespaceURI() == namespace_uri; } // Node test on the namespace axis is not implemented yet, the caller // has a check for it. - DCHECK_NE(Step::NamespaceAxis, axis); + DCHECK_NE(Step::kNamespaceAxis, axis); // For other axes, the principal node type is element. #if DCHECK_IS_ON() - DCHECK_EQ(Node::kElementNode, primaryNodeType(axis)); + DCHECK_EQ(Node::kElementNode, PrimaryNodeType(axis)); #endif - if (!node->isElementNode()) + if (!node->IsElementNode()) return false; - Element& element = toElement(*node); + Element& element = ToElement(*node); - if (name == starAtom) - return namespaceURI.isEmpty() || namespaceURI == element.namespaceURI(); + if (name == g_star_atom) + return namespace_uri.IsEmpty() || + namespace_uri == element.namespaceURI(); - if (element.document().isHTMLDocument()) { - if (element.isHTMLElement()) { + if (element.GetDocument().IsHTMLDocument()) { + if (element.IsHTMLElement()) { // Paths without namespaces should match HTML elements in HTML // documents despite those having an XHTML namespace. Names are // compared case-insensitively. - return equalIgnoringCase(element.localName(), name) && - (namespaceURI.isNull() || - namespaceURI == element.namespaceURI()); + return DeprecatedEqualIgnoringCase(element.localName(), name) && + (namespace_uri.IsNull() || + namespace_uri == element.namespaceURI()); } // An expression without any prefix shouldn't match no-namespace // nodes (because HTML5 says so). - return element.hasLocalName(name) && - namespaceURI == element.namespaceURI() && !namespaceURI.isNull(); + return element.HasLocalName(name) && + namespace_uri == element.namespaceURI() && + !namespace_uri.IsNull(); } - return element.hasLocalName(name) && - namespaceURI == element.namespaceURI(); + return element.HasLocalName(name) && + namespace_uri == element.namespaceURI(); } } NOTREACHED(); return false; } -static inline bool nodeMatches(EvaluationContext& evaluationContext, +static inline bool NodeMatches(EvaluationContext& evaluation_context, Node* node, Step::Axis axis, - const Step::NodeTest& nodeTest) { - if (!nodeMatchesBasicTest(node, axis, nodeTest)) + const Step::NodeTest& node_test) { + if (!NodeMatchesBasicTest(node, axis, node_test)) return false; // Only the first merged predicate may depend on position. - ++evaluationContext.position; + ++evaluation_context.position; - for (const auto& predicate : nodeTest.mergedPredicates()) { - evaluationContext.node = node; + for (const auto& predicate : node_test.MergedPredicates()) { + evaluation_context.node = node; // No need to set context size - we only get here when evaluating // predicates that do not depend on it. - if (!predicate->evaluate(evaluationContext)) + if (!predicate->Evaluate(evaluation_context)) return false; } @@ -254,188 +258,197 @@ static inline bool nodeMatches(EvaluationContext& evaluationContext, // Result nodes are ordered in axis order. Node test (including merged // predicates) is applied. -void Step::nodesInAxis(EvaluationContext& evaluationContext, +void Step::NodesInAxis(EvaluationContext& evaluation_context, Node* context, NodeSet& nodes) const { - DCHECK(nodes.isEmpty()); - switch (m_axis) { - case ChildAxis: + DCHECK(nodes.IsEmpty()); + switch (axis_) { + case kChildAxis: // In XPath model, attribute nodes do not have children. - if (context->isAttributeNode()) + if (context->IsAttributeNode()) return; for (Node* n = context->firstChild(); n; n = n->nextSibling()) { - if (nodeMatches(evaluationContext, n, ChildAxis, nodeTest())) - nodes.append(n); + if (NodeMatches(evaluation_context, n, kChildAxis, GetNodeTest())) + nodes.Append(n); } return; - case DescendantAxis: + case kDescendantAxis: // In XPath model, attribute nodes do not have children. - if (context->isAttributeNode()) + if (context->IsAttributeNode()) return; - for (Node& n : NodeTraversal::descendantsOf(*context)) { - if (nodeMatches(evaluationContext, &n, DescendantAxis, nodeTest())) - nodes.append(&n); + for (Node& n : NodeTraversal::DescendantsOf(*context)) { + if (NodeMatches(evaluation_context, &n, kDescendantAxis, GetNodeTest())) + nodes.Append(&n); } return; - case ParentAxis: - if (context->isAttributeNode()) { - Element* n = toAttr(context)->ownerElement(); - if (nodeMatches(evaluationContext, n, ParentAxis, nodeTest())) - nodes.append(n); + case kParentAxis: + if (context->IsAttributeNode()) { + Element* n = ToAttr(context)->ownerElement(); + if (NodeMatches(evaluation_context, n, kParentAxis, GetNodeTest())) + nodes.Append(n); } else { ContainerNode* n = context->parentNode(); - if (n && nodeMatches(evaluationContext, n, ParentAxis, nodeTest())) - nodes.append(n); + if (n && NodeMatches(evaluation_context, n, kParentAxis, GetNodeTest())) + nodes.Append(n); } return; - case AncestorAxis: { + case kAncestorAxis: { Node* n = context; - if (context->isAttributeNode()) { - n = toAttr(context)->ownerElement(); - if (nodeMatches(evaluationContext, n, AncestorAxis, nodeTest())) - nodes.append(n); + if (context->IsAttributeNode()) { + n = ToAttr(context)->ownerElement(); + if (NodeMatches(evaluation_context, n, kAncestorAxis, GetNodeTest())) + nodes.Append(n); } for (n = n->parentNode(); n; n = n->parentNode()) { - if (nodeMatches(evaluationContext, n, AncestorAxis, nodeTest())) - nodes.append(n); + if (NodeMatches(evaluation_context, n, kAncestorAxis, GetNodeTest())) + nodes.Append(n); } - nodes.markSorted(false); + nodes.MarkSorted(false); return; } - case FollowingSiblingAxis: + case kFollowingSiblingAxis: if (context->getNodeType() == Node::kAttributeNode) return; for (Node* n = context->nextSibling(); n; n = n->nextSibling()) { - if (nodeMatches(evaluationContext, n, FollowingSiblingAxis, nodeTest())) - nodes.append(n); + if (NodeMatches(evaluation_context, n, kFollowingSiblingAxis, + GetNodeTest())) + nodes.Append(n); } return; - case PrecedingSiblingAxis: + case kPrecedingSiblingAxis: if (context->getNodeType() == Node::kAttributeNode) return; for (Node* n = context->previousSibling(); n; n = n->previousSibling()) { - if (nodeMatches(evaluationContext, n, PrecedingSiblingAxis, nodeTest())) - nodes.append(n); + if (NodeMatches(evaluation_context, n, kPrecedingSiblingAxis, + GetNodeTest())) + nodes.Append(n); } - nodes.markSorted(false); + nodes.MarkSorted(false); return; - case FollowingAxis: - if (context->isAttributeNode()) { + case kFollowingAxis: + if (context->IsAttributeNode()) { for (Node& p : - NodeTraversal::startsAfter(*toAttr(context)->ownerElement())) { - if (nodeMatches(evaluationContext, &p, FollowingAxis, nodeTest())) - nodes.append(&p); + NodeTraversal::StartsAfter(*ToAttr(context)->ownerElement())) { + if (NodeMatches(evaluation_context, &p, kFollowingAxis, + GetNodeTest())) + nodes.Append(&p); } } else { - for (Node* p = context; !isRootDomNode(p); p = p->parentNode()) { + for (Node* p = context; !IsRootDomNode(p); p = p->parentNode()) { for (Node* n = p->nextSibling(); n; n = n->nextSibling()) { - if (nodeMatches(evaluationContext, n, FollowingAxis, nodeTest())) - nodes.append(n); - for (Node& c : NodeTraversal::descendantsOf(*n)) { - if (nodeMatches(evaluationContext, &c, FollowingAxis, nodeTest())) - nodes.append(&c); + if (NodeMatches(evaluation_context, n, kFollowingAxis, + GetNodeTest())) + nodes.Append(n); + for (Node& c : NodeTraversal::DescendantsOf(*n)) { + if (NodeMatches(evaluation_context, &c, kFollowingAxis, + GetNodeTest())) + nodes.Append(&c); } } } } return; - case PrecedingAxis: { - if (context->isAttributeNode()) - context = toAttr(context)->ownerElement(); + case kPrecedingAxis: { + if (context->IsAttributeNode()) + context = ToAttr(context)->ownerElement(); Node* n = context; while (ContainerNode* parent = n->parentNode()) { - for (n = NodeTraversal::previous(*n); n != parent; - n = NodeTraversal::previous(*n)) { - if (nodeMatches(evaluationContext, n, PrecedingAxis, nodeTest())) - nodes.append(n); + for (n = NodeTraversal::Previous(*n); n != parent; + n = NodeTraversal::Previous(*n)) { + if (NodeMatches(evaluation_context, n, kPrecedingAxis, GetNodeTest())) + nodes.Append(n); } n = parent; } - nodes.markSorted(false); + nodes.MarkSorted(false); return; } - case AttributeAxis: { - if (!context->isElementNode()) + case kAttributeAxis: { + if (!context->IsElementNode()) return; - Element* contextElement = toElement(context); + Element* context_element = ToElement(context); // Avoid lazily creating attribute nodes for attributes that we do not // need anyway. - if (nodeTest().getKind() == NodeTest::NameTest && - nodeTest().data() != starAtom) { - Attr* attr = contextElement->getAttributeNodeNS( - nodeTest().namespaceURI(), nodeTest().data()); + if (GetNodeTest().GetKind() == NodeTest::kNameTest && + GetNodeTest().Data() != g_star_atom) { + Attr* attr = context_element->getAttributeNodeNS( + GetNodeTest().NamespaceURI(), GetNodeTest().Data()); // In XPath land, namespace nodes are not accessible on the attribute // axis. if (attr && attr->namespaceURI() != XMLNSNames::xmlnsNamespaceURI) { // Still need to check merged predicates. - if (nodeMatches(evaluationContext, attr, AttributeAxis, nodeTest())) - nodes.append(attr); + if (NodeMatches(evaluation_context, attr, kAttributeAxis, + GetNodeTest())) + nodes.Append(attr); } return; } - AttributeCollection attributes = contextElement->attributes(); + AttributeCollection attributes = context_element->Attributes(); for (auto& attribute : attributes) { - Attr* attr = contextElement->ensureAttr(attribute.name()); - if (nodeMatches(evaluationContext, attr, AttributeAxis, nodeTest())) - nodes.append(attr); + Attr* attr = context_element->EnsureAttr(attribute.GetName()); + if (NodeMatches(evaluation_context, attr, kAttributeAxis, + GetNodeTest())) + nodes.Append(attr); } return; } - case NamespaceAxis: + case kNamespaceAxis: // XPath namespace nodes are not implemented. return; - case SelfAxis: - if (nodeMatches(evaluationContext, context, SelfAxis, nodeTest())) - nodes.append(context); + case kSelfAxis: + if (NodeMatches(evaluation_context, context, kSelfAxis, GetNodeTest())) + nodes.Append(context); return; - case DescendantOrSelfAxis: - if (nodeMatches(evaluationContext, context, DescendantOrSelfAxis, - nodeTest())) - nodes.append(context); + case kDescendantOrSelfAxis: + if (NodeMatches(evaluation_context, context, kDescendantOrSelfAxis, + GetNodeTest())) + nodes.Append(context); // In XPath model, attribute nodes do not have children. - if (context->isAttributeNode()) + if (context->IsAttributeNode()) return; - for (Node& n : NodeTraversal::descendantsOf(*context)) { - if (nodeMatches(evaluationContext, &n, DescendantOrSelfAxis, - nodeTest())) - nodes.append(&n); + for (Node& n : NodeTraversal::DescendantsOf(*context)) { + if (NodeMatches(evaluation_context, &n, kDescendantOrSelfAxis, + GetNodeTest())) + nodes.Append(&n); } return; - case AncestorOrSelfAxis: { - if (nodeMatches(evaluationContext, context, AncestorOrSelfAxis, - nodeTest())) - nodes.append(context); + case kAncestorOrSelfAxis: { + if (NodeMatches(evaluation_context, context, kAncestorOrSelfAxis, + GetNodeTest())) + nodes.Append(context); Node* n = context; - if (context->isAttributeNode()) { - n = toAttr(context)->ownerElement(); - if (nodeMatches(evaluationContext, n, AncestorOrSelfAxis, nodeTest())) - nodes.append(n); + if (context->IsAttributeNode()) { + n = ToAttr(context)->ownerElement(); + if (NodeMatches(evaluation_context, n, kAncestorOrSelfAxis, + GetNodeTest())) + nodes.Append(n); } for (n = n->parentNode(); n; n = n->parentNode()) { - if (nodeMatches(evaluationContext, n, AncestorOrSelfAxis, nodeTest())) - nodes.append(n); + if (NodeMatches(evaluation_context, n, kAncestorOrSelfAxis, + GetNodeTest())) + nodes.Append(n); } - nodes.markSorted(false); + nodes.MarkSorted(false); return; } } diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathStep.h b/chromium/third_party/WebKit/Source/core/xml/XPathStep.h index 1af0794d4e2..88fd5f21e01 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XPathStep.h +++ b/chromium/third_party/WebKit/Source/core/xml/XPathStep.h @@ -43,69 +43,69 @@ class Step final : public ParseNode { public: enum Axis { - AncestorAxis, - AncestorOrSelfAxis, - AttributeAxis, - ChildAxis, - DescendantAxis, - DescendantOrSelfAxis, - FollowingAxis, - FollowingSiblingAxis, - NamespaceAxis, - ParentAxis, - PrecedingAxis, - PrecedingSiblingAxis, - SelfAxis + kAncestorAxis, + kAncestorOrSelfAxis, + kAttributeAxis, + kChildAxis, + kDescendantAxis, + kDescendantOrSelfAxis, + kFollowingAxis, + kFollowingSiblingAxis, + kNamespaceAxis, + kParentAxis, + kPrecedingAxis, + kPrecedingSiblingAxis, + kSelfAxis }; class NodeTest : public GarbageCollectedFinalized<NodeTest> { public: enum Kind { - TextNodeTest, - CommentNodeTest, - ProcessingInstructionNodeTest, - AnyNodeTest, - NameTest + kTextNodeTest, + kCommentNodeTest, + kProcessingInstructionNodeTest, + kAnyNodeTest, + kNameTest }; - NodeTest(Kind kind) : m_kind(kind) {} - NodeTest(Kind kind, const String& data) : m_kind(kind), m_data(data) {} + NodeTest(Kind kind) : kind_(kind) {} + NodeTest(Kind kind, const String& data) : kind_(kind), data_(data) {} NodeTest(Kind kind, const AtomicString& data, - const AtomicString& namespaceURI) - : m_kind(kind), m_data(data), m_namespaceURI(namespaceURI) {} + const AtomicString& namespace_uri) + : kind_(kind), data_(data), namespace_uri_(namespace_uri) {} NodeTest(const NodeTest& o) - : m_kind(o.m_kind), m_data(o.m_data), m_namespaceURI(o.m_namespaceURI) { - DCHECK(o.m_mergedPredicates.isEmpty()); + : kind_(o.kind_), data_(o.data_), namespace_uri_(o.namespace_uri_) { + DCHECK(o.merged_predicates_.IsEmpty()); } NodeTest& operator=(const NodeTest& o) { - m_kind = o.m_kind; - m_data = o.m_data; - m_namespaceURI = o.m_namespaceURI; - DCHECK(o.m_mergedPredicates.isEmpty()); + kind_ = o.kind_; + data_ = o.data_; + namespace_uri_ = o.namespace_uri_; + DCHECK(o.merged_predicates_.IsEmpty()); return *this; } - DEFINE_INLINE_TRACE() { visitor->trace(m_mergedPredicates); } + DEFINE_INLINE_TRACE() { visitor->Trace(merged_predicates_); } - Kind getKind() const { return m_kind; } - const AtomicString& data() const { return m_data; } - const AtomicString& namespaceURI() const { return m_namespaceURI; } - HeapVector<Member<Predicate>>& mergedPredicates() { - return m_mergedPredicates; + Kind GetKind() const { return kind_; } + const AtomicString& Data() const { return data_; } + const AtomicString& NamespaceURI() const { return namespace_uri_; } + HeapVector<Member<Predicate>>& MergedPredicates() { + return merged_predicates_; } - const HeapVector<Member<Predicate>>& mergedPredicates() const { - return m_mergedPredicates; + const HeapVector<Member<Predicate>>& MergedPredicates() const { + return merged_predicates_; } private: - Kind m_kind; - AtomicString m_data; - AtomicString m_namespaceURI; + Kind kind_; + AtomicString data_; + AtomicString namespace_uri_; // When possible, we merge some or all predicates with node test for better // performance. - HeapVector<Member<Predicate>> m_mergedPredicates; + HeapVector<Member<Predicate>> merged_predicates_; }; Step(Axis, const NodeTest&); @@ -113,28 +113,28 @@ class Step final : public ParseNode { ~Step() override; DECLARE_VIRTUAL_TRACE(); - void optimize(); + void Optimize(); - void evaluate(EvaluationContext&, Node* context, NodeSet&) const; + void Evaluate(EvaluationContext&, Node* context, NodeSet&) const; - Axis getAxis() const { return m_axis; } - const NodeTest& nodeTest() const { return *m_nodeTest; } + Axis GetAxis() const { return axis_; } + const NodeTest& GetNodeTest() const { return *node_test_; } private: - friend bool optimizeStepPair(Step*, Step*); - bool predicatesAreContextListInsensitive() const; - NodeTest& nodeTest() { return *m_nodeTest; } + friend bool OptimizeStepPair(Step*, Step*); + bool PredicatesAreContextListInsensitive() const; + NodeTest& GetNodeTest() { return *node_test_; } - void parseNodeTest(const String&); - void nodesInAxis(EvaluationContext&, Node* context, NodeSet&) const; - String namespaceFromNodetest(const String& nodeTest) const; + void ParseNodeTest(const String&); + void NodesInAxis(EvaluationContext&, Node* context, NodeSet&) const; + String NamespaceFromNodetest(const String& node_test) const; - Axis m_axis; - Member<NodeTest> m_nodeTest; - HeapVector<Member<Predicate>> m_predicates; + Axis axis_; + Member<NodeTest> node_test_; + HeapVector<Member<Predicate>> predicates_; }; -bool optimizeStepPair(Step*, Step*); +bool OptimizeStepPair(Step*, Step*); } // namespace XPath diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathUtil.cpp b/chromium/third_party/WebKit/Source/core/xml/XPathUtil.cpp index a2a24d759e2..c6ac519eb79 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XPathUtil.cpp +++ b/chromium/third_party/WebKit/Source/core/xml/XPathUtil.cpp @@ -28,16 +28,16 @@ #include "core/dom/ContainerNode.h" #include "core/dom/NodeTraversal.h" -#include "wtf/text/StringBuilder.h" +#include "platform/wtf/text/StringBuilder.h" namespace blink { namespace XPath { -bool isRootDomNode(Node* node) { +bool IsRootDomNode(Node* node) { return node && !node->parentNode(); } -String stringValue(Node* node) { +String StringValue(Node* node) { switch (node->getNodeType()) { case Node::kAttributeNode: case Node::kProcessingInstructionNode: @@ -46,25 +46,25 @@ String stringValue(Node* node) { case Node::kCdataSectionNode: return node->nodeValue(); default: - if (isRootDomNode(node) || node->isElementNode()) { + if (IsRootDomNode(node) || node->IsElementNode()) { StringBuilder result; - result.reserveCapacity(1024); + result.ReserveCapacity(1024); - for (Node& n : NodeTraversal::descendantsOf(*node)) { - if (n.isTextNode()) { - const String& nodeValue = n.nodeValue(); - result.append(nodeValue); + for (Node& n : NodeTraversal::DescendantsOf(*node)) { + if (n.IsTextNode()) { + const String& node_value = n.nodeValue(); + result.Append(node_value); } } - return result.toString(); + return result.ToString(); } } return String(); } -bool isValidContextNode(Node* node) { +bool IsValidContextNode(Node* node) { if (!node) return false; switch (node->getNodeType()) { diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathUtil.h b/chromium/third_party/WebKit/Source/core/xml/XPathUtil.h index db1aba7d3dd..2755260281d 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XPathUtil.h +++ b/chromium/third_party/WebKit/Source/core/xml/XPathUtil.h @@ -27,7 +27,7 @@ #ifndef XPathUtil_h #define XPathUtil_h -#include "wtf/Forward.h" +#include "platform/wtf/Forward.h" namespace blink { @@ -36,14 +36,14 @@ class Node; namespace XPath { // @return whether the given node is the root node -bool isRootDomNode(Node*); +bool IsRootDomNode(Node*); // @return the 'string-value' of the given node as specified by // http://www.w3.org/TR/xpath -String stringValue(Node*); +String StringValue(Node*); // @return whether the given node is a valid context node -bool isValidContextNode(Node*); +bool IsValidContextNode(Node*); } // namespace XPath diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathValue.cpp b/chromium/third_party/WebKit/Source/core/xml/XPathValue.cpp index 647394b92ae..1c1c8897ea9 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XPathValue.cpp +++ b/chromium/third_party/WebKit/Source/core/xml/XPathValue.cpp @@ -26,112 +26,112 @@ #include "core/xml/XPathValue.h" +#include <limits> #include "core/xml/XPathExpressionNode.h" #include "core/xml/XPathUtil.h" -#include "wtf/MathExtras.h" -#include "wtf/StdLibExtras.h" -#include <limits> +#include "platform/wtf/MathExtras.h" +#include "platform/wtf/StdLibExtras.h" namespace blink { namespace XPath { -const Value::AdoptTag Value::adopt = {}; +const Value::AdoptTag Value::kAdopt = {}; DEFINE_TRACE(ValueData) { - visitor->trace(m_nodeSet); + visitor->Trace(node_set_); } DEFINE_TRACE(Value) { - visitor->trace(m_data); + visitor->Trace(data_); } -const NodeSet& Value::toNodeSet(EvaluationContext* context) const { - if (!isNodeSet() && context) - context->hadTypeConversionError = true; +const NodeSet& Value::ToNodeSet(EvaluationContext* context) const { + if (!IsNodeSet() && context) + context->had_type_conversion_error = true; - if (!m_data) { - DEFINE_STATIC_LOCAL(NodeSet, emptyNodeSet, (NodeSet::create())); - return emptyNodeSet; + if (!data_) { + DEFINE_STATIC_LOCAL(NodeSet, empty_node_set, (NodeSet::Create())); + return empty_node_set; } - return m_data->nodeSet(); + return data_->GetNodeSet(); } -NodeSet& Value::modifiableNodeSet(EvaluationContext& context) { - if (!isNodeSet()) - context.hadTypeConversionError = true; +NodeSet& Value::ModifiableNodeSet(EvaluationContext& context) { + if (!IsNodeSet()) + context.had_type_conversion_error = true; - if (!m_data) - m_data = ValueData::create(); + if (!data_) + data_ = ValueData::Create(); - m_type = NodeSetValue; - return m_data->nodeSet(); + type_ = kNodeSetValue; + return data_->GetNodeSet(); } -bool Value::toBoolean() const { - switch (m_type) { - case NodeSetValue: - return !m_data->nodeSet().isEmpty(); - case BooleanValue: - return m_bool; - case NumberValue: - return m_number && !std::isnan(m_number); - case StringValue: - return !m_data->m_string.isEmpty(); +bool Value::ToBoolean() const { + switch (type_) { + case kNodeSetValue: + return !data_->GetNodeSet().IsEmpty(); + case kBooleanValue: + return bool_; + case kNumberValue: + return number_ && !std::isnan(number_); + case kStringValue: + return !data_->string_.IsEmpty(); } NOTREACHED(); return false; } -double Value::toNumber() const { - switch (m_type) { - case NodeSetValue: - return Value(toString()).toNumber(); - case NumberValue: - return m_number; - case StringValue: { - const String& str = m_data->m_string.simplifyWhiteSpace(); +double Value::ToNumber() const { + switch (type_) { + case kNodeSetValue: + return Value(ToString()).ToNumber(); + case kNumberValue: + return number_; + case kStringValue: { + const String& str = data_->string_.SimplifyWhiteSpace(); // String::toDouble() supports exponential notation, which is not // allowed in XPath. unsigned len = str.length(); for (unsigned i = 0; i < len; ++i) { UChar c = str[i]; - if (!isASCIIDigit(c) && c != '.' && c != '-') + if (!IsASCIIDigit(c) && c != '.' && c != '-') return std::numeric_limits<double>::quiet_NaN(); } - bool canConvert; - double value = str.toDouble(&canConvert); - if (canConvert) + bool can_convert; + double value = str.ToDouble(&can_convert); + if (can_convert) return value; return std::numeric_limits<double>::quiet_NaN(); } - case BooleanValue: - return m_bool; + case kBooleanValue: + return bool_; } NOTREACHED(); return 0.0; } -String Value::toString() const { - switch (m_type) { - case NodeSetValue: - if (m_data->nodeSet().isEmpty()) +String Value::ToString() const { + switch (type_) { + case kNodeSetValue: + if (data_->GetNodeSet().IsEmpty()) return ""; - return stringValue(m_data->nodeSet().firstNode()); - case StringValue: - return m_data->m_string; - case NumberValue: - if (std::isnan(m_number)) + return StringValue(data_->GetNodeSet().FirstNode()); + case kStringValue: + return data_->string_; + case kNumberValue: + if (std::isnan(number_)) return "NaN"; - if (m_number == 0) + if (number_ == 0) return "0"; - if (std::isinf(m_number)) - return std::signbit(m_number) ? "-Infinity" : "Infinity"; - return String::number(m_number); - case BooleanValue: - return m_bool ? "true" : "false"; + if (std::isinf(number_)) + return std::signbit(number_) ? "-Infinity" : "Infinity"; + return String::Number(number_); + case kBooleanValue: + return bool_ ? "true" : "false"; } NOTREACHED(); return String(); diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathValue.h b/chromium/third_party/WebKit/Source/core/xml/XPathValue.h index 44653a99a02..4e0454eadc1 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XPathValue.h +++ b/chromium/third_party/WebKit/Source/core/xml/XPathValue.h @@ -29,7 +29,7 @@ #include "core/CoreExport.h" #include "core/xml/XPathNodeSet.h" -#include "wtf/text/WTFString.h" +#include "platform/wtf/text/WTFString.h" namespace blink { @@ -39,28 +39,30 @@ struct EvaluationContext; class ValueData : public GarbageCollectedFinalized<ValueData> { public: - static ValueData* create() { return new ValueData; } - static ValueData* create(const NodeSet& nodeSet) { - return new ValueData(nodeSet); + static ValueData* Create() { return new ValueData; } + static ValueData* Create(const NodeSet& node_set) { + return new ValueData(node_set); } - static ValueData* create(NodeSet* nodeSet) { return new ValueData(nodeSet); } - static ValueData* create(const String& string) { + static ValueData* Create(NodeSet* node_set) { + return new ValueData(node_set); + } + static ValueData* Create(const String& string) { return new ValueData(string); } DECLARE_TRACE(); - NodeSet& nodeSet() { return *m_nodeSet; } + NodeSet& GetNodeSet() { return *node_set_; } - String m_string; + String string_; private: - ValueData() : m_nodeSet(NodeSet::create()) {} - explicit ValueData(const NodeSet& nodeSet) - : m_nodeSet(NodeSet::create(nodeSet)) {} - explicit ValueData(NodeSet* nodeSet) : m_nodeSet(nodeSet) {} + ValueData() : node_set_(NodeSet::Create()) {} + explicit ValueData(const NodeSet& node_set) + : node_set_(NodeSet::Create(node_set)) {} + explicit ValueData(NodeSet* node_set) : node_set_(node_set) {} explicit ValueData(const String& string) - : m_string(string), m_nodeSet(NodeSet::create()) {} + : string_(string), node_set_(NodeSet::Create()) {} - Member<NodeSet> m_nodeSet; + Member<NodeSet> node_set_; }; // Copying Value objects makes their data partially shared, so care has to be @@ -69,34 +71,34 @@ class CORE_EXPORT Value { DISALLOW_NEW(); public: - enum Type { NodeSetValue, BooleanValue, NumberValue, StringValue }; + enum Type { kNodeSetValue, kBooleanValue, kNumberValue, kStringValue }; - Value(unsigned value) : m_type(NumberValue), m_bool(false), m_number(value) {} + Value(unsigned value) : type_(kNumberValue), bool_(false), number_(value) {} Value(unsigned long value) - : m_type(NumberValue), m_bool(false), m_number(value) {} - Value(double value) : m_type(NumberValue), m_bool(false), m_number(value) {} + : type_(kNumberValue), bool_(false), number_(value) {} + Value(double value) : type_(kNumberValue), bool_(false), number_(value) {} Value(const char* value) - : m_type(StringValue), - m_bool(false), - m_number(0), - m_data(ValueData::create(value)) {} + : type_(kStringValue), + bool_(false), + number_(0), + data_(ValueData::Create(value)) {} Value(const String& value) - : m_type(StringValue), - m_bool(false), - m_number(0), - m_data(ValueData::create(value)) {} + : type_(kStringValue), + bool_(false), + number_(0), + data_(ValueData::Create(value)) {} Value(const NodeSet& value) - : m_type(NodeSetValue), - m_bool(false), - m_number(0), - m_data(ValueData::create(value)) {} + : type_(kNodeSetValue), + bool_(false), + number_(0), + data_(ValueData::Create(value)) {} Value(Node* value) - : m_type(NodeSetValue), - m_bool(false), - m_number(0), - m_data(ValueData::create()) { - m_data->nodeSet().append(value); + : type_(kNodeSetValue), + bool_(false), + number_(0), + data_(ValueData::Create()) { + data_->GetNodeSet().Append(value); } DECLARE_TRACE(); @@ -106,38 +108,38 @@ class CORE_EXPORT Value { Value(T); static const struct AdoptTag { - } adopt; + } kAdopt; Value(NodeSet* value, const AdoptTag&) - : m_type(NodeSetValue), - m_bool(false), - m_number(0), - m_data(ValueData::create(value)) {} + : type_(kNodeSetValue), + bool_(false), + number_(0), + data_(ValueData::Create(value)) {} - Type getType() const { return m_type; } + Type GetType() const { return type_; } - bool isNodeSet() const { return m_type == NodeSetValue; } - bool isBoolean() const { return m_type == BooleanValue; } - bool isNumber() const { return m_type == NumberValue; } - bool isString() const { return m_type == StringValue; } + bool IsNodeSet() const { return type_ == kNodeSetValue; } + bool IsBoolean() const { return type_ == kBooleanValue; } + bool IsNumber() const { return type_ == kNumberValue; } + bool IsString() const { return type_ == kStringValue; } // If this is called during XPathExpression::evaluate(), EvaluationContext // should be passed. - const NodeSet& toNodeSet(EvaluationContext*) const; - NodeSet& modifiableNodeSet(EvaluationContext&); - bool toBoolean() const; - double toNumber() const; - String toString() const; + const NodeSet& ToNodeSet(EvaluationContext*) const; + NodeSet& ModifiableNodeSet(EvaluationContext&); + bool ToBoolean() const; + double ToNumber() const; + String ToString() const; private: - Type m_type; - bool m_bool; - double m_number; - Member<ValueData> m_data; + Type type_; + bool bool_; + double number_; + Member<ValueData> data_; }; template <> inline Value::Value(bool value) - : m_type(BooleanValue), m_bool(value), m_number(0) {} + : type_(kBooleanValue), bool_(value), number_(0) {} } // namespace XPath diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathVariableReference.cpp b/chromium/third_party/WebKit/Source/core/xml/XPathVariableReference.cpp index 41682d7b50c..da11f54a010 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XPathVariableReference.cpp +++ b/chromium/third_party/WebKit/Source/core/xml/XPathVariableReference.cpp @@ -31,16 +31,16 @@ namespace blink { namespace XPath { -VariableReference::VariableReference(const String& name) : m_name(name) {} +VariableReference::VariableReference(const String& name) : name_(name) {} -Value VariableReference::evaluate(EvaluationContext& context) const { - HashMap<String, String>& bindings = context.variableBindings; - if (!bindings.contains(m_name)) { +Value VariableReference::Evaluate(EvaluationContext& context) const { + HashMap<String, String>& bindings = context.variable_bindings; + if (!bindings.Contains(name_)) { // FIXME: Is this the right thing to do if an unknown variable is // referenced? return ""; } - return bindings.at(m_name); + return bindings.at(name_); } } // namespace XPath diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathVariableReference.h b/chromium/third_party/WebKit/Source/core/xml/XPathVariableReference.h index 2c83f7f842c..c9c34f6aa9c 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XPathVariableReference.h +++ b/chromium/third_party/WebKit/Source/core/xml/XPathVariableReference.h @@ -38,13 +38,13 @@ class VariableReference final : public Expression { explicit VariableReference(const String& name); private: - Value evaluate(EvaluationContext&) const override; - Value::Type resultType() const override { + Value Evaluate(EvaluationContext&) const override; + Value::Type ResultType() const override { NOTREACHED(); - return Value::NumberValue; + return Value::kNumberValue; } - String m_name; + String name_; }; } // namespace XPath diff --git a/chromium/third_party/WebKit/Source/core/xml/XSLImportRule.cpp b/chromium/third_party/WebKit/Source/core/xml/XSLImportRule.cpp index ca3385b113f..e50da78a1d7 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XSLImportRule.cpp +++ b/chromium/third_party/WebKit/Source/core/xml/XSLImportRule.cpp @@ -25,84 +25,85 @@ #include "core/loader/resource/XSLStyleSheetResource.h" #include "platform/SharedBuffer.h" #include "platform/loader/fetch/FetchInitiatorTypeNames.h" -#include "platform/loader/fetch/FetchRequest.h" +#include "platform/loader/fetch/FetchParameters.h" #include "platform/loader/fetch/RawResource.h" #include "platform/loader/fetch/ResourceFetcher.h" -#include "wtf/text/TextEncoding.h" +#include "platform/wtf/text/TextEncoding.h" namespace blink { XSLImportRule::XSLImportRule(XSLStyleSheet* parent, const String& href) - : m_parentStyleSheet(parent), m_strHref(href), m_loading(false) {} + : parent_style_sheet_(parent), str_href_(href), loading_(false) {} XSLImportRule::~XSLImportRule() {} -void XSLImportRule::setXSLStyleSheet(const String& href, - const KURL& baseURL, +void XSLImportRule::SetXSLStyleSheet(const String& href, + const KURL& base_url, const String& sheet) { - if (m_styleSheet) - m_styleSheet->setParentStyleSheet(0); + if (style_sheet_) + style_sheet_->SetParentStyleSheet(0); - m_styleSheet = XSLStyleSheet::create(this, href, baseURL); + style_sheet_ = XSLStyleSheet::Create(this, href, base_url); - XSLStyleSheet* parent = parentStyleSheet(); + XSLStyleSheet* parent = ParentStyleSheet(); if (parent) - m_styleSheet->setParentStyleSheet(parent); + style_sheet_->SetParentStyleSheet(parent); - m_styleSheet->parseString(sheet); - m_loading = false; + style_sheet_->ParseString(sheet); + loading_ = false; if (parent) - parent->checkLoaded(); + parent->CheckLoaded(); } -bool XSLImportRule::isLoading() { - return m_loading || (m_styleSheet && m_styleSheet->isLoading()); +bool XSLImportRule::IsLoading() { + return loading_ || (style_sheet_ && style_sheet_->IsLoading()); } -void XSLImportRule::loadSheet() { - Document* ownerDocument = nullptr; - XSLStyleSheet* rootSheet = parentStyleSheet(); +void XSLImportRule::LoadSheet() { + Document* owner_document = nullptr; + XSLStyleSheet* root_sheet = ParentStyleSheet(); - if (rootSheet) { - while (XSLStyleSheet* parentSheet = rootSheet->parentStyleSheet()) - rootSheet = parentSheet; + if (root_sheet) { + while (XSLStyleSheet* parent_sheet = root_sheet->parentStyleSheet()) + root_sheet = parent_sheet; } - if (rootSheet) - ownerDocument = rootSheet->ownerDocument(); + if (root_sheet) + owner_document = root_sheet->OwnerDocument(); - String absHref = m_strHref; - XSLStyleSheet* parentSheet = parentStyleSheet(); - if (!parentSheet->baseURL().isNull()) { + String abs_href = str_href_; + XSLStyleSheet* parent_sheet = ParentStyleSheet(); + if (!parent_sheet->BaseURL().IsNull()) { // Use parent styleheet's URL as the base URL - absHref = KURL(parentSheet->baseURL(), m_strHref).getString(); + abs_href = KURL(parent_sheet->BaseURL(), str_href_).GetString(); } // Check for a cycle in our import chain. If we encounter a stylesheet in // our parent chain with the same URL, then just bail. - for (XSLStyleSheet* parentSheet = parentStyleSheet(); parentSheet; - parentSheet = parentSheet->parentStyleSheet()) { - if (absHref == parentSheet->baseURL().getString()) + for (XSLStyleSheet* parent_sheet = ParentStyleSheet(); parent_sheet; + parent_sheet = parent_sheet->parentStyleSheet()) { + if (abs_href == parent_sheet->BaseURL().GetString()) return; } - ResourceLoaderOptions fetchOptions(ResourceFetcher::defaultResourceOptions()); - FetchRequest request(ResourceRequest(ownerDocument->completeURL(absHref)), - FetchInitiatorTypeNames::xml, fetchOptions); - request.setOriginRestriction(FetchRequest::RestrictToSameOrigin); - XSLStyleSheetResource* resource = XSLStyleSheetResource::fetchSynchronously( - request, ownerDocument->fetcher()); - if (!resource || !resource->sheet()) + ResourceLoaderOptions fetch_options( + ResourceFetcher::DefaultResourceOptions()); + FetchParameters params(ResourceRequest(owner_document->CompleteURL(abs_href)), + FetchInitiatorTypeNames::xml, fetch_options); + params.SetOriginRestriction(FetchParameters::kRestrictToSameOrigin); + XSLStyleSheetResource* resource = XSLStyleSheetResource::FetchSynchronously( + params, owner_document->Fetcher()); + if (!resource || !resource->Sheet()) return; - DCHECK(!m_styleSheet); - setXSLStyleSheet(absHref, resource->response().url(), resource->sheet()); + DCHECK(!style_sheet_); + SetXSLStyleSheet(abs_href, resource->GetResponse().Url(), resource->Sheet()); } DEFINE_TRACE(XSLImportRule) { - visitor->trace(m_parentStyleSheet); - visitor->trace(m_styleSheet); + visitor->Trace(parent_style_sheet_); + visitor->Trace(style_sheet_); } } // namespace blink diff --git a/chromium/third_party/WebKit/Source/core/xml/XSLImportRule.h b/chromium/third_party/WebKit/Source/core/xml/XSLImportRule.h index 8631c8c2e5d..7dd8e60aa7b 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XSLImportRule.h +++ b/chromium/third_party/WebKit/Source/core/xml/XSLImportRule.h @@ -30,36 +30,37 @@ namespace blink { class XSLImportRule final : public GarbageCollectedFinalized<XSLImportRule> { public: - static XSLImportRule* create(XSLStyleSheet* parentSheet, const String& href) { + static XSLImportRule* Create(XSLStyleSheet* parent_sheet, + const String& href) { DCHECK(RuntimeEnabledFeatures::xsltEnabled()); - return new XSLImportRule(parentSheet, href); + return new XSLImportRule(parent_sheet, href); } virtual ~XSLImportRule(); DECLARE_VIRTUAL_TRACE(); - const String& href() const { return m_strHref; } - XSLStyleSheet* styleSheet() const { return m_styleSheet.get(); } + const String& Href() const { return str_href_; } + XSLStyleSheet* GetStyleSheet() const { return style_sheet_.Get(); } - XSLStyleSheet* parentStyleSheet() const { return m_parentStyleSheet; } - void setParentStyleSheet(XSLStyleSheet* styleSheet) { - m_parentStyleSheet = styleSheet; + XSLStyleSheet* ParentStyleSheet() const { return parent_style_sheet_; } + void SetParentStyleSheet(XSLStyleSheet* style_sheet) { + parent_style_sheet_ = style_sheet; } - bool isLoading(); - void loadSheet(); + bool IsLoading(); + void LoadSheet(); private: - XSLImportRule(XSLStyleSheet* parentSheet, const String& href); + XSLImportRule(XSLStyleSheet* parent_sheet, const String& href); - void setXSLStyleSheet(const String& href, - const KURL& baseURL, + void SetXSLStyleSheet(const String& href, + const KURL& base_url, const String& sheet); - Member<XSLStyleSheet> m_parentStyleSheet; - String m_strHref; - Member<XSLStyleSheet> m_styleSheet; - bool m_loading; + Member<XSLStyleSheet> parent_style_sheet_; + String str_href_; + Member<XSLStyleSheet> style_sheet_; + bool loading_; }; } // namespace blink diff --git a/chromium/third_party/WebKit/Source/core/xml/XSLStyleSheet.h b/chromium/third_party/WebKit/Source/core/xml/XSLStyleSheet.h index f057d2da616..34fd4c63f48 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XSLStyleSheet.h +++ b/chromium/third_party/WebKit/Source/core/xml/XSLStyleSheet.h @@ -23,12 +23,12 @@ #ifndef XSLStyleSheet_h #define XSLStyleSheet_h +#include <libxml/tree.h> +#include <libxslt/transform.h> #include "core/css/StyleSheet.h" #include "core/dom/ProcessingInstruction.h" #include "platform/RuntimeEnabledFeatures.h" -#include "wtf/PassRefPtr.h" -#include <libxml/tree.h> -#include <libxslt/transform.h> +#include "platform/wtf/PassRefPtr.h" namespace blink { @@ -36,113 +36,114 @@ class XSLImportRule; class XSLStyleSheet final : public StyleSheet { public: - static XSLStyleSheet* create(XSLImportRule* parentImport, - const String& originalURL, - const KURL& finalURL) { + static XSLStyleSheet* Create(XSLImportRule* parent_import, + const String& original_url, + const KURL& final_url) { DCHECK(RuntimeEnabledFeatures::xsltEnabled()); - return new XSLStyleSheet(parentImport, originalURL, finalURL); + return new XSLStyleSheet(parent_import, original_url, final_url); } - static XSLStyleSheet* create(ProcessingInstruction* parentNode, - const String& originalURL, - const KURL& finalURL) { + static XSLStyleSheet* Create(ProcessingInstruction* parent_node, + const String& original_url, + const KURL& final_url) { DCHECK(RuntimeEnabledFeatures::xsltEnabled()); - return new XSLStyleSheet(parentNode, originalURL, finalURL, false); + return new XSLStyleSheet(parent_node, original_url, final_url, false); } - static XSLStyleSheet* createEmbedded(ProcessingInstruction* parentNode, - const KURL& finalURL) { + static XSLStyleSheet* CreateEmbedded(ProcessingInstruction* parent_node, + const KURL& final_url) { DCHECK(RuntimeEnabledFeatures::xsltEnabled()); - return new XSLStyleSheet(parentNode, finalURL.getString(), finalURL, true); + return new XSLStyleSheet(parent_node, final_url.GetString(), final_url, + true); } // Taking an arbitrary node is unsafe, because owner node pointer can become // stale. XSLTProcessor ensures that the stylesheet doesn't outlive its // parent, in part by not exposing it to JavaScript. - static XSLStyleSheet* createForXSLTProcessor(Document* document, - Node* stylesheetRootNode, - const String& originalURL, - const KURL& finalURL) { + static XSLStyleSheet* CreateForXSLTProcessor(Document* document, + Node* stylesheet_root_node, + const String& original_url, + const KURL& final_url) { DCHECK(RuntimeEnabledFeatures::xsltEnabled()); - return new XSLStyleSheet(document, stylesheetRootNode, originalURL, - finalURL, false); + return new XSLStyleSheet(document, stylesheet_root_node, original_url, + final_url, false); } ~XSLStyleSheet() override; - bool parseString(const String&); + bool ParseString(const String&); - void checkLoaded(); + void CheckLoaded(); - const KURL& finalURL() const { return m_finalURL; } + const KURL& FinalURL() const { return final_url_; } - void loadChildSheets(); - void loadChildSheet(const String& href); + void LoadChildSheets(); + void LoadChildSheet(const String& href); - Document* ownerDocument(); + Document* OwnerDocument(); XSLStyleSheet* parentStyleSheet() const override { - return m_parentStyleSheet; + return parent_style_sheet_; } - void setParentStyleSheet(XSLStyleSheet*); + void SetParentStyleSheet(XSLStyleSheet*); - xmlDocPtr document(); - xsltStylesheetPtr compileStyleSheet(); - xmlDocPtr locateStylesheetSubResource(xmlDocPtr parentDoc, + xmlDocPtr GetDocument(); + xsltStylesheetPtr CompileStyleSheet(); + xmlDocPtr LocateStylesheetSubResource(xmlDocPtr parent_doc, const xmlChar* uri); - void clearDocuments(); + void ClearDocuments(); - void markAsProcessed(); - bool processed() const { return m_processed; } + void MarkAsProcessed(); + bool Processed() const { return processed_; } String type() const override { return "text/xml"; } - bool disabled() const override { return m_isDisabled; } - void setDisabled(bool b) override { m_isDisabled = b; } - Node* ownerNode() const override { return m_ownerNode; } - String href() const override { return m_originalURL; } - String title() const override { return emptyString; } + bool disabled() const override { return is_disabled_; } + void setDisabled(bool b) override { is_disabled_ = b; } + Node* ownerNode() const override { return owner_node_; } + String href() const override { return original_url_; } + String title() const override { return g_empty_string; } - void clearOwnerNode() override { m_ownerNode = nullptr; } - KURL baseURL() const override { return m_finalURL; } - bool isLoading() const override; + void ClearOwnerNode() override { owner_node_ = nullptr; } + KURL BaseURL() const override { return final_url_; } + bool IsLoading() const override; DECLARE_VIRTUAL_TRACE(); private: - XSLStyleSheet(Node* parentNode, - const String& originalURL, - const KURL& finalURL, + XSLStyleSheet(Node* parent_node, + const String& original_url, + const KURL& final_url, bool embedded); - XSLStyleSheet(Document* ownerDocument, - Node* styleSheetRootNode, - const String& originalURL, - const KURL& finalURL, + XSLStyleSheet(Document* owner_document, + Node* style_sheet_root_node, + const String& original_url, + const KURL& final_url, bool embedded); - XSLStyleSheet(XSLImportRule* parentImport, - const String& originalURL, - const KURL& finalURL); + XSLStyleSheet(XSLImportRule* parent_import, + const String& original_url, + const KURL& final_url); - Member<Node> m_ownerNode; - String m_originalURL; - KURL m_finalURL; - bool m_isDisabled; + Member<Node> owner_node_; + String original_url_; + KURL final_url_; + bool is_disabled_; - HeapVector<Member<XSLImportRule>> m_children; + HeapVector<Member<XSLImportRule>> children_; - bool m_embedded; - bool m_processed; + bool embedded_; + bool processed_; - xmlDocPtr m_stylesheetDoc; - bool m_stylesheetDocTaken; - bool m_compilationFailed; + xmlDocPtr stylesheet_doc_; + bool stylesheet_doc_taken_; + bool compilation_failed_; - Member<XSLStyleSheet> m_parentStyleSheet; - Member<Document> m_ownerDocument; + Member<XSLStyleSheet> parent_style_sheet_; + Member<Document> owner_document_; }; DEFINE_TYPE_CASTS(XSLStyleSheet, StyleSheet, sheet, - !sheet->isCSSStyleSheet(), - !sheet.isCSSStyleSheet()); + !sheet->IsCSSStyleSheet(), + !sheet.IsCSSStyleSheet()); } // namespace blink diff --git a/chromium/third_party/WebKit/Source/core/xml/XSLStyleSheetLibxslt.cpp b/chromium/third_party/WebKit/Source/core/xml/XSLStyleSheetLibxslt.cpp index e9c2d488853..7be18dad3cc 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XSLStyleSheetLibxslt.cpp +++ b/chromium/third_party/WebKit/Source/core/xml/XSLStyleSheetLibxslt.cpp @@ -21,127 +21,126 @@ #include "core/xml/XSLStyleSheet.h" +#include <libxml/uri.h> +#include <libxslt/xsltutils.h> #include "core/dom/Document.h" #include "core/dom/Node.h" #include "core/dom/TransformSource.h" -#include "core/frame/FrameHost.h" #include "core/frame/LocalFrame.h" #include "core/xml/XSLImportRule.h" #include "core/xml/XSLTProcessor.h" #include "core/xml/parser/XMLDocumentParserScope.h" #include "core/xml/parser/XMLParserInput.h" -#include "wtf/text/CString.h" -#include <libxml/uri.h> -#include <libxslt/xsltutils.h> +#include "platform/wtf/text/CString.h" namespace blink { -XSLStyleSheet::XSLStyleSheet(XSLImportRule* parentRule, - const String& originalURL, - const KURL& finalURL) - : m_ownerNode(nullptr), - m_originalURL(originalURL), - m_finalURL(finalURL), - m_isDisabled(false), - m_embedded(false), +XSLStyleSheet::XSLStyleSheet(XSLImportRule* parent_rule, + const String& original_url, + const KURL& final_url) + : owner_node_(nullptr), + original_url_(original_url), + final_url_(final_url), + is_disabled_(false), + embedded_(false), // Child sheets get marked as processed when the libxslt engine has // finally seen them. - m_processed(false), - m_stylesheetDoc(0), - m_stylesheetDocTaken(false), - m_compilationFailed(false), - m_parentStyleSheet(parentRule ? parentRule->parentStyleSheet() : 0), - m_ownerDocument(nullptr) {} - -XSLStyleSheet::XSLStyleSheet(Node* parentNode, - const String& originalURL, - const KURL& finalURL, + processed_(false), + stylesheet_doc_(0), + stylesheet_doc_taken_(false), + compilation_failed_(false), + parent_style_sheet_(parent_rule ? parent_rule->ParentStyleSheet() : 0), + owner_document_(nullptr) {} + +XSLStyleSheet::XSLStyleSheet(Node* parent_node, + const String& original_url, + const KURL& final_url, bool embedded) - : m_ownerNode(parentNode), - m_originalURL(originalURL), - m_finalURL(finalURL), - m_isDisabled(false), - m_embedded(embedded), - m_processed(true), // The root sheet starts off processed. - m_stylesheetDoc(0), - m_stylesheetDocTaken(false), - m_compilationFailed(false), - m_parentStyleSheet(nullptr), - m_ownerDocument(nullptr) {} - -XSLStyleSheet::XSLStyleSheet(Document* ownerDocument, - Node* styleSheetRootNode, - const String& originalURL, - const KURL& finalURL, + : owner_node_(parent_node), + original_url_(original_url), + final_url_(final_url), + is_disabled_(false), + embedded_(embedded), + processed_(true), // The root sheet starts off processed. + stylesheet_doc_(0), + stylesheet_doc_taken_(false), + compilation_failed_(false), + parent_style_sheet_(nullptr), + owner_document_(nullptr) {} + +XSLStyleSheet::XSLStyleSheet(Document* owner_document, + Node* style_sheet_root_node, + const String& original_url, + const KURL& final_url, bool embedded) - : m_ownerNode(styleSheetRootNode), - m_originalURL(originalURL), - m_finalURL(finalURL), - m_isDisabled(false), - m_embedded(embedded), - m_processed(true), // The root sheet starts off processed. - m_stylesheetDoc(0), - m_stylesheetDocTaken(false), - m_compilationFailed(false), - m_parentStyleSheet(nullptr), - m_ownerDocument(ownerDocument) {} + : owner_node_(style_sheet_root_node), + original_url_(original_url), + final_url_(final_url), + is_disabled_(false), + embedded_(embedded), + processed_(true), // The root sheet starts off processed. + stylesheet_doc_(0), + stylesheet_doc_taken_(false), + compilation_failed_(false), + parent_style_sheet_(nullptr), + owner_document_(owner_document) {} XSLStyleSheet::~XSLStyleSheet() { - if (!m_stylesheetDocTaken) - xmlFreeDoc(m_stylesheetDoc); + if (!stylesheet_doc_taken_) + xmlFreeDoc(stylesheet_doc_); } -bool XSLStyleSheet::isLoading() const { - for (unsigned i = 0; i < m_children.size(); ++i) { - if (m_children.at(i)->isLoading()) +bool XSLStyleSheet::IsLoading() const { + for (unsigned i = 0; i < children_.size(); ++i) { + if (children_.at(i)->IsLoading()) return true; } return false; } -void XSLStyleSheet::checkLoaded() { - if (isLoading()) +void XSLStyleSheet::CheckLoaded() { + if (IsLoading()) return; - if (XSLStyleSheet* styleSheet = parentStyleSheet()) - styleSheet->checkLoaded(); + if (XSLStyleSheet* style_sheet = parentStyleSheet()) + style_sheet->CheckLoaded(); if (ownerNode()) - ownerNode()->sheetLoaded(); + ownerNode()->SheetLoaded(); } -xmlDocPtr XSLStyleSheet::document() { - if (m_embedded && ownerDocument() && ownerDocument()->transformSource()) - return (xmlDocPtr)ownerDocument()->transformSource()->platformSource(); - return m_stylesheetDoc; +xmlDocPtr XSLStyleSheet::GetDocument() { + if (embedded_ && OwnerDocument() && OwnerDocument()->GetTransformSource()) + return (xmlDocPtr)OwnerDocument()->GetTransformSource()->PlatformSource(); + return stylesheet_doc_; } -void XSLStyleSheet::clearDocuments() { - m_stylesheetDoc = 0; - for (unsigned i = 0; i < m_children.size(); ++i) { - XSLImportRule* import = m_children.at(i).get(); - if (import->styleSheet()) - import->styleSheet()->clearDocuments(); +void XSLStyleSheet::ClearDocuments() { + stylesheet_doc_ = 0; + for (unsigned i = 0; i < children_.size(); ++i) { + XSLImportRule* import = children_.at(i).Get(); + if (import->GetStyleSheet()) + import->GetStyleSheet()->ClearDocuments(); } } -bool XSLStyleSheet::parseString(const String& source) { +bool XSLStyleSheet::ParseString(const String& source) { // Parse in a single chunk into an xmlDocPtr - if (!m_stylesheetDocTaken) - xmlFreeDoc(m_stylesheetDoc); - m_stylesheetDocTaken = false; + if (!stylesheet_doc_taken_) + xmlFreeDoc(stylesheet_doc_); + stylesheet_doc_taken_ = false; FrameConsole* console = nullptr; - if (LocalFrame* frame = ownerDocument()->frame()) - console = &frame->console(); + if (LocalFrame* frame = OwnerDocument()->GetFrame()) + console = &frame->Console(); - XMLDocumentParserScope scope(ownerDocument(), XSLTProcessor::genericErrorFunc, - XSLTProcessor::parseErrorFunc, console); + XMLDocumentParserScope scope(OwnerDocument(), XSLTProcessor::GenericErrorFunc, + XSLTProcessor::ParseErrorFunc, console); XMLParserInput input(source); - xmlParserCtxtPtr ctxt = xmlCreateMemoryParserCtxt(input.data(), input.size()); + xmlParserCtxtPtr ctxt = xmlCreateMemoryParserCtxt(input.Data(), input.size()); if (!ctxt) return 0; - if (m_parentStyleSheet) { + if (parent_style_sheet_) { // The XSL transform may leave the newly-transformed document // with references to the symbol dictionaries of the style sheet // and any of its children. XML document disposal can corrupt memory @@ -149,58 +148,59 @@ bool XSLStyleSheet::parseString(const String& source) { // ensure that all child stylesheets use the same dictionaries as their // parents. xmlDictFree(ctxt->dict); - ctxt->dict = m_parentStyleSheet->m_stylesheetDoc->dict; + ctxt->dict = parent_style_sheet_->stylesheet_doc_->dict; xmlDictReference(ctxt->dict); } - m_stylesheetDoc = xmlCtxtReadMemory( - ctxt, input.data(), input.size(), finalURL().getString().utf8().data(), - input.encoding(), XML_PARSE_NOENT | XML_PARSE_DTDATTR | + stylesheet_doc_ = + xmlCtxtReadMemory(ctxt, input.Data(), input.size(), + FinalURL().GetString().Utf8().Data(), input.Encoding(), + XML_PARSE_NOENT | XML_PARSE_DTDATTR | XML_PARSE_NOWARNING | XML_PARSE_NOCDATA); xmlFreeParserCtxt(ctxt); - loadChildSheets(); - return m_stylesheetDoc; + LoadChildSheets(); + return stylesheet_doc_; } -void XSLStyleSheet::loadChildSheets() { - if (!document()) +void XSLStyleSheet::LoadChildSheets() { + if (!GetDocument()) return; - xmlNodePtr stylesheetRoot = document()->children; + xmlNodePtr stylesheet_root = GetDocument()->children; // Top level children may include other things such as DTD nodes, we ignore // those. - while (stylesheetRoot && stylesheetRoot->type != XML_ELEMENT_NODE) - stylesheetRoot = stylesheetRoot->next; + while (stylesheet_root && stylesheet_root->type != XML_ELEMENT_NODE) + stylesheet_root = stylesheet_root->next; - if (m_embedded) { + if (embedded_) { // We have to locate (by ID) the appropriate embedded stylesheet // element, so that we can walk the import/include list. - xmlAttrPtr idNode = xmlGetID( - document(), (const xmlChar*)(finalURL().getString().utf8().data())); - if (!idNode) + xmlAttrPtr id_node = xmlGetID( + GetDocument(), (const xmlChar*)(FinalURL().GetString().Utf8().Data())); + if (!id_node) return; - stylesheetRoot = idNode->parent; + stylesheet_root = id_node->parent; } else { // FIXME: Need to handle an external URI with a # in it. This is a // pretty minor edge case, so we'll deal with it later. } - if (stylesheetRoot) { + if (stylesheet_root) { // Walk the children of the root element and look for import/include // elements. Imports must occur first. - xmlNodePtr curr = stylesheetRoot->children; + xmlNodePtr curr = stylesheet_root->children; while (curr) { if (curr->type != XML_ELEMENT_NODE) { curr = curr->next; continue; } if (IS_XSLT_ELEM(curr) && IS_XSLT_NAME(curr, "import")) { - xmlChar* uriRef = + xmlChar* uri_ref = xsltGetNsProp(curr, (const xmlChar*)"href", XSLT_NAMESPACE); - loadChildSheet(String::fromUTF8((const char*)uriRef)); - xmlFree(uriRef); + LoadChildSheet(String::FromUTF8((const char*)uri_ref)); + xmlFree(uri_ref); } else { break; } @@ -211,89 +211,90 @@ void XSLStyleSheet::loadChildSheets() { while (curr) { if (curr->type == XML_ELEMENT_NODE && IS_XSLT_ELEM(curr) && IS_XSLT_NAME(curr, "include")) { - xmlChar* uriRef = + xmlChar* uri_ref = xsltGetNsProp(curr, (const xmlChar*)"href", XSLT_NAMESPACE); - loadChildSheet(String::fromUTF8((const char*)uriRef)); - xmlFree(uriRef); + LoadChildSheet(String::FromUTF8((const char*)uri_ref)); + xmlFree(uri_ref); } curr = curr->next; } } } -void XSLStyleSheet::loadChildSheet(const String& href) { - XSLImportRule* childRule = XSLImportRule::create(this, href); - m_children.push_back(childRule); - childRule->loadSheet(); +void XSLStyleSheet::LoadChildSheet(const String& href) { + XSLImportRule* child_rule = XSLImportRule::Create(this, href); + children_.push_back(child_rule); + child_rule->LoadSheet(); } -xsltStylesheetPtr XSLStyleSheet::compileStyleSheet() { +xsltStylesheetPtr XSLStyleSheet::CompileStyleSheet() { // FIXME: Hook up error reporting for the stylesheet compilation process. - if (m_embedded) - return xsltLoadStylesheetPI(document()); + if (embedded_) + return xsltLoadStylesheetPI(GetDocument()); // Certain libxslt versions are corrupting the xmlDoc on compilation // failures - hence attempting to recompile after a failure is unsafe. - if (m_compilationFailed) + if (compilation_failed_) return 0; // xsltParseStylesheetDoc makes the document part of the stylesheet // so we have to release our pointer to it. - DCHECK(!m_stylesheetDocTaken); - xsltStylesheetPtr result = xsltParseStylesheetDoc(m_stylesheetDoc); + DCHECK(!stylesheet_doc_taken_); + xsltStylesheetPtr result = xsltParseStylesheetDoc(stylesheet_doc_); if (result) - m_stylesheetDocTaken = true; + stylesheet_doc_taken_ = true; else - m_compilationFailed = true; + compilation_failed_ = true; return result; } -void XSLStyleSheet::setParentStyleSheet(XSLStyleSheet* parent) { - m_parentStyleSheet = parent; +void XSLStyleSheet::SetParentStyleSheet(XSLStyleSheet* parent) { + parent_style_sheet_ = parent; } -Document* XSLStyleSheet::ownerDocument() { - for (XSLStyleSheet* styleSheet = this; styleSheet; - styleSheet = styleSheet->parentStyleSheet()) { - if (styleSheet->m_ownerDocument) - return styleSheet->m_ownerDocument.get(); - Node* node = styleSheet->ownerNode(); +Document* XSLStyleSheet::OwnerDocument() { + for (XSLStyleSheet* style_sheet = this; style_sheet; + style_sheet = style_sheet->parentStyleSheet()) { + if (style_sheet->owner_document_) + return style_sheet->owner_document_.Get(); + Node* node = style_sheet->ownerNode(); if (node) - return &node->document(); + return &node->GetDocument(); } return nullptr; } -xmlDocPtr XSLStyleSheet::locateStylesheetSubResource(xmlDocPtr parentDoc, +xmlDocPtr XSLStyleSheet::LocateStylesheetSubResource(xmlDocPtr parent_doc, const xmlChar* uri) { - bool matchedParent = (parentDoc == document()); - for (unsigned i = 0; i < m_children.size(); ++i) { - XSLImportRule* import = m_children.at(i).get(); - XSLStyleSheet* child = import->styleSheet(); + bool matched_parent = (parent_doc == GetDocument()); + for (unsigned i = 0; i < children_.size(); ++i) { + XSLImportRule* import = children_.at(i).Get(); + XSLStyleSheet* child = import->GetStyleSheet(); if (!child) continue; - if (matchedParent) { - if (child->processed()) + if (matched_parent) { + if (child->Processed()) continue; // libxslt has been given this sheet already. // Check the URI of the child stylesheet against the doc URI. // In order to ensure that libxml canonicalized both URLs, we get // the original href string from the import rule and canonicalize it // using libxml before comparing it with the URI argument. - CString importHref = import->href().utf8(); - xmlChar* base = xmlNodeGetBase(parentDoc, (xmlNodePtr)parentDoc); - xmlChar* childURI = xmlBuildURI((const xmlChar*)importHref.data(), base); - bool equalURIs = xmlStrEqual(uri, childURI); + CString import_href = import->Href().Utf8(); + xmlChar* base = xmlNodeGetBase(parent_doc, (xmlNodePtr)parent_doc); + xmlChar* child_uri = + xmlBuildURI((const xmlChar*)import_href.Data(), base); + bool equal_ur_is = xmlStrEqual(uri, child_uri); xmlFree(base); - xmlFree(childURI); - if (equalURIs) { - child->markAsProcessed(); - return child->document(); + xmlFree(child_uri); + if (equal_ur_is) { + child->MarkAsProcessed(); + return child->GetDocument(); } continue; } xmlDocPtr result = - import->styleSheet()->locateStylesheetSubResource(parentDoc, uri); + import->GetStyleSheet()->LocateStylesheetSubResource(parent_doc, uri); if (result) return result; } @@ -301,19 +302,19 @@ xmlDocPtr XSLStyleSheet::locateStylesheetSubResource(xmlDocPtr parentDoc, return 0; } -void XSLStyleSheet::markAsProcessed() { - DCHECK(!m_processed); - DCHECK(!m_stylesheetDocTaken); - m_processed = true; - m_stylesheetDocTaken = true; +void XSLStyleSheet::MarkAsProcessed() { + DCHECK(!processed_); + DCHECK(!stylesheet_doc_taken_); + processed_ = true; + stylesheet_doc_taken_ = true; } DEFINE_TRACE(XSLStyleSheet) { - visitor->trace(m_ownerNode); - visitor->trace(m_children); - visitor->trace(m_parentStyleSheet); - visitor->trace(m_ownerDocument); - StyleSheet::trace(visitor); + visitor->Trace(owner_node_); + visitor->Trace(children_); + visitor->Trace(parent_style_sheet_); + visitor->Trace(owner_document_); + StyleSheet::Trace(visitor); } } // namespace blink diff --git a/chromium/third_party/WebKit/Source/core/xml/XSLTExtensions.cpp b/chromium/third_party/WebKit/Source/core/xml/XSLTExtensions.cpp index e208030839a..15a1f4bcc96 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XSLTExtensions.cpp +++ b/chromium/third_party/WebKit/Source/core/xml/XSLTExtensions.cpp @@ -26,20 +26,20 @@ #include "core/xml/XSLTExtensions.h" -#include "platform/RuntimeEnabledFeatures.h" -#include "wtf/Assertions.h" #include <libxml/xpathInternals.h> #include <libxslt/extensions.h> #include <libxslt/extra.h> #include <libxslt/xsltutils.h> +#include "platform/RuntimeEnabledFeatures.h" +#include "platform/wtf/Assertions.h" namespace blink { // FIXME: This code is taken from libexslt 1.1.11; should sync with newer // versions. -static void exsltNodeSetFunction(xmlXPathParserContextPtr ctxt, int nargs) { +static void ExsltNodeSetFunction(xmlXPathParserContextPtr ctxt, int nargs) { xmlChar* strval; - xmlNodePtr retNode; + xmlNodePtr ret_node; xmlXPathObjectPtr ret; if (nargs != 1) { @@ -63,9 +63,9 @@ static void exsltNodeSetFunction(xmlXPathParserContextPtr ctxt, int nargs) { // Create the text node and wrap it in a result set. strval = xmlXPathPopString(ctxt); - retNode = xmlNewDocText(fragment, strval); - xmlAddChild(reinterpret_cast<xmlNodePtr>(fragment), retNode); - ret = xmlXPathNewNodeSet(retNode); + ret_node = xmlNewDocText(fragment, strval); + xmlAddChild(reinterpret_cast<xmlNodePtr>(fragment), ret_node); + ret = xmlXPathNewNodeSet(ret_node); CHECK(ret); if (strval) @@ -74,11 +74,11 @@ static void exsltNodeSetFunction(xmlXPathParserContextPtr ctxt, int nargs) { valuePush(ctxt, ret); } -void registerXSLTExtensions(xsltTransformContextPtr ctxt) { +void RegisterXSLTExtensions(xsltTransformContextPtr ctxt) { DCHECK(RuntimeEnabledFeatures::xsltEnabled()); xsltRegisterExtFunction(ctxt, (const xmlChar*)"node-set", (const xmlChar*)"http://exslt.org/common", - exsltNodeSetFunction); + ExsltNodeSetFunction); } } // namespace blink diff --git a/chromium/third_party/WebKit/Source/core/xml/XSLTExtensions.h b/chromium/third_party/WebKit/Source/core/xml/XSLTExtensions.h index 943322eef34..2599e687fbf 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XSLTExtensions.h +++ b/chromium/third_party/WebKit/Source/core/xml/XSLTExtensions.h @@ -30,7 +30,7 @@ namespace blink { -void registerXSLTExtensions(xsltTransformContextPtr ctxt); +void RegisterXSLTExtensions(xsltTransformContextPtr ctxt); } #endif diff --git a/chromium/third_party/WebKit/Source/core/xml/XSLTProcessor.cpp b/chromium/third_party/WebKit/Source/core/xml/XSLTProcessor.cpp index 5e37c61418f..1ba88049e6d 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XSLTProcessor.cpp +++ b/chromium/third_party/WebKit/Source/core/xml/XSLTProcessor.cpp @@ -33,15 +33,15 @@ #include "core/frame/csp/ContentSecurityPolicy.h" #include "core/xml/DocumentXSLT.h" #include "platform/weborigin/SecurityOrigin.h" -#include "wtf/Assertions.h" +#include "platform/wtf/Assertions.h" namespace blink { -static inline void transformTextStringToXHTMLDocumentString(String& text) { +static inline void TransformTextStringToXHTMLDocumentString(String& text) { // Modify the output so that it is a well-formed XHTML document with a <pre> // tag enclosing the text. - text.replace('&', "&"); - text.replace('<', "<"); + text.Replace('&', "&"); + text.Replace('<', "<"); text = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" " @@ -58,117 +58,119 @@ static inline void transformTextStringToXHTMLDocumentString(String& text) { XSLTProcessor::~XSLTProcessor() {} -Document* XSLTProcessor::createDocumentFromSource(const String& sourceString, - const String& sourceEncoding, - const String& sourceMIMEType, - Node* sourceNode, - LocalFrame* frame) { - Document* ownerDocument = &sourceNode->document(); - bool sourceIsDocument = (sourceNode == ownerDocument); - String documentSource = sourceString; +Document* XSLTProcessor::CreateDocumentFromSource( + const String& source_string, + const String& source_encoding, + const String& source_mime_type, + Node* source_node, + LocalFrame* frame) { + Document* owner_document = &source_node->GetDocument(); + bool source_is_document = (source_node == owner_document); + String document_source = source_string; Document* result = nullptr; - DocumentInit init(sourceIsDocument ? ownerDocument->url() : KURL(), frame); + DocumentInit init(source_is_document ? owner_document->Url() : KURL(), frame); - bool forceXHTML = sourceMIMEType == "text/plain"; - if (forceXHTML) - transformTextStringToXHTMLDocumentString(documentSource); + bool force_xhtml = source_mime_type == "text/plain"; + if (force_xhtml) + TransformTextStringToXHTMLDocumentString(document_source); if (frame) { - Document* oldDocument = frame->document(); + Document* old_document = frame->GetDocument(); // Before parsing, we need to save & detach the old document and get the new // document in place. Document::shutdown() tears down the FrameView, so // remember whether or not there was one. - bool hasView = frame->view(); - oldDocument->shutdown(); + bool has_view = frame->View(); + old_document->Shutdown(); // Re-create the FrameView if needed. - if (hasView) - frame->loader().client()->transitionToCommittedForNewPage(); - result = frame->domWindow()->installNewDocument(sourceMIMEType, init, - forceXHTML); - - if (oldDocument) { - DocumentXSLT::from(*result).setTransformSourceDocument(oldDocument); - result->updateSecurityOrigin(oldDocument->getSecurityOrigin()); - result->setCookieURL(oldDocument->cookieURL()); - - ContentSecurityPolicy* csp = ContentSecurityPolicy::create(); - csp->copyStateFrom(oldDocument->contentSecurityPolicy()); - result->initContentSecurityPolicy(csp); + if (has_view) + frame->Loader().Client()->TransitionToCommittedForNewPage(); + result = frame->DomWindow()->InstallNewDocument(source_mime_type, init, + force_xhtml); + + if (old_document) { + DocumentXSLT::From(*result).SetTransformSourceDocument(old_document); + result->UpdateSecurityOrigin(old_document->GetSecurityOrigin()); + result->SetCookieURL(old_document->CookieURL()); + + ContentSecurityPolicy* csp = ContentSecurityPolicy::Create(); + csp->CopyStateFrom(old_document->GetContentSecurityPolicy()); + result->InitContentSecurityPolicy(csp); } } else { - result = LocalDOMWindow::createDocument(sourceMIMEType, init, forceXHTML); + result = + LocalDOMWindow::CreateDocument(source_mime_type, init, force_xhtml); } DocumentEncodingData data; - data.setEncoding(sourceEncoding.isEmpty() + data.SetEncoding(source_encoding.IsEmpty() ? UTF8Encoding() - : WTF::TextEncoding(sourceEncoding)); - result->setEncodingData(data); - result->setContent(documentSource); + : WTF::TextEncoding(source_encoding)); + result->SetEncodingData(data); + result->SetContent(document_source); return result; } -Document* XSLTProcessor::transformToDocument(Node* sourceNode) { - String resultMIMEType; - String resultString; - String resultEncoding; - if (!transformToString(sourceNode, resultMIMEType, resultString, - resultEncoding)) +Document* XSLTProcessor::transformToDocument(Node* source_node) { + String result_mime_type; + String result_string; + String result_encoding; + if (!TransformToString(source_node, result_mime_type, result_string, + result_encoding)) return nullptr; - return createDocumentFromSource(resultString, resultEncoding, resultMIMEType, - sourceNode, 0); + return CreateDocumentFromSource(result_string, result_encoding, + result_mime_type, source_node, 0); } -DocumentFragment* XSLTProcessor::transformToFragment(Node* sourceNode, - Document* outputDoc) { - String resultMIMEType; - String resultString; - String resultEncoding; +DocumentFragment* XSLTProcessor::transformToFragment(Node* source_node, + Document* output_doc) { + String result_mime_type; + String result_string; + String result_encoding; // If the output document is HTML, default to HTML method. - if (outputDoc->isHTMLDocument()) - resultMIMEType = "text/html"; + if (output_doc->IsHTMLDocument()) + result_mime_type = "text/html"; - if (!transformToString(sourceNode, resultMIMEType, resultString, - resultEncoding)) + if (!TransformToString(source_node, result_mime_type, result_string, + result_encoding)) return nullptr; - return createFragmentForTransformToFragment(resultString, resultMIMEType, - *outputDoc); + return CreateFragmentForTransformToFragment(result_string, result_mime_type, + *output_doc); } void XSLTProcessor::setParameter(const String& /*namespaceURI*/, - const String& localName, + const String& local_name, const String& value) { // FIXME: namespace support? // should make a QualifiedName here but we'd have to expose the impl - m_parameters.set(localName, value); + parameters_.Set(local_name, value); } String XSLTProcessor::getParameter(const String& /*namespaceURI*/, - const String& localName) const { + const String& local_name) const { // FIXME: namespace support? // should make a QualifiedName here but we'd have to expose the impl - return m_parameters.at(localName); + return parameters_.at(local_name); } void XSLTProcessor::removeParameter(const String& /*namespaceURI*/, - const String& localName) { + const String& local_name) { // FIXME: namespace support? - m_parameters.erase(localName); + parameters_.erase(local_name); } void XSLTProcessor::reset() { - m_stylesheet.clear(); - m_stylesheetRootNode.clear(); - m_parameters.clear(); + stylesheet_.Clear(); + stylesheet_root_node_.Clear(); + parameters_.Clear(); } DEFINE_TRACE(XSLTProcessor) { - visitor->trace(m_stylesheet); - visitor->trace(m_stylesheetRootNode); - visitor->trace(m_document); + visitor->Trace(stylesheet_); + visitor->Trace(stylesheet_root_node_); + visitor->Trace(document_); } } // namespace blink diff --git a/chromium/third_party/WebKit/Source/core/xml/XSLTProcessor.h b/chromium/third_party/WebKit/Source/core/xml/XSLTProcessor.h index 808e0bc6ece..9c5ef7e86ab 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XSLTProcessor.h +++ b/chromium/third_party/WebKit/Source/core/xml/XSLTProcessor.h @@ -27,8 +27,8 @@ #include "core/dom/Node.h" #include "core/xml/XSLStyleSheet.h" #include "platform/RuntimeEnabledFeatures.h" -#include "wtf/HashMap.h" -#include "wtf/text/StringHash.h" +#include "platform/wtf/HashMap.h" +#include "platform/wtf/text/StringHash.h" #include <libxml/parserInternals.h> #include <libxslt/documents.h> @@ -44,57 +44,57 @@ class XSLTProcessor final : public GarbageCollectedFinalized<XSLTProcessor>, DEFINE_WRAPPERTYPEINFO(); public: - static XSLTProcessor* create(Document& document) { + static XSLTProcessor* Create(Document& document) { DCHECK(RuntimeEnabledFeatures::xsltEnabled()); return new XSLTProcessor(document); } ~XSLTProcessor(); - void setXSLStyleSheet(XSLStyleSheet* styleSheet) { - m_stylesheet = styleSheet; + void SetXSLStyleSheet(XSLStyleSheet* style_sheet) { + stylesheet_ = style_sheet; } - bool transformToString(Node* source, - String& resultMIMEType, - String& resultString, - String& resultEncoding); - Document* createDocumentFromSource(const String& source, - const String& sourceEncoding, - const String& sourceMIMEType, - Node* sourceNode, + bool TransformToString(Node* source, + String& result_mime_type, + String& result_string, + String& result_encoding); + Document* CreateDocumentFromSource(const String& source, + const String& source_encoding, + const String& source_mime_type, + Node* source_node, LocalFrame*); // DOM methods - void importStylesheet(Node* style) { m_stylesheetRootNode = style; } - DocumentFragment* transformToFragment(Node* source, Document* ouputDoc); + void importStylesheet(Node* style) { stylesheet_root_node_ = style; } + DocumentFragment* transformToFragment(Node* source, Document* ouput_doc); Document* transformToDocument(Node* source); - void setParameter(const String& namespaceURI, - const String& localName, + void setParameter(const String& namespace_uri, + const String& local_name, const String& value); - String getParameter(const String& namespaceURI, - const String& localName) const; - void removeParameter(const String& namespaceURI, const String& localName); - void clearParameters() { m_parameters.clear(); } + String getParameter(const String& namespace_uri, + const String& local_name) const; + void removeParameter(const String& namespace_uri, const String& local_name); + void clearParameters() { parameters_.Clear(); } void reset(); - static void parseErrorFunc(void* userData, xmlError*); - static void genericErrorFunc(void* userData, const char* msg, ...); + static void ParseErrorFunc(void* user_data, xmlError*); + static void GenericErrorFunc(void* user_data, const char* msg, ...); // Only for libXSLT callbacks - XSLStyleSheet* xslStylesheet() const { return m_stylesheet.get(); } + XSLStyleSheet* XslStylesheet() const { return stylesheet_.Get(); } typedef HashMap<String, String> ParameterMap; DECLARE_TRACE(); private: - XSLTProcessor(Document& document) : m_document(&document) {} + XSLTProcessor(Document& document) : document_(&document) {} - Member<XSLStyleSheet> m_stylesheet; - Member<Node> m_stylesheetRootNode; - Member<Document> m_document; - ParameterMap m_parameters; + Member<XSLStyleSheet> stylesheet_; + Member<Node> stylesheet_root_node_; + Member<Document> document_; + ParameterMap parameters_; }; } // namespace blink diff --git a/chromium/third_party/WebKit/Source/core/xml/XSLTProcessorLibxslt.cpp b/chromium/third_party/WebKit/Source/core/xml/XSLTProcessorLibxslt.cpp index 88284a9a0f8..078a79ce1d1 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XSLTProcessorLibxslt.cpp +++ b/chromium/third_party/WebKit/Source/core/xml/XSLTProcessorLibxslt.cpp @@ -22,12 +22,15 @@ #include "core/xml/XSLTProcessor.h" +#include <libxslt/imports.h> +#include <libxslt/security.h> +#include <libxslt/variables.h> +#include <libxslt/xsltutils.h> #include "bindings/core/v8/SourceLocation.h" #include "core/dom/Document.h" #include "core/dom/TransformSource.h" #include "core/editing/serializers/Serialization.h" #include "core/frame/FrameConsole.h" -#include "core/frame/FrameHost.h" #include "core/frame/LocalFrame.h" #include "core/inspector/ConsoleMessage.h" #include "core/xml/XSLStyleSheet.h" @@ -38,95 +41,91 @@ #include "platform/loader/fetch/FetchInitiatorTypeNames.h" #include "platform/loader/fetch/RawResource.h" #include "platform/loader/fetch/Resource.h" +#include "platform/loader/fetch/ResourceError.h" #include "platform/loader/fetch/ResourceFetcher.h" -#include "platform/network/ResourceError.h" -#include "platform/network/ResourceRequest.h" -#include "platform/network/ResourceResponse.h" +#include "platform/loader/fetch/ResourceRequest.h" +#include "platform/loader/fetch/ResourceResponse.h" #include "platform/weborigin/SecurityOrigin.h" -#include "wtf/Assertions.h" -#include "wtf/allocator/Partitions.h" -#include "wtf/text/CString.h" -#include "wtf/text/StringBuffer.h" -#include "wtf/text/UTF8.h" -#include <libxslt/imports.h> -#include <libxslt/security.h> -#include <libxslt/variables.h> -#include <libxslt/xsltutils.h> +#include "platform/wtf/Assertions.h" +#include "platform/wtf/allocator/Partitions.h" +#include "platform/wtf/text/CString.h" +#include "platform/wtf/text/StringBuffer.h" +#include "platform/wtf/text/UTF8.h" namespace blink { -void XSLTProcessor::genericErrorFunc(void*, const char*, ...) { +void XSLTProcessor::GenericErrorFunc(void*, const char*, ...) { // It would be nice to do something with this error message. } -void XSLTProcessor::parseErrorFunc(void* userData, xmlError* error) { - FrameConsole* console = static_cast<FrameConsole*>(userData); +void XSLTProcessor::ParseErrorFunc(void* user_data, xmlError* error) { + FrameConsole* console = static_cast<FrameConsole*>(user_data); if (!console) return; MessageLevel level; switch (error->level) { case XML_ERR_NONE: - level = VerboseMessageLevel; + level = kVerboseMessageLevel; break; case XML_ERR_WARNING: - level = WarningMessageLevel; + level = kWarningMessageLevel; break; case XML_ERR_ERROR: case XML_ERR_FATAL: default: - level = ErrorMessageLevel; + level = kErrorMessageLevel; break; } - console->addMessage(ConsoleMessage::create( - XMLMessageSource, level, error->message, - SourceLocation::create(error->file, error->line, 0, nullptr))); + console->AddMessage(ConsoleMessage::Create( + kXMLMessageSource, level, error->message, + SourceLocation::Create(error->file, error->line, 0, nullptr))); } // FIXME: There seems to be no way to control the ctxt pointer for loading here, // thus we have globals. -static XSLTProcessor* globalProcessor = nullptr; -static ResourceFetcher* globalResourceFetcher = nullptr; +static XSLTProcessor* g_global_processor = nullptr; +static ResourceFetcher* g_global_resource_fetcher = nullptr; -static xmlDocPtr docLoaderFunc(const xmlChar* uri, +static xmlDocPtr DocLoaderFunc(const xmlChar* uri, xmlDictPtr, int options, void* ctxt, xsltLoadType type) { - if (!globalProcessor) + if (!g_global_processor) return nullptr; switch (type) { case XSLT_LOAD_DOCUMENT: { xsltTransformContextPtr context = (xsltTransformContextPtr)ctxt; xmlChar* base = xmlNodeGetBase(context->document->doc, context->node); - KURL url(KURL(ParsedURLString, reinterpret_cast<const char*>(base)), + KURL url(KURL(kParsedURLString, reinterpret_cast<const char*>(base)), reinterpret_cast<const char*>(uri)); xmlFree(base); - ResourceLoaderOptions fetchOptions( - ResourceFetcher::defaultResourceOptions()); - FetchRequest request(ResourceRequest(url), FetchInitiatorTypeNames::xml, - fetchOptions); - request.setOriginRestriction(FetchRequest::RestrictToSameOrigin); + ResourceLoaderOptions fetch_options( + ResourceFetcher::DefaultResourceOptions()); + FetchParameters params(ResourceRequest(url), FetchInitiatorTypeNames::xml, + fetch_options); + params.SetOriginRestriction(FetchParameters::kRestrictToSameOrigin); Resource* resource = - RawResource::fetchSynchronously(request, globalResourceFetcher); - if (!resource || !globalProcessor) + RawResource::FetchSynchronously(params, g_global_resource_fetcher); + if (!resource || !g_global_processor) return nullptr; FrameConsole* console = nullptr; LocalFrame* frame = - globalProcessor->xslStylesheet()->ownerDocument()->frame(); + g_global_processor->XslStylesheet()->OwnerDocument()->GetFrame(); if (frame) - console = &frame->console(); - xmlSetStructuredErrorFunc(console, XSLTProcessor::parseErrorFunc); - xmlSetGenericErrorFunc(console, XSLTProcessor::genericErrorFunc); + console = &frame->Console(); + xmlSetStructuredErrorFunc(console, XSLTProcessor::ParseErrorFunc); + xmlSetGenericErrorFunc(console, XSLTProcessor::GenericErrorFunc); // We don't specify an encoding here. Neither Gecko nor WinIE respects // the encoding specified in the HTTP headers. - RefPtr<const SharedBuffer> data = resource->resourceBuffer(); - xmlDocPtr doc = data ? xmlReadMemory(data->data(), data->size(), + RefPtr<const SharedBuffer> data = resource->ResourceBuffer(); + xmlDocPtr doc = data ? xmlReadMemory(data->Data(), data->size(), (const char*)uri, 0, options) : nullptr; @@ -136,7 +135,7 @@ static xmlDocPtr docLoaderFunc(const xmlChar* uri, return doc; } case XSLT_LOAD_STYLESHEET: - return globalProcessor->xslStylesheet()->locateStylesheetSubResource( + return g_global_processor->XslStylesheet()->LocateStylesheetSubResource( ((xsltStylesheetPtr)ctxt)->doc, uri); default: break; @@ -145,250 +144,252 @@ static xmlDocPtr docLoaderFunc(const xmlChar* uri, return nullptr; } -static inline void setXSLTLoadCallBack(xsltDocLoaderFunc func, +static inline void SetXSLTLoadCallBack(xsltDocLoaderFunc func, XSLTProcessor* processor, ResourceFetcher* fetcher) { xsltSetLoaderFunc(func); - globalProcessor = processor; - globalResourceFetcher = fetcher; + g_global_processor = processor; + g_global_resource_fetcher = fetcher; } -static int writeToStringBuilder(void* context, const char* buffer, int len) { - StringBuilder& resultOutput = *static_cast<StringBuilder*>(context); +static int WriteToStringBuilder(void* context, const char* buffer, int len) { + StringBuilder& result_output = *static_cast<StringBuilder*>(context); if (!len) return 0; - StringBuffer<UChar> stringBuffer(len); - UChar* bufferUChar = stringBuffer.characters(); - UChar* bufferUCharEnd = bufferUChar + len; + StringBuffer<UChar> string_buffer(len); + UChar* buffer_u_char = string_buffer.Characters(); + UChar* buffer_u_char_end = buffer_u_char + len; - const char* stringCurrent = buffer; - WTF::Unicode::ConversionResult result = WTF::Unicode::convertUTF8ToUTF16( - &stringCurrent, buffer + len, &bufferUChar, bufferUCharEnd); - if (result != WTF::Unicode::conversionOK && - result != WTF::Unicode::sourceExhausted) { + const char* string_current = buffer; + WTF::Unicode::ConversionResult result = WTF::Unicode::ConvertUTF8ToUTF16( + &string_current, buffer + len, &buffer_u_char, buffer_u_char_end); + if (result != WTF::Unicode::kConversionOK && + result != WTF::Unicode::kSourceExhausted) { NOTREACHED(); return -1; } - int utf16Length = bufferUChar - stringBuffer.characters(); - resultOutput.append(stringBuffer.characters(), utf16Length); - return stringCurrent - buffer; + int utf16_length = buffer_u_char - string_buffer.Characters(); + result_output.Append(string_buffer.Characters(), utf16_length); + return string_current - buffer; } -static bool saveResultToString(xmlDocPtr resultDoc, +static bool SaveResultToString(xmlDocPtr result_doc, xsltStylesheetPtr sheet, - String& resultString) { - xmlOutputBufferPtr outputBuf = xmlAllocOutputBuffer(0); - if (!outputBuf) + String& result_string) { + xmlOutputBufferPtr output_buf = xmlAllocOutputBuffer(0); + if (!output_buf) return false; - StringBuilder resultBuilder; - outputBuf->context = &resultBuilder; - outputBuf->writecallback = writeToStringBuilder; + StringBuilder result_builder; + output_buf->context = &result_builder; + output_buf->writecallback = WriteToStringBuilder; - int retval = xsltSaveResultTo(outputBuf, resultDoc, sheet); - xmlOutputBufferClose(outputBuf); + int retval = xsltSaveResultTo(output_buf, result_doc, sheet); + xmlOutputBufferClose(output_buf); if (retval < 0) return false; // Workaround for <http://bugzilla.gnome.org/show_bug.cgi?id=495668>: // libxslt appends an extra line feed to the result. - if (resultBuilder.length() > 0 && - resultBuilder[resultBuilder.length() - 1] == '\n') - resultBuilder.resize(resultBuilder.length() - 1); + if (result_builder.length() > 0 && + result_builder[result_builder.length() - 1] == '\n') + result_builder.Resize(result_builder.length() - 1); - resultString = resultBuilder.toString(); + result_string = result_builder.ToString(); return true; } -static char* allocateParameterArray(const char* data) { +static char* AllocateParameterArray(const char* data) { size_t length = strlen(data) + 1; - char* parameterArray = static_cast<char*>(WTF::Partitions::fastMalloc( + char* parameter_array = static_cast<char*>(WTF::Partitions::FastMalloc( length, WTF_HEAP_PROFILER_TYPE_NAME(XSLTProcessor))); - memcpy(parameterArray, data, length); - return parameterArray; + memcpy(parameter_array, data, length); + return parameter_array; } -static const char** xsltParamArrayFromParameterMap( +static const char** XsltParamArrayFromParameterMap( XSLTProcessor::ParameterMap& parameters) { - if (parameters.isEmpty()) + if (parameters.IsEmpty()) return nullptr; - const char** parameterArray = static_cast<const char**>( - WTF::Partitions::fastMalloc(((parameters.size() * 2) + 1) * sizeof(char*), + const char** parameter_array = static_cast<const char**>( + WTF::Partitions::FastMalloc(((parameters.size() * 2) + 1) * sizeof(char*), WTF_HEAP_PROFILER_TYPE_NAME(XSLTProcessor))); unsigned index = 0; for (auto& parameter : parameters) { - parameterArray[index++] = - allocateParameterArray(parameter.key.utf8().data()); - parameterArray[index++] = - allocateParameterArray(parameter.value.utf8().data()); + parameter_array[index++] = + AllocateParameterArray(parameter.key.Utf8().Data()); + parameter_array[index++] = + AllocateParameterArray(parameter.value.Utf8().Data()); } - parameterArray[index] = 0; + parameter_array[index] = 0; - return parameterArray; + return parameter_array; } -static void freeXsltParamArray(const char** params) { +static void FreeXsltParamArray(const char** params) { const char** temp = params; if (!params) return; while (*temp) { - WTF::Partitions::fastFree(const_cast<char*>(*(temp++))); - WTF::Partitions::fastFree(const_cast<char*>(*(temp++))); + WTF::Partitions::FastFree(const_cast<char*>(*(temp++))); + WTF::Partitions::FastFree(const_cast<char*>(*(temp++))); } - WTF::Partitions::fastFree(params); + WTF::Partitions::FastFree(params); } -static xsltStylesheetPtr xsltStylesheetPointer( +static xsltStylesheetPtr XsltStylesheetPointer( Document* document, - Member<XSLStyleSheet>& cachedStylesheet, - Node* stylesheetRootNode) { - if (!cachedStylesheet && stylesheetRootNode) { + Member<XSLStyleSheet>& cached_stylesheet, + Node* stylesheet_root_node) { + if (!cached_stylesheet && stylesheet_root_node) { // When using importStylesheet, we will use the given document as the // imported stylesheet's owner. - cachedStylesheet = XSLStyleSheet::createForXSLTProcessor( - stylesheetRootNode->parentNode() - ? &stylesheetRootNode->parentNode()->document() + cached_stylesheet = XSLStyleSheet::CreateForXSLTProcessor( + stylesheet_root_node->parentNode() + ? &stylesheet_root_node->parentNode()->GetDocument() : document, - stylesheetRootNode, stylesheetRootNode->document().url().getString(), - stylesheetRootNode->document() - .url()); // FIXME: Should we use baseURL here? + stylesheet_root_node, + stylesheet_root_node->GetDocument().Url().GetString(), + stylesheet_root_node->GetDocument() + .Url()); // FIXME: Should we use baseURL here? // According to Mozilla documentation, the node must be a Document node, // an xsl:stylesheet or xsl:transform element. But we just use text // content regardless of node type. - cachedStylesheet->parseString(createMarkup(stylesheetRootNode)); + cached_stylesheet->ParseString(CreateMarkup(stylesheet_root_node)); } - if (!cachedStylesheet || !cachedStylesheet->document()) + if (!cached_stylesheet || !cached_stylesheet->GetDocument()) return nullptr; - return cachedStylesheet->compileStyleSheet(); + return cached_stylesheet->CompileStyleSheet(); } -static inline xmlDocPtr xmlDocPtrFromNode(Node* sourceNode, - bool& shouldDelete) { - Document* ownerDocument = &sourceNode->document(); - bool sourceIsDocument = (sourceNode == ownerDocument); - - xmlDocPtr sourceDoc = nullptr; - if (sourceIsDocument && ownerDocument->transformSource()) - sourceDoc = (xmlDocPtr)ownerDocument->transformSource()->platformSource(); - if (!sourceDoc) { - sourceDoc = (xmlDocPtr)xmlDocPtrForString( - ownerDocument, createMarkup(sourceNode), - sourceIsDocument ? ownerDocument->url().getString() : String()); - shouldDelete = sourceDoc; +static inline xmlDocPtr XmlDocPtrFromNode(Node* source_node, + bool& should_delete) { + Document* owner_document = &source_node->GetDocument(); + bool source_is_document = (source_node == owner_document); + + xmlDocPtr source_doc = nullptr; + if (source_is_document && owner_document->GetTransformSource()) + source_doc = + (xmlDocPtr)owner_document->GetTransformSource()->PlatformSource(); + if (!source_doc) { + source_doc = (xmlDocPtr)XmlDocPtrForString( + owner_document, CreateMarkup(source_node), + source_is_document ? owner_document->Url().GetString() : String()); + should_delete = source_doc; } - return sourceDoc; + return source_doc; } -static inline String resultMIMEType(xmlDocPtr resultDoc, +static inline String ResultMIMEType(xmlDocPtr result_doc, xsltStylesheetPtr sheet) { // There are three types of output we need to be able to deal with: // HTML (create an HTML document), XML (create an XML document), // and text (wrap in a <pre> and create an XML document). - const xmlChar* resultType = nullptr; - XSLT_GET_IMPORT_PTR(resultType, sheet, method); - if (!resultType && resultDoc->type == XML_HTML_DOCUMENT_NODE) - resultType = (const xmlChar*)"html"; + const xmlChar* result_type = nullptr; + XSLT_GET_IMPORT_PTR(result_type, sheet, method); + if (!result_type && result_doc->type == XML_HTML_DOCUMENT_NODE) + result_type = (const xmlChar*)"html"; - if (xmlStrEqual(resultType, (const xmlChar*)"html")) + if (xmlStrEqual(result_type, (const xmlChar*)"html")) return "text/html"; - if (xmlStrEqual(resultType, (const xmlChar*)"text")) + if (xmlStrEqual(result_type, (const xmlChar*)"text")) return "text/plain"; return "application/xml"; } -bool XSLTProcessor::transformToString(Node* sourceNode, - String& mimeType, - String& resultString, - String& resultEncoding) { - Document* ownerDocument = &sourceNode->document(); +bool XSLTProcessor::TransformToString(Node* source_node, + String& mime_type, + String& result_string, + String& result_encoding) { + Document* owner_document = &source_node->GetDocument(); - setXSLTLoadCallBack(docLoaderFunc, this, ownerDocument->fetcher()); - xsltStylesheetPtr sheet = xsltStylesheetPointer( - m_document.get(), m_stylesheet, m_stylesheetRootNode.get()); + SetXSLTLoadCallBack(DocLoaderFunc, this, owner_document->Fetcher()); + xsltStylesheetPtr sheet = XsltStylesheetPointer(document_.Get(), stylesheet_, + stylesheet_root_node_.Get()); if (!sheet) { - setXSLTLoadCallBack(0, 0, 0); - m_stylesheet = nullptr; + SetXSLTLoadCallBack(0, 0, 0); + stylesheet_ = nullptr; return false; } - m_stylesheet->clearDocuments(); + stylesheet_->ClearDocuments(); - xmlChar* origMethod = sheet->method; - if (!origMethod && mimeType == "text/html") + xmlChar* orig_method = sheet->method; + if (!orig_method && mime_type == "text/html") sheet->method = (xmlChar*)"html"; bool success = false; - bool shouldFreeSourceDoc = false; - if (xmlDocPtr sourceDoc = - xmlDocPtrFromNode(sourceNode, shouldFreeSourceDoc)) { + bool should_free_source_doc = false; + if (xmlDocPtr source_doc = + XmlDocPtrFromNode(source_node, should_free_source_doc)) { // The XML declaration would prevent parsing the result as a fragment, // and it's not needed even for documents, as the result of this // function is always immediately parsed. sheet->omitXmlDeclaration = true; - xsltTransformContextPtr transformContext = - xsltNewTransformContext(sheet, sourceDoc); - registerXSLTExtensions(transformContext); + xsltTransformContextPtr transform_context = + xsltNewTransformContext(sheet, source_doc); + RegisterXSLTExtensions(transform_context); - xsltSecurityPrefsPtr securityPrefs = xsltNewSecurityPrefs(); + xsltSecurityPrefsPtr security_prefs = xsltNewSecurityPrefs(); // Read permissions are checked by docLoaderFunc. - if (0 != xsltSetSecurityPrefs(securityPrefs, XSLT_SECPREF_WRITE_FILE, + if (0 != xsltSetSecurityPrefs(security_prefs, XSLT_SECPREF_WRITE_FILE, xsltSecurityForbid)) CRASH(); - if (0 != xsltSetSecurityPrefs(securityPrefs, XSLT_SECPREF_CREATE_DIRECTORY, + if (0 != xsltSetSecurityPrefs(security_prefs, XSLT_SECPREF_CREATE_DIRECTORY, xsltSecurityForbid)) CRASH(); - if (0 != xsltSetSecurityPrefs(securityPrefs, XSLT_SECPREF_WRITE_NETWORK, + if (0 != xsltSetSecurityPrefs(security_prefs, XSLT_SECPREF_WRITE_NETWORK, xsltSecurityForbid)) CRASH(); - if (0 != xsltSetCtxtSecurityPrefs(securityPrefs, transformContext)) + if (0 != xsltSetCtxtSecurityPrefs(security_prefs, transform_context)) CRASH(); // <http://bugs.webkit.org/show_bug.cgi?id=16077>: XSLT processor // <xsl:sort> algorithm only compares by code point. - xsltSetCtxtSortFunc(transformContext, xsltUnicodeSortFunction); + xsltSetCtxtSortFunc(transform_context, XsltUnicodeSortFunction); // This is a workaround for a bug in libxslt. // The bug has been fixed in version 1.1.13, so once we ship that this // can be removed. - if (!transformContext->globalVars) - transformContext->globalVars = xmlHashCreate(20); + if (!transform_context->globalVars) + transform_context->globalVars = xmlHashCreate(20); - const char** params = xsltParamArrayFromParameterMap(m_parameters); - xsltQuoteUserParams(transformContext, params); - xmlDocPtr resultDoc = - xsltApplyStylesheetUser(sheet, sourceDoc, 0, 0, 0, transformContext); + const char** params = XsltParamArrayFromParameterMap(parameters_); + xsltQuoteUserParams(transform_context, params); + xmlDocPtr result_doc = + xsltApplyStylesheetUser(sheet, source_doc, 0, 0, 0, transform_context); - xsltFreeTransformContext(transformContext); - xsltFreeSecurityPrefs(securityPrefs); - freeXsltParamArray(params); + xsltFreeTransformContext(transform_context); + xsltFreeSecurityPrefs(security_prefs); + FreeXsltParamArray(params); - if (shouldFreeSourceDoc) - xmlFreeDoc(sourceDoc); + if (should_free_source_doc) + xmlFreeDoc(source_doc); - success = saveResultToString(resultDoc, sheet, resultString); + success = SaveResultToString(result_doc, sheet, result_string); if (success) { - mimeType = resultMIMEType(resultDoc, sheet); - resultEncoding = (char*)resultDoc->encoding; + mime_type = ResultMIMEType(result_doc, sheet); + result_encoding = (char*)result_doc->encoding; } - xmlFreeDoc(resultDoc); + xmlFreeDoc(result_doc); } - sheet->method = origMethod; - setXSLTLoadCallBack(0, 0, 0); + sheet->method = orig_method; + SetXSLTLoadCallBack(0, 0, 0); xsltFreeStylesheet(sheet); - m_stylesheet = nullptr; + stylesheet_ = nullptr; return success; } diff --git a/chromium/third_party/WebKit/Source/core/xml/XSLTUnicodeSort.cpp b/chromium/third_party/WebKit/Source/core/xml/XSLTUnicodeSort.cpp index 64b4e9f1a89..42d0820285b 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XSLTUnicodeSort.cpp +++ b/chromium/third_party/WebKit/Source/core/xml/XSLTUnicodeSort.cpp @@ -28,20 +28,20 @@ #include "core/xml/XSLTUnicodeSort.h" -#include "wtf/text/Collator.h" -#include "wtf/text/WTFString.h" #include <libxslt/templates.h> #include <libxslt/xsltutils.h> +#include "platform/wtf/text/Collator.h" +#include "platform/wtf/text/WTFString.h" namespace blink { -inline const xmlChar* toXMLChar(const char* string) { +inline const xmlChar* ToXMLChar(const char* string) { return reinterpret_cast<const xmlChar*>(string); } // Based on default implementation from libxslt 1.1.22 and xsltICUSort.c // example. -void xsltUnicodeSortFunction(xsltTransformContextPtr ctxt, +void XsltUnicodeSortFunction(xsltTransformContextPtr ctxt, xmlNodePtr* sorts, int nbsorts) { #ifdef XSLT_REFACTORED @@ -49,7 +49,7 @@ void xsltUnicodeSortFunction(xsltTransformContextPtr ctxt, #else xsltStylePreCompPtr comp; #endif - xmlXPathObjectPtr* resultsTab[XSLT_MAX_SORT]; + xmlXPathObjectPtr* results_tab[XSLT_MAX_SORT]; xmlXPathObjectPtr* results = nullptr; xmlNodeSetPtr list = nullptr; int depth; @@ -73,12 +73,12 @@ void xsltUnicodeSortFunction(xsltTransformContextPtr ctxt, tempstype[j] = 0; if (!comp->stype && comp->has_stype) { comp->stype = xsltEvalAttrValueTemplate( - ctxt, sorts[j], toXMLChar("data-type"), XSLT_NAMESPACE); + ctxt, sorts[j], ToXMLChar("data-type"), XSLT_NAMESPACE); if (comp->stype) { tempstype[j] = 1; - if (xmlStrEqual(comp->stype, toXMLChar("text"))) { + if (xmlStrEqual(comp->stype, ToXMLChar("text"))) { comp->number = 0; - } else if (xmlStrEqual(comp->stype, toXMLChar("number"))) { + } else if (xmlStrEqual(comp->stype, ToXMLChar("number"))) { comp->number = 1; } else { xsltTransformError( @@ -92,12 +92,12 @@ void xsltUnicodeSortFunction(xsltTransformContextPtr ctxt, temporder[j] = 0; if (!comp->order && comp->has_order) { comp->order = xsltEvalAttrValueTemplate( - ctxt, sorts[j], toXMLChar("order"), XSLT_NAMESPACE); + ctxt, sorts[j], ToXMLChar("order"), XSLT_NAMESPACE); if (comp->order) { temporder[j] = 1; - if (xmlStrEqual(comp->order, toXMLChar("ascending"))) { + if (xmlStrEqual(comp->order, ToXMLChar("ascending"))) { comp->descending = 0; - } else if (xmlStrEqual(comp->order, toXMLChar("descending"))) { + } else if (xmlStrEqual(comp->order, ToXMLChar("descending"))) { comp->descending = 1; } else { xsltTransformError(ctxt, 0, sorts[j], @@ -111,11 +111,11 @@ void xsltUnicodeSortFunction(xsltTransformContextPtr ctxt, int len = list->nodeNr; - resultsTab[0] = xsltComputeSortResult(ctxt, sorts[0]); + results_tab[0] = xsltComputeSortResult(ctxt, sorts[0]); for (int i = 1; i < XSLT_MAX_SORT; ++i) - resultsTab[i] = 0; + results_tab[i] = 0; - results = resultsTab[0]; + results = results_tab[0]; comp = static_cast<xsltStylePreComp*>(sorts[0]->psvi); int descending = comp->descending; @@ -130,7 +130,7 @@ void xsltUnicodeSortFunction(xsltTransformContextPtr ctxt, // possible with language alone. Collator collator(comp->has_lang ? reinterpret_cast<const char*>(comp->lang) : "en"); - collator.setOrderLowerFirst(comp->lower_first); + collator.SetOrderLowerFirst(comp->lower_first); // Shell's sort of node-set. for (int incr = len / 2; incr > 0; incr /= 2) { @@ -164,14 +164,14 @@ void xsltUnicodeSortFunction(xsltTransformContextPtr ctxt, } else { Vector<UChar> string1; Vector<UChar> string2; - String::fromUTF8( + String::FromUTF8( reinterpret_cast<const char*>(results[j]->stringval)) - .appendTo(string1); - String::fromUTF8( + .AppendTo(string1); + String::FromUTF8( reinterpret_cast<const char*>(results[j + incr]->stringval)) - .appendTo(string2); - tst = collator.collate(string1.data(), string1.size(), - string2.data(), string2.size()); + .AppendTo(string2); + tst = collator.Collate(string1.Data(), string1.size(), + string2.Data(), string2.size()); } if (descending) tst = -tst; @@ -190,9 +190,9 @@ void xsltUnicodeSortFunction(xsltTransformContextPtr ctxt, // Compute the result of the next level for the full // set, this might be optimized ... or not - if (!resultsTab[depth]) - resultsTab[depth] = xsltComputeSortResult(ctxt, sorts[depth]); - xmlXPathObjectPtr* res = resultsTab[depth]; + if (!results_tab[depth]) + results_tab[depth] = xsltComputeSortResult(ctxt, sorts[depth]); + xmlXPathObjectPtr* res = results_tab[depth]; if (!res) break; if (!res[j]) { @@ -219,14 +219,14 @@ void xsltUnicodeSortFunction(xsltTransformContextPtr ctxt, } else { Vector<UChar> string1; Vector<UChar> string2; - String::fromUTF8( + String::FromUTF8( reinterpret_cast<const char*>(res[j]->stringval)) - .appendTo(string1); - String::fromUTF8( + .AppendTo(string1); + String::FromUTF8( reinterpret_cast<const char*>(res[j + incr]->stringval)) - .appendTo(string2); - tst = collator.collate(string1.data(), string1.size(), - string2.data(), string2.size()); + .AppendTo(string2); + tst = collator.Collate(string1.Data(), string1.size(), + string2.Data(), string2.size()); } if (desc) tst = -tst; @@ -253,9 +253,9 @@ void xsltUnicodeSortFunction(xsltTransformContextPtr ctxt, while (depth < nbsorts) { if (!sorts[depth]) break; - if (!resultsTab[depth]) + if (!results_tab[depth]) break; - xmlXPathObjectPtr* res = resultsTab[depth]; + xmlXPathObjectPtr* res = results_tab[depth]; tmp = res[j]; res[j] = res[j + incr]; res[j + incr] = tmp; @@ -281,10 +281,10 @@ void xsltUnicodeSortFunction(xsltTransformContextPtr ctxt, xmlFree(const_cast<xmlChar*>(comp->order)); comp->order = 0; } - if (resultsTab[j]) { + if (results_tab[j]) { for (int i = 0; i < len; ++i) - xmlXPathFreeObject(resultsTab[j][i]); - xmlFree(resultsTab[j]); + xmlXPathFreeObject(results_tab[j][i]); + xmlFree(results_tab[j]); } } } diff --git a/chromium/third_party/WebKit/Source/core/xml/XSLTUnicodeSort.h b/chromium/third_party/WebKit/Source/core/xml/XSLTUnicodeSort.h index e30bdc8427e..c308a188dcb 100644 --- a/chromium/third_party/WebKit/Source/core/xml/XSLTUnicodeSort.h +++ b/chromium/third_party/WebKit/Source/core/xml/XSLTUnicodeSort.h @@ -32,7 +32,7 @@ namespace blink { -void xsltUnicodeSortFunction(xsltTransformContextPtr ctxt, +void XsltUnicodeSortFunction(xsltTransformContextPtr ctxt, xmlNodePtr* sorts, int nbsorts); } diff --git a/chromium/third_party/WebKit/Source/core/xml/parser/SharedBufferReader.cpp b/chromium/third_party/WebKit/Source/core/xml/parser/SharedBufferReader.cpp index be713d49cc7..3835de2aa9a 100644 --- a/chromium/third_party/WebKit/Source/core/xml/parser/SharedBufferReader.cpp +++ b/chromium/third_party/WebKit/Source/core/xml/parser/SharedBufferReader.cpp @@ -31,8 +31,8 @@ #include "core/xml/parser/SharedBufferReader.h" #include "platform/SharedBuffer.h" -#include "wtf/PassRefPtr.h" -#include "wtf/RefPtr.h" +#include "platform/wtf/PassRefPtr.h" +#include "platform/wtf/RefPtr.h" #include <algorithm> #include <cstring> @@ -40,31 +40,31 @@ namespace blink { SharedBufferReader::SharedBufferReader(PassRefPtr<const SharedBuffer> buffer) - : m_buffer(buffer), m_currentOffset(0) {} + : buffer_(std::move(buffer)), current_offset_(0) {} SharedBufferReader::~SharedBufferReader() {} -int SharedBufferReader::readData(char* outputBuffer, int askedToRead) { - if (!m_buffer || m_currentOffset > m_buffer->size()) +int SharedBufferReader::ReadData(char* output_buffer, int asked_to_read) { + if (!buffer_ || current_offset_ > buffer_->size()) return 0; - size_t bytesCopied = 0; - size_t bytesLeft = m_buffer->size() - m_currentOffset; - size_t lenToCopy = std::min(safeCast<size_t>(askedToRead), bytesLeft); + size_t bytes_copied = 0; + size_t bytes_left = buffer_->size() - current_offset_; + size_t len_to_copy = std::min(SafeCast<size_t>(asked_to_read), bytes_left); - while (bytesCopied < lenToCopy) { + while (bytes_copied < len_to_copy) { const char* data; - size_t segmentSize = m_buffer->getSomeData(data, m_currentOffset); - if (!segmentSize) + size_t segment_size = buffer_->GetSomeData(data, current_offset_); + if (!segment_size) break; - segmentSize = std::min(segmentSize, lenToCopy - bytesCopied); - memcpy(outputBuffer + bytesCopied, data, segmentSize); - bytesCopied += segmentSize; - m_currentOffset += segmentSize; + segment_size = std::min(segment_size, len_to_copy - bytes_copied); + memcpy(output_buffer + bytes_copied, data, segment_size); + bytes_copied += segment_size; + current_offset_ += segment_size; } - return safeCast<int>(bytesCopied); + return SafeCast<int>(bytes_copied); } } // namespace blink diff --git a/chromium/third_party/WebKit/Source/core/xml/parser/SharedBufferReader.h b/chromium/third_party/WebKit/Source/core/xml/parser/SharedBufferReader.h index 9c6e05128a8..2e14dc7ead4 100644 --- a/chromium/third_party/WebKit/Source/core/xml/parser/SharedBufferReader.h +++ b/chromium/third_party/WebKit/Source/core/xml/parser/SharedBufferReader.h @@ -32,9 +32,9 @@ #define SharedBufferReader_h #include "core/CoreExport.h" -#include "wtf/Allocator.h" -#include "wtf/Forward.h" -#include "wtf/RefPtr.h" +#include "platform/wtf/Allocator.h" +#include "platform/wtf/Forward.h" +#include "platform/wtf/RefPtr.h" namespace blink { @@ -54,11 +54,11 @@ class CORE_EXPORT SharedBufferReader { // |outputBuffer|). // TODO(junov): use size_t instead of int. Until then, readData uses safeCast // internally. - int readData(char* outputBuffer, int askedToRead); + int ReadData(char* output_buffer, int asked_to_read); private: - RefPtr<const SharedBuffer> m_buffer; - size_t m_currentOffset; + RefPtr<const SharedBuffer> buffer_; + size_t current_offset_; }; } // namespace blink diff --git a/chromium/third_party/WebKit/Source/core/xml/parser/SharedBufferReaderTest.cpp b/chromium/third_party/WebKit/Source/core/xml/parser/SharedBufferReaderTest.cpp index 10081c91659..00b620a0c9a 100644 --- a/chromium/third_party/WebKit/Source/core/xml/parser/SharedBufferReaderTest.cpp +++ b/chromium/third_party/WebKit/Source/core/xml/parser/SharedBufferReaderTest.cpp @@ -41,77 +41,79 @@ TEST(SharedBufferReaderTest, readDataWithNullSharedBuffer) { SharedBufferReader reader(nullptr); char buffer[32]; - EXPECT_EQ(0, reader.readData(buffer, sizeof(buffer))); + EXPECT_EQ(0, reader.ReadData(buffer, sizeof(buffer))); } TEST(SharedBufferReaderTest, readDataWith0BytesRequest) { - RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(); - SharedBufferReader reader(sharedBuffer); + RefPtr<SharedBuffer> shared_buffer = SharedBuffer::Create(); + SharedBufferReader reader(shared_buffer); - EXPECT_EQ(0, reader.readData(0, 0)); + EXPECT_EQ(0, reader.ReadData(0, 0)); } TEST(SharedBufferReaderTest, readDataWithSizeBiggerThanSharedBufferSize) { - static const char testData[] = "hello"; - RefPtr<SharedBuffer> sharedBuffer = - SharedBuffer::create(testData, sizeof(testData)); + static const char kTestData[] = "hello"; + RefPtr<SharedBuffer> shared_buffer = + SharedBuffer::Create(kTestData, sizeof(kTestData)); - SharedBufferReader reader(sharedBuffer); + SharedBufferReader reader(shared_buffer); - const int extraBytes = 3; - char outputBuffer[sizeof(testData) + extraBytes]; + const int kExtraBytes = 3; + char output_buffer[sizeof(kTestData) + kExtraBytes]; - const char initializationByte = 'a'; - memset(outputBuffer, initializationByte, sizeof(outputBuffer)); - EXPECT_EQ(sizeof(testData), static_cast<size_t>(reader.readData( - outputBuffer, sizeof(outputBuffer)))); + const char kInitializationByte = 'a'; + memset(output_buffer, kInitializationByte, sizeof(output_buffer)); + EXPECT_EQ(sizeof(kTestData), static_cast<size_t>(reader.ReadData( + output_buffer, sizeof(output_buffer)))); - EXPECT_TRUE(std::equal(testData, testData + sizeof(testData), outputBuffer)); + EXPECT_TRUE( + std::equal(kTestData, kTestData + sizeof(kTestData), output_buffer)); // Check that the bytes past index sizeof(testData) were not touched. - EXPECT_EQ(extraBytes, - std::count(outputBuffer, outputBuffer + sizeof(outputBuffer), - initializationByte)); + EXPECT_EQ(kExtraBytes, + std::count(output_buffer, output_buffer + sizeof(output_buffer), + kInitializationByte)); } TEST(SharedBufferReaderTest, readDataInMultiples) { - const int iterationsCount = 8; - const int bytesPerIteration = 64; + const int kIterationsCount = 8; + const int kBytesPerIteration = 64; - Vector<char> testData(iterationsCount * bytesPerIteration); - std::generate(testData.begin(), testData.end(), &std::rand); + Vector<char> test_data(kIterationsCount * kBytesPerIteration); + std::generate(test_data.begin(), test_data.end(), &std::rand); - RefPtr<SharedBuffer> sharedBuffer = - SharedBuffer::create(&testData[0], testData.size()); - SharedBufferReader reader(sharedBuffer); + RefPtr<SharedBuffer> shared_buffer = + SharedBuffer::Create(&test_data[0], test_data.size()); + SharedBufferReader reader(shared_buffer); - Vector<char> destinationVector(testData.size()); + Vector<char> destination_vector(test_data.size()); - for (int i = 0; i < iterationsCount; ++i) { - const int offset = i * bytesPerIteration; - const int bytesRead = - reader.readData(&destinationVector[0] + offset, bytesPerIteration); - EXPECT_EQ(bytesPerIteration, bytesRead); + for (int i = 0; i < kIterationsCount; ++i) { + const int offset = i * kBytesPerIteration; + const int bytes_read = + reader.ReadData(&destination_vector[0] + offset, kBytesPerIteration); + EXPECT_EQ(kBytesPerIteration, bytes_read); } - EXPECT_TRUE( - std::equal(testData.begin(), testData.end(), destinationVector.begin())); + EXPECT_TRUE(std::equal(test_data.begin(), test_data.end(), + destination_vector.begin())); } TEST(SharedBufferReaderTest, clearSharedBufferBetweenCallsToReadData) { - Vector<char> testData(128); - std::generate(testData.begin(), testData.end(), &std::rand); + Vector<char> test_data(128); + std::generate(test_data.begin(), test_data.end(), &std::rand); - RefPtr<SharedBuffer> sharedBuffer = - SharedBuffer::create(&testData[0], testData.size()); - SharedBufferReader reader(sharedBuffer); + RefPtr<SharedBuffer> shared_buffer = + SharedBuffer::Create(&test_data[0], test_data.size()); + SharedBufferReader reader(shared_buffer); - Vector<char> destinationVector(testData.size()); - const int bytesToRead = testData.size() / 2; - EXPECT_EQ(bytesToRead, reader.readData(&destinationVector[0], bytesToRead)); + Vector<char> destination_vector(test_data.size()); + const int bytes_to_read = test_data.size() / 2; + EXPECT_EQ(bytes_to_read, + reader.ReadData(&destination_vector[0], bytes_to_read)); - sharedBuffer->clear(); + shared_buffer->Clear(); - EXPECT_EQ(0, reader.readData(&destinationVector[0], bytesToRead)); + EXPECT_EQ(0, reader.ReadData(&destination_vector[0], bytes_to_read)); } } // namespace blink diff --git a/chromium/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp b/chromium/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp index 800abaeba2f..8b033386247 100644 --- a/chromium/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp +++ b/chromium/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp @@ -26,12 +26,17 @@ #include "core/xml/parser/XMLDocumentParser.h" +#include <libxml/parser.h> +#include <libxml/parserInternals.h> +#include <libxslt/xslt.h> +#include <memory> #include "bindings/core/v8/ExceptionState.h" #include "bindings/core/v8/ScriptController.h" #include "bindings/core/v8/ScriptSourceCode.h" #include "core/HTMLNames.h" #include "core/XMLNSNames.h" #include "core/dom/CDATASection.h" +#include "core/dom/ClassicScript.h" #include "core/dom/Comment.h" #include "core/dom/Document.h" #include "core/dom/DocumentFragment.h" @@ -61,59 +66,54 @@ #include "platform/instrumentation/tracing/TraceEvent.h" #include "platform/loader/fetch/FetchInitiatorTypeNames.h" #include "platform/loader/fetch/RawResource.h" +#include "platform/loader/fetch/ResourceError.h" #include "platform/loader/fetch/ResourceFetcher.h" -#include "platform/network/ResourceError.h" -#include "platform/network/ResourceRequest.h" -#include "platform/network/ResourceResponse.h" +#include "platform/loader/fetch/ResourceRequest.h" +#include "platform/loader/fetch/ResourceResponse.h" #include "platform/weborigin/SecurityOrigin.h" -#include "wtf/AutoReset.h" -#include "wtf/PtrUtil.h" -#include "wtf/StringExtras.h" -#include "wtf/Threading.h" -#include "wtf/Vector.h" -#include "wtf/text/UTF8.h" -#include <libxml/catalog.h> -#include <libxml/parser.h> -#include <libxml/parserInternals.h> -#include <libxslt/xslt.h> -#include <memory> +#include "platform/wtf/AutoReset.h" +#include "platform/wtf/PtrUtil.h" +#include "platform/wtf/StringExtras.h" +#include "platform/wtf/Threading.h" +#include "platform/wtf/Vector.h" +#include "platform/wtf/text/UTF8.h" namespace blink { using namespace HTMLNames; // FIXME: HTMLConstructionSite has a limit of 512, should these match? -static const unsigned maxXMLTreeDepth = 5000; +static const unsigned kMaxXMLTreeDepth = 5000; -static inline String toString(const xmlChar* string, size_t length) { - return String::fromUTF8(reinterpret_cast<const char*>(string), length); +static inline String ToString(const xmlChar* string, size_t length) { + return String::FromUTF8(reinterpret_cast<const char*>(string), length); } -static inline String toString(const xmlChar* string) { - return String::fromUTF8(reinterpret_cast<const char*>(string)); +static inline String ToString(const xmlChar* string) { + return String::FromUTF8(reinterpret_cast<const char*>(string)); } -static inline AtomicString toAtomicString(const xmlChar* string, +static inline AtomicString ToAtomicString(const xmlChar* string, size_t length) { - return AtomicString::fromUTF8(reinterpret_cast<const char*>(string), length); + return AtomicString::FromUTF8(reinterpret_cast<const char*>(string), length); } -static inline AtomicString toAtomicString(const xmlChar* string) { - return AtomicString::fromUTF8(reinterpret_cast<const char*>(string)); +static inline AtomicString ToAtomicString(const xmlChar* string) { + return AtomicString::FromUTF8(reinterpret_cast<const char*>(string)); } -static inline bool hasNoStyleInformation(Document* document) { - if (document->sawElementsInKnownNamespaces() || - DocumentXSLT::hasTransformSourceDocument(*document)) +static inline bool HasNoStyleInformation(Document* document) { + if (document->SawElementsInKnownNamespaces() || + DocumentXSLT::HasTransformSourceDocument(*document)) return false; - if (!document->frame() || !document->frame()->page()) + if (!document->GetFrame() || !document->GetFrame()->GetPage()) return false; - if (document->frame()->tree().parent()) + if (document->GetFrame()->Tree().Parent()) return false; // This document is not in a top frame - if (SVGImage::isInSVGImage(document)) + if (SVGImage::IsInSVGImage(document)) return false; return true; @@ -122,200 +122,200 @@ static inline bool hasNoStyleInformation(Document* document) { class PendingStartElementNSCallback final : public XMLDocumentParser::PendingCallback { public: - PendingStartElementNSCallback(const AtomicString& localName, + PendingStartElementNSCallback(const AtomicString& local_name, const AtomicString& prefix, const AtomicString& uri, - int namespaceCount, + int namespace_count, const xmlChar** namespaces, - int attributeCount, - int defaultedCount, + int attribute_count, + int defaulted_count, const xmlChar** attributes) - : m_localName(localName), - m_prefix(prefix), - m_uri(uri), - m_namespaceCount(namespaceCount), - m_attributeCount(attributeCount), - m_defaultedCount(defaultedCount) { - m_namespaces = static_cast<xmlChar**>( - xmlMalloc(sizeof(xmlChar*) * namespaceCount * 2)); - for (int i = 0; i < namespaceCount * 2; ++i) - m_namespaces[i] = xmlStrdup(namespaces[i]); - m_attributes = static_cast<xmlChar**>( - xmlMalloc(sizeof(xmlChar*) * attributeCount * 5)); - for (int i = 0; i < attributeCount; ++i) { + : local_name_(local_name), + prefix_(prefix), + uri_(uri), + namespace_count_(namespace_count), + attribute_count_(attribute_count), + defaulted_count_(defaulted_count) { + namespaces_ = static_cast<xmlChar**>( + xmlMalloc(sizeof(xmlChar*) * namespace_count * 2)); + for (int i = 0; i < namespace_count * 2; ++i) + namespaces_[i] = xmlStrdup(namespaces[i]); + attributes_ = static_cast<xmlChar**>( + xmlMalloc(sizeof(xmlChar*) * attribute_count * 5)); + for (int i = 0; i < attribute_count; ++i) { // Each attribute has 5 elements in the array: // name, prefix, uri, value and an end pointer. for (int j = 0; j < 3; ++j) - m_attributes[i * 5 + j] = xmlStrdup(attributes[i * 5 + j]); + attributes_[i * 5 + j] = xmlStrdup(attributes[i * 5 + j]); int length = attributes[i * 5 + 4] - attributes[i * 5 + 3]; - m_attributes[i * 5 + 3] = xmlStrndup(attributes[i * 5 + 3], length); - m_attributes[i * 5 + 4] = m_attributes[i * 5 + 3] + length; + attributes_[i * 5 + 3] = xmlStrndup(attributes[i * 5 + 3], length); + attributes_[i * 5 + 4] = attributes_[i * 5 + 3] + length; } } ~PendingStartElementNSCallback() override { - for (int i = 0; i < m_namespaceCount * 2; ++i) - xmlFree(m_namespaces[i]); - xmlFree(m_namespaces); - for (int i = 0; i < m_attributeCount; ++i) + for (int i = 0; i < namespace_count_ * 2; ++i) + xmlFree(namespaces_[i]); + xmlFree(namespaces_); + for (int i = 0; i < attribute_count_; ++i) for (int j = 0; j < 4; ++j) - xmlFree(m_attributes[i * 5 + j]); - xmlFree(m_attributes); + xmlFree(attributes_[i * 5 + j]); + xmlFree(attributes_); } - void call(XMLDocumentParser* parser) override { - parser->startElementNs(m_localName, m_prefix, m_uri, m_namespaceCount, - const_cast<const xmlChar**>(m_namespaces), - m_attributeCount, m_defaultedCount, - const_cast<const xmlChar**>(m_attributes)); + void Call(XMLDocumentParser* parser) override { + parser->StartElementNs(local_name_, prefix_, uri_, namespace_count_, + const_cast<const xmlChar**>(namespaces_), + attribute_count_, defaulted_count_, + const_cast<const xmlChar**>(attributes_)); } private: - AtomicString m_localName; - AtomicString m_prefix; - AtomicString m_uri; - int m_namespaceCount; - xmlChar** m_namespaces; - int m_attributeCount; - int m_defaultedCount; - xmlChar** m_attributes; + AtomicString local_name_; + AtomicString prefix_; + AtomicString uri_; + int namespace_count_; + xmlChar** namespaces_; + int attribute_count_; + int defaulted_count_; + xmlChar** attributes_; }; class PendingEndElementNSCallback final : public XMLDocumentParser::PendingCallback { public: - explicit PendingEndElementNSCallback(TextPosition scriptStartPosition) - : m_scriptStartPosition(scriptStartPosition) {} + explicit PendingEndElementNSCallback(TextPosition script_start_position) + : script_start_position_(script_start_position) {} - void call(XMLDocumentParser* parser) override { - parser->setScriptStartPosition(m_scriptStartPosition); - parser->endElementNs(); + void Call(XMLDocumentParser* parser) override { + parser->SetScriptStartPosition(script_start_position_); + parser->EndElementNs(); } private: - TextPosition m_scriptStartPosition; + TextPosition script_start_position_; }; class PendingCharactersCallback final : public XMLDocumentParser::PendingCallback { public: PendingCharactersCallback(const xmlChar* chars, int length) - : m_chars(xmlStrndup(chars, length)), m_length(length) {} + : chars_(xmlStrndup(chars, length)), length_(length) {} - ~PendingCharactersCallback() override { xmlFree(m_chars); } + ~PendingCharactersCallback() override { xmlFree(chars_); } - void call(XMLDocumentParser* parser) override { - parser->characters(m_chars, m_length); + void Call(XMLDocumentParser* parser) override { + parser->Characters(chars_, length_); } private: - xmlChar* m_chars; - int m_length; + xmlChar* chars_; + int length_; }; class PendingProcessingInstructionCallback final : public XMLDocumentParser::PendingCallback { public: PendingProcessingInstructionCallback(const String& target, const String& data) - : m_target(target), m_data(data) {} + : target_(target), data_(data) {} - void call(XMLDocumentParser* parser) override { - parser->processingInstruction(m_target, m_data); + void Call(XMLDocumentParser* parser) override { + parser->GetProcessingInstruction(target_, data_); } private: - String m_target; - String m_data; + String target_; + String data_; }; class PendingCDATABlockCallback final : public XMLDocumentParser::PendingCallback { public: - explicit PendingCDATABlockCallback(const String& text) : m_text(text) {} + explicit PendingCDATABlockCallback(const String& text) : text_(text) {} - void call(XMLDocumentParser* parser) override { parser->cdataBlock(m_text); } + void Call(XMLDocumentParser* parser) override { parser->CdataBlock(text_); } private: - String m_text; + String text_; }; class PendingCommentCallback final : public XMLDocumentParser::PendingCallback { public: - explicit PendingCommentCallback(const String& text) : m_text(text) {} + explicit PendingCommentCallback(const String& text) : text_(text) {} - void call(XMLDocumentParser* parser) override { parser->comment(m_text); } + void Call(XMLDocumentParser* parser) override { parser->Comment(text_); } private: - String m_text; + String text_; }; class PendingInternalSubsetCallback final : public XMLDocumentParser::PendingCallback { public: PendingInternalSubsetCallback(const String& name, - const String& externalID, - const String& systemID) - : m_name(name), m_externalID(externalID), m_systemID(systemID) {} + const String& external_id, + const String& system_id) + : name_(name), external_id_(external_id), system_id_(system_id) {} - void call(XMLDocumentParser* parser) override { - parser->internalSubset(m_name, m_externalID, m_systemID); + void Call(XMLDocumentParser* parser) override { + parser->InternalSubset(name_, external_id_, system_id_); } private: - String m_name; - String m_externalID; - String m_systemID; + String name_; + String external_id_; + String system_id_; }; class PendingErrorCallback final : public XMLDocumentParser::PendingCallback { public: PendingErrorCallback(XMLErrors::ErrorType type, const xmlChar* message, - OrdinalNumber lineNumber, - OrdinalNumber columnNumber) - : m_type(type), - m_message(xmlStrdup(message)), - m_lineNumber(lineNumber), - m_columnNumber(columnNumber) {} - - ~PendingErrorCallback() override { xmlFree(m_message); } - - void call(XMLDocumentParser* parser) override { - parser->handleError(m_type, reinterpret_cast<char*>(m_message), - TextPosition(m_lineNumber, m_columnNumber)); + OrdinalNumber line_number, + OrdinalNumber column_number) + : type_(type), + message_(xmlStrdup(message)), + line_number_(line_number), + column_number_(column_number) {} + + ~PendingErrorCallback() override { xmlFree(message_); } + + void Call(XMLDocumentParser* parser) override { + parser->HandleError(type_, reinterpret_cast<char*>(message_), + TextPosition(line_number_, column_number_)); } private: - XMLErrors::ErrorType m_type; - xmlChar* m_message; - OrdinalNumber m_lineNumber; - OrdinalNumber m_columnNumber; + XMLErrors::ErrorType type_; + xmlChar* message_; + OrdinalNumber line_number_; + OrdinalNumber column_number_; }; -void XMLDocumentParser::pushCurrentNode(ContainerNode* n) { +void XMLDocumentParser::PushCurrentNode(ContainerNode* n) { DCHECK(n); - DCHECK(m_currentNode); - m_currentNodeStack.push_back(m_currentNode); - m_currentNode = n; - if (m_currentNodeStack.size() > maxXMLTreeDepth) - handleError(XMLErrors::ErrorTypeFatal, "Excessive node nesting.", - textPosition()); + DCHECK(current_node_); + current_node_stack_.push_back(current_node_); + current_node_ = n; + if (current_node_stack_.size() > kMaxXMLTreeDepth) + HandleError(XMLErrors::kErrorTypeFatal, "Excessive node nesting.", + GetTextPosition()); } -void XMLDocumentParser::popCurrentNode() { - if (!m_currentNode) +void XMLDocumentParser::PopCurrentNode() { + if (!current_node_) return; - DCHECK(m_currentNodeStack.size()); - m_currentNode = m_currentNodeStack.back(); - m_currentNodeStack.pop_back(); + DCHECK(current_node_stack_.size()); + current_node_ = current_node_stack_.back(); + current_node_stack_.pop_back(); } -void XMLDocumentParser::clearCurrentNodeStack() { - m_currentNode = nullptr; - m_leafTextNode = nullptr; +void XMLDocumentParser::ClearCurrentNodeStack() { + current_node_ = nullptr; + leaf_text_node_ = nullptr; - if (m_currentNodeStack.size()) { // Aborted parsing. - m_currentNodeStack.clear(); + if (current_node_stack_.size()) { // Aborted parsing. + current_node_stack_.Clear(); } } @@ -323,65 +323,65 @@ void XMLDocumentParser::insert(const SegmentedString&) { NOTREACHED(); } -void XMLDocumentParser::append(const String& inputSource) { - const SegmentedString source(inputSource); - if (m_sawXSLTransform || !m_sawFirstElement) - m_originalSourceForTransform.append(source); +void XMLDocumentParser::Append(const String& input_source) { + const SegmentedString source(input_source); + if (saw_xsl_transform_ || !saw_first_element_) + original_source_for_transform_.Append(source); - if (isStopped() || m_sawXSLTransform) + if (IsStopped() || saw_xsl_transform_) return; - if (m_parserPaused) { - m_pendingSrc.append(source); + if (parser_paused_) { + pending_src_.Append(source); return; } - doWrite(source.toString()); + DoWrite(source.ToString()); } -void XMLDocumentParser::handleError(XMLErrors::ErrorType type, - const char* formattedMessage, +void XMLDocumentParser::HandleError(XMLErrors::ErrorType type, + const char* formatted_message, TextPosition position) { - m_xmlErrors.handleError(type, formattedMessage, position); - if (type != XMLErrors::ErrorTypeWarning) - m_sawError = true; - if (type == XMLErrors::ErrorTypeFatal) - stopParsing(); + xml_errors_.HandleError(type, formatted_message, position); + if (type != XMLErrors::kErrorTypeWarning) + saw_error_ = true; + if (type == XMLErrors::kErrorTypeFatal) + StopParsing(); } -void XMLDocumentParser::createLeafTextNodeIfNeeded() { - if (m_leafTextNode) +void XMLDocumentParser::CreateLeafTextNodeIfNeeded() { + if (leaf_text_node_) return; - DCHECK_EQ(m_bufferedText.size(), 0u); - m_leafTextNode = Text::create(m_currentNode->document(), ""); - m_currentNode->parserAppendChild(m_leafTextNode.get()); + DCHECK_EQ(buffered_text_.size(), 0u); + leaf_text_node_ = Text::Create(current_node_->GetDocument(), ""); + current_node_->ParserAppendChild(leaf_text_node_.Get()); } -bool XMLDocumentParser::updateLeafTextNode() { - if (isStopped()) +bool XMLDocumentParser::UpdateLeafTextNode() { + if (IsStopped()) return false; - if (!m_leafTextNode) + if (!leaf_text_node_) return true; - m_leafTextNode->appendData( - toString(m_bufferedText.data(), m_bufferedText.size())); - m_bufferedText.clear(); - m_leafTextNode = nullptr; + leaf_text_node_->appendData( + ToString(buffered_text_.Data(), buffered_text_.size())); + buffered_text_.Clear(); + leaf_text_node_ = nullptr; // Mutation event handlers executed by appendData() might detach this parser. - return !isStopped(); + return !IsStopped(); } -void XMLDocumentParser::detach() { - if (m_pendingScript) { - m_pendingScript->removeClient(this); - m_pendingScript = nullptr; - m_parserBlockingPendingScriptLoadStartTime = 0.0; +void XMLDocumentParser::Detach() { + if (pending_script_) { + pending_script_->RemoveClient(this); + pending_script_ = nullptr; + parser_blocking_pending_script_load_start_time_ = 0.0; } - clearCurrentNodeStack(); - ScriptableDocumentParser::detach(); + ClearCurrentNodeStack(); + ScriptableDocumentParser::Detach(); } void XMLDocumentParser::end() { @@ -389,149 +389,152 @@ void XMLDocumentParser::end() { // XMLDocumentParserLibxml2 will do bad things to the document if doEnd() is // called. I don't believe XMLDocumentParserQt needs doEnd called in the // fragment case. - DCHECK(!m_parsingFragment); + DCHECK(!parsing_fragment_); - doEnd(); + DoEnd(); // doEnd() call above can detach the parser and null out its document. // In that case, we just bail out. - if (isDetached()) + if (IsDetached()) return; // doEnd() could process a script tag, thus pausing parsing. - if (m_parserPaused) + if (parser_paused_) return; - if (m_sawError) - insertErrorMessageBlock(); + if (saw_error_) + InsertErrorMessageBlock(); else - updateLeafTextNode(); + UpdateLeafTextNode(); - if (isParsing()) - prepareToStopParsing(); - document()->setReadyState(Document::Interactive); - clearCurrentNodeStack(); - document()->finishedParsing(); + if (IsParsing()) + PrepareToStopParsing(); + GetDocument()->SetReadyState(Document::kInteractive); + ClearCurrentNodeStack(); + GetDocument()->FinishedParsing(); } -void XMLDocumentParser::finish() { +void XMLDocumentParser::Finish() { // FIXME: We should DCHECK(!m_parserStopped) here, since it does not // makes sense to call any methods on DocumentParser once it's been stopped. // However, FrameLoader::stop calls DocumentParser::finish unconditionally. - flush(); - if (isDetached()) + Flush(); + if (IsDetached()) return; - if (m_parserPaused) - m_finishCalled = true; + if (parser_paused_) + finish_called_ = true; else end(); } -void XMLDocumentParser::insertErrorMessageBlock() { - m_xmlErrors.insertErrorMessageBlock(); +void XMLDocumentParser::InsertErrorMessageBlock() { + xml_errors_.InsertErrorMessageBlock(); } -void XMLDocumentParser::notifyFinished(Resource* unusedResource) { - DCHECK_EQ(unusedResource, m_pendingScript); +void XMLDocumentParser::NotifyFinished(Resource* unused_resource) { + DCHECK_EQ(unused_resource, pending_script_); - ScriptSourceCode sourceCode(m_pendingScript.get()); - bool errorOccurred = m_pendingScript->errorOccurred(); - bool wasCanceled = m_pendingScript->wasCanceled(); - double scriptParserBlockingTime = m_parserBlockingPendingScriptLoadStartTime; - m_parserBlockingPendingScriptLoadStartTime = 0.0; + ScriptSourceCode source_code(pending_script_.Get()); + bool error_occurred = pending_script_->ErrorOccurred(); + bool was_canceled = pending_script_->WasCanceled(); + double script_parser_blocking_time = + parser_blocking_pending_script_load_start_time_; + parser_blocking_pending_script_load_start_time_ = 0.0; - m_pendingScript->removeClient(this); - m_pendingScript = nullptr; + pending_script_->RemoveClient(this); + pending_script_ = nullptr; - Element* e = m_scriptElement; - m_scriptElement = nullptr; + Element* e = script_element_; + script_element_ = nullptr; - ScriptLoader* scriptLoader = toScriptLoaderIfPossible(e); - DCHECK(scriptLoader); + ScriptLoader* script_loader = + ScriptElementBase::FromElementIfPossible(e)->Loader(); + DCHECK(script_loader); - if (errorOccurred) { - scriptLoader->dispatchErrorEvent(); - } else if (!wasCanceled) { - if (scriptParserBlockingTime > 0.0) { - DocumentParserTiming::from(*document()) - .recordParserBlockedOnScriptLoadDuration( - monotonicallyIncreasingTime() - scriptParserBlockingTime, - scriptLoader->wasCreatedDuringDocumentWrite()); + if (error_occurred) { + script_loader->DispatchErrorEvent(); + } else if (!was_canceled) { + if (script_parser_blocking_time > 0.0) { + DocumentParserTiming::From(*GetDocument()) + .RecordParserBlockedOnScriptLoadDuration( + MonotonicallyIncreasingTime() - script_parser_blocking_time, + script_loader->WasCreatedDuringDocumentWrite()); } - if (!scriptLoader->executeScript(sourceCode)) - scriptLoader->dispatchErrorEvent(); + if (!script_loader->ExecuteScript(ClassicScript::Create(source_code))) + script_loader->DispatchErrorEvent(); else - scriptLoader->dispatchLoadEvent(); + script_loader->DispatchLoadEvent(); } - m_scriptElement = nullptr; + script_element_ = nullptr; - if (!isDetached() && !m_requestingScript) - resumeParsing(); + if (!IsDetached() && !requesting_script_) + ResumeParsing(); } -bool XMLDocumentParser::isWaitingForScripts() const { - return m_pendingScript; +bool XMLDocumentParser::IsWaitingForScripts() const { + return pending_script_; } -void XMLDocumentParser::pauseParsing() { - if (!m_parsingFragment) - m_parserPaused = true; +void XMLDocumentParser::PauseParsing() { + if (!parsing_fragment_) + parser_paused_ = true; } -bool XMLDocumentParser::parseDocumentFragment( +bool XMLDocumentParser::ParseDocumentFragment( const String& chunk, DocumentFragment* fragment, - Element* contextElement, - ParserContentPolicy parserContentPolicy) { + Element* context_element, + ParserContentPolicy parser_content_policy) { if (!chunk.length()) return true; // FIXME: We need to implement the HTML5 XML Fragment parsing algorithm: // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-xhtml-syntax.html#xml-fragment-parsing-algorithm // For now we have a hack for script/style innerHTML support: - if (contextElement && (contextElement->hasLocalName(scriptTag.localName()) || - contextElement->hasLocalName(styleTag.localName()))) { - fragment->parserAppendChild(fragment->document().createTextNode(chunk)); + if (context_element && + (context_element->HasLocalName(scriptTag.LocalName()) || + context_element->HasLocalName(styleTag.LocalName()))) { + fragment->ParserAppendChild(fragment->GetDocument().createTextNode(chunk)); return true; } - XMLDocumentParser* parser = - XMLDocumentParser::create(fragment, contextElement, parserContentPolicy); - bool wellFormed = parser->appendFragmentSource(chunk); + XMLDocumentParser* parser = XMLDocumentParser::Create( + fragment, context_element, parser_content_policy); + bool well_formed = parser->AppendFragmentSource(chunk); // Do not call finish(). Current finish() and doEnd() implementations touch // the main Document/loader and can cause crashes in the fragment case. // Allows ~DocumentParser to assert it was detached before destruction. - parser->detach(); + parser->Detach(); // appendFragmentSource()'s wellFormed is more permissive than wellFormed(). - return wellFormed; + return well_formed; } -static int globalDescriptor = 0; -static ThreadIdentifier libxmlLoaderThread = 0; +static int g_global_descriptor = 0; +static ThreadIdentifier g_libxml_loader_thread = 0; -static int matchFunc(const char*) { +static int MatchFunc(const char*) { // Only match loads initiated due to uses of libxml2 from within // XMLDocumentParser to avoid interfering with client applications that also // use libxml2. http://bugs.webkit.org/show_bug.cgi?id=17353 - return XMLDocumentParserScope::currentDocument && - currentThread() == libxmlLoaderThread; + return XMLDocumentParserScope::current_document_ && + CurrentThread() == g_libxml_loader_thread; } -static inline void setAttributes(Element* element, - Vector<Attribute>& attributeVector, - ParserContentPolicy parserContentPolicy) { - if (!scriptingContentIsAllowed(parserContentPolicy)) - element->stripScriptingAttributes(attributeVector); - element->parserSetAttributes(attributeVector); +static inline void SetAttributes(Element* element, + Vector<Attribute>& attribute_vector, + ParserContentPolicy parser_content_policy) { + if (!ScriptingContentIsAllowed(parser_content_policy)) + element->StripScriptingAttributes(attribute_vector); + element->ParserSetAttributes(attribute_vector); } -static void switchEncoding(xmlParserCtxtPtr ctxt, bool is8Bit) { +static void SwitchEncoding(xmlParserCtxtPtr ctxt, bool is8_bit) { // Make sure we don't call xmlSwitchEncoding in an error state. if ((ctxt->errNo != XML_ERR_OK) && (ctxt->disableSAX == 1)) return; @@ -540,66 +543,66 @@ static void switchEncoding(xmlParserCtxtPtr ctxt, bool is8Bit) { // resetting the encoding to UTF-16 before every chunk. Otherwise libxml // will detect <?xml version="1.0" encoding="<encoding name>"?> blocks and // switch encodings, causing the parse to fail. - if (is8Bit) { + if (is8_bit) { xmlSwitchEncoding(ctxt, XML_CHAR_ENCODING_8859_1); return; } - const UChar BOM = 0xFEFF; - const unsigned char BOMHighByte = - *reinterpret_cast<const unsigned char*>(&BOM); - xmlSwitchEncoding(ctxt, BOMHighByte == 0xFF ? XML_CHAR_ENCODING_UTF16LE - : XML_CHAR_ENCODING_UTF16BE); + const UChar kBOM = 0xFEFF; + const unsigned char bom_high_byte = + *reinterpret_cast<const unsigned char*>(&kBOM); + xmlSwitchEncoding(ctxt, bom_high_byte == 0xFF ? XML_CHAR_ENCODING_UTF16LE + : XML_CHAR_ENCODING_UTF16BE); } -static void parseChunk(xmlParserCtxtPtr ctxt, const String& chunk) { - bool is8Bit = chunk.is8Bit(); - switchEncoding(ctxt, is8Bit); - if (is8Bit) - xmlParseChunk(ctxt, reinterpret_cast<const char*>(chunk.characters8()), +static void ParseChunk(xmlParserCtxtPtr ctxt, const String& chunk) { + bool is8_bit = chunk.Is8Bit(); + SwitchEncoding(ctxt, is8_bit); + if (is8_bit) + xmlParseChunk(ctxt, reinterpret_cast<const char*>(chunk.Characters8()), sizeof(LChar) * chunk.length(), 0); else - xmlParseChunk(ctxt, reinterpret_cast<const char*>(chunk.characters16()), + xmlParseChunk(ctxt, reinterpret_cast<const char*>(chunk.Characters16()), sizeof(UChar) * chunk.length(), 0); } -static void finishParsing(xmlParserCtxtPtr ctxt) { +static void FinishParsing(xmlParserCtxtPtr ctxt) { xmlParseChunk(ctxt, 0, 0, 1); } #define xmlParseChunk \ #error "Use parseChunk instead to select the correct encoding." -static bool isLibxmlDefaultCatalogFile(const String& urlString) { - // On non-Windows platforms libxml asks for this URL, the - // "XML_XML_DEFAULT_CATALOG", on initialization. - if (urlString == "file:///etc/xml/catalog") +static bool IsLibxmlDefaultCatalogFile(const String& url_string) { + // On non-Windows platforms libxml with catalogs enabled asks for + // this URL, the "XML_XML_DEFAULT_CATALOG", on initialization. + if (url_string == "file:///etc/xml/catalog") return true; - // On Windows, libxml computes a URL relative to where its DLL resides. - if (urlString.startsWith("file:///", TextCaseASCIIInsensitive) && - urlString.endsWith("/etc/catalog", TextCaseASCIIInsensitive)) + // On Windows, libxml with catalogs enabled computes a URL relative + // to where its DLL resides. + if (url_string.StartsWith("file:///", kTextCaseASCIIInsensitive) && + url_string.EndsWith("/etc/catalog", kTextCaseASCIIInsensitive)) return true; return false; } -static bool shouldAllowExternalLoad(const KURL& url) { - String urlString = url.getString(); +static bool ShouldAllowExternalLoad(const KURL& url) { + String url_string = url.GetString(); - // This isn't really necessary now that initializeLibXMLIfNecessary - // disables catalog support in libxml, but keeping it for defense in depth. - if (isLibxmlDefaultCatalogFile(url)) - return false; + // libxml should not be configured with catalogs enabled, so it + // should not be asking to load default catalogs. + CHECK(!IsLibxmlDefaultCatalogFile(url)); // The most common DTD. There isn't much point in hammering www.w3c.org by // requesting this URL for every XHTML document. - if (urlString.startsWith("http://www.w3.org/TR/xhtml", - TextCaseASCIIInsensitive)) + if (url_string.StartsWith("http://www.w3.org/TR/xhtml", + kTextCaseASCIIInsensitive)) return false; // Similarly, there isn't much point in requesting the SVG DTD. - if (urlString.startsWith("http://www.w3.org/Graphics/SVG", - TextCaseASCIIInsensitive)) + if (url_string.StartsWith("http://www.w3.org/Graphics/SVG", + kTextCaseASCIIInsensitive)) return false; // The libxml doesn't give us a lot of context for deciding whether to allow @@ -608,18 +611,18 @@ static bool shouldAllowExternalLoad(const KURL& url) { // content. If we had more context, we could potentially allow the parser to // load a DTD. As things stand, we take the conservative route and allow // same-origin requests only. - if (!XMLDocumentParserScope::currentDocument->getSecurityOrigin()->canRequest( - url)) { + if (!XMLDocumentParserScope::current_document_->GetSecurityOrigin() + ->CanRequest(url)) { // FIXME: This is copy/pasted. We should probably build console logging into // canRequest(). - if (!url.isNull()) { + if (!url.IsNull()) { String message = - "Unsafe attempt to load URL " + url.elidedString() + + "Unsafe attempt to load URL " + url.ElidedString() + " from frame with URL " + - XMLDocumentParserScope::currentDocument->url().elidedString() + + XMLDocumentParserScope::current_document_->Url().ElidedString() + ". Domains, protocols and ports must match.\n"; - XMLDocumentParserScope::currentDocument->addConsoleMessage( - ConsoleMessage::create(SecurityMessageSource, ErrorMessageLevel, + XMLDocumentParserScope::current_document_->AddConsoleMessage( + ConsoleMessage::Create(kSecurityMessageSource, kErrorMessageLevel, message)); } return false; @@ -628,106 +631,102 @@ static bool shouldAllowExternalLoad(const KURL& url) { return true; } -static void* openFunc(const char* uri) { - DCHECK(XMLDocumentParserScope::currentDocument); - DCHECK_EQ(currentThread(), libxmlLoaderThread); +static void* OpenFunc(const char* uri) { + DCHECK(XMLDocumentParserScope::current_document_); + DCHECK_EQ(CurrentThread(), g_libxml_loader_thread); KURL url(KURL(), uri); - if (!shouldAllowExternalLoad(url)) - return &globalDescriptor; + if (!ShouldAllowExternalLoad(url)) + return &g_global_descriptor; - KURL finalURL; + KURL final_url; RefPtr<const SharedBuffer> data; { - Document* document = XMLDocumentParserScope::currentDocument; + Document* document = XMLDocumentParserScope::current_document_; XMLDocumentParserScope scope(0); // FIXME: We should restore the original global error handler as well. - FetchRequest request(ResourceRequest(url), FetchInitiatorTypeNames::xml, - ResourceFetcher::defaultResourceOptions()); + FetchParameters params(ResourceRequest(url), FetchInitiatorTypeNames::xml, + ResourceFetcher::DefaultResourceOptions()); Resource* resource = - RawResource::fetchSynchronously(request, document->fetcher()); - if (resource && !resource->errorOccurred()) { - data = resource->resourceBuffer(); - finalURL = resource->response().url(); + RawResource::FetchSynchronously(params, document->Fetcher()); + if (resource && !resource->ErrorOccurred()) { + data = resource->ResourceBuffer(); + final_url = resource->GetResponse().Url(); } } // We have to check the URL again after the load to catch redirects. // See <https://bugs.webkit.org/show_bug.cgi?id=21963>. - if (!shouldAllowExternalLoad(finalURL)) - return &globalDescriptor; + if (!ShouldAllowExternalLoad(final_url)) + return &g_global_descriptor; - UseCounter::count(XMLDocumentParserScope::currentDocument, - UseCounter::XMLExternalResourceLoad); + UseCounter::Count(XMLDocumentParserScope::current_document_, + UseCounter::kXMLExternalResourceLoad); return new SharedBufferReader(data); } -static int readFunc(void* context, char* buffer, int len) { +static int ReadFunc(void* context, char* buffer, int len) { // Do 0-byte reads in case of a null descriptor - if (context == &globalDescriptor) + if (context == &g_global_descriptor) return 0; SharedBufferReader* data = static_cast<SharedBufferReader*>(context); - return data->readData(buffer, len); + return data->ReadData(buffer, len); } -static int writeFunc(void*, const char*, int) { +static int WriteFunc(void*, const char*, int) { // Always just do 0-byte writes return 0; } -static int closeFunc(void* context) { - if (context != &globalDescriptor) { +static int CloseFunc(void* context) { + if (context != &g_global_descriptor) { SharedBufferReader* data = static_cast<SharedBufferReader*>(context); delete data; } return 0; } -static void errorFunc(void*, const char*, ...) { +static void ErrorFunc(void*, const char*, ...) { // FIXME: It would be nice to display error messages somewhere. } -static void initializeLibXMLIfNecessary() { - static bool didInit = false; - if (didInit) +static void InitializeLibXMLIfNecessary() { + static bool did_init = false; + if (did_init) return; - // We don't want libxml to try and load catalogs. - // FIXME: It's not nice to set global settings in libxml, embedders of Blink - // could be trying to use libxml themselves. - xmlCatalogSetDefaults(XML_CATA_ALLOW_NONE); xmlInitParser(); - xmlRegisterInputCallbacks(matchFunc, openFunc, readFunc, closeFunc); - xmlRegisterOutputCallbacks(matchFunc, openFunc, writeFunc, closeFunc); - libxmlLoaderThread = currentThread(); - didInit = true; + xmlRegisterInputCallbacks(MatchFunc, OpenFunc, ReadFunc, CloseFunc); + xmlRegisterOutputCallbacks(MatchFunc, OpenFunc, WriteFunc, CloseFunc); + g_libxml_loader_thread = CurrentThread(); + did_init = true; } -PassRefPtr<XMLParserContext> XMLParserContext::createStringParser( +PassRefPtr<XMLParserContext> XMLParserContext::CreateStringParser( xmlSAXHandlerPtr handlers, - void* userData) { - initializeLibXMLIfNecessary(); + void* user_data) { + InitializeLibXMLIfNecessary(); xmlParserCtxtPtr parser = xmlCreatePushParserCtxt(handlers, 0, 0, 0, 0); xmlCtxtUseOptions(parser, XML_PARSE_HUGE); - parser->_private = userData; + parser->_private = user_data; parser->replaceEntities = true; - return adoptRef(new XMLParserContext(parser)); + return AdoptRef(new XMLParserContext(parser)); } // Chunk should be encoded in UTF-8 -PassRefPtr<XMLParserContext> XMLParserContext::createMemoryParser( +PassRefPtr<XMLParserContext> XMLParserContext::CreateMemoryParser( xmlSAXHandlerPtr handlers, - void* userData, + void* user_data, const CString& chunk) { - initializeLibXMLIfNecessary(); + InitializeLibXMLIfNecessary(); // appendFragmentSource() checks that the length doesn't overflow an int. xmlParserCtxtPtr parser = - xmlCreateMemoryParserCtxt(chunk.data(), chunk.length()); + xmlCreateMemoryParserCtxt(chunk.Data(), chunk.length()); if (!parser) return nullptr; @@ -749,142 +748,142 @@ PassRefPtr<XMLParserContext> XMLParserContext::createMemoryParser( parser->str_xml = xmlDictLookup(parser->dict, BAD_CAST "xml", 3); parser->str_xmlns = xmlDictLookup(parser->dict, BAD_CAST "xmlns", 5); parser->str_xml_ns = xmlDictLookup(parser->dict, XML_XML_NAMESPACE, 36); - parser->_private = userData; + parser->_private = user_data; - return adoptRef(new XMLParserContext(parser)); + return AdoptRef(new XMLParserContext(parser)); } // -------------------------------- -bool XMLDocumentParser::supportsXMLVersion(const String& version) { +bool XMLDocumentParser::SupportsXMLVersion(const String& version) { return version == "1.0"; } -XMLDocumentParser::XMLDocumentParser(Document& document, FrameView* frameView) +XMLDocumentParser::XMLDocumentParser(Document& document, FrameView* frame_view) : ScriptableDocumentParser(document), - m_hasView(frameView), - m_context(nullptr), - m_currentNode(&document), - m_isCurrentlyParsing8BitChunk(false), - m_sawError(false), - m_sawCSS(false), - m_sawXSLTransform(false), - m_sawFirstElement(false), - m_isXHTMLDocument(false), - m_parserPaused(false), - m_requestingScript(false), - m_finishCalled(false), - m_xmlErrors(&document), - m_scriptStartPosition(TextPosition::belowRangePosition()), - m_parserBlockingPendingScriptLoadStartTime(0.0), - m_parsingFragment(false) { + has_view_(frame_view), + context_(nullptr), + current_node_(&document), + is_currently_parsing8_bit_chunk_(false), + saw_error_(false), + saw_css_(false), + saw_xsl_transform_(false), + saw_first_element_(false), + is_xhtml_document_(false), + parser_paused_(false), + requesting_script_(false), + finish_called_(false), + xml_errors_(&document), + script_start_position_(TextPosition::BelowRangePosition()), + parser_blocking_pending_script_load_start_time_(0.0), + parsing_fragment_(false) { // This is XML being used as a document resource. - if (frameView && document.isXMLDocument()) - UseCounter::count(document, UseCounter::XMLDocument); + if (frame_view && document.IsXMLDocument()) + UseCounter::Count(document, UseCounter::kXMLDocument); } XMLDocumentParser::XMLDocumentParser(DocumentFragment* fragment, - Element* parentElement, - ParserContentPolicy parserContentPolicy) - : ScriptableDocumentParser(fragment->document(), parserContentPolicy), - m_hasView(false), - m_context(nullptr), - m_currentNode(fragment), - m_isCurrentlyParsing8BitChunk(false), - m_sawError(false), - m_sawCSS(false), - m_sawXSLTransform(false), - m_sawFirstElement(false), - m_isXHTMLDocument(false), - m_parserPaused(false), - m_requestingScript(false), - m_finishCalled(false), - m_xmlErrors(&fragment->document()), - m_scriptStartPosition(TextPosition::belowRangePosition()), - m_parsingFragment(true) { + Element* parent_element, + ParserContentPolicy parser_content_policy) + : ScriptableDocumentParser(fragment->GetDocument(), parser_content_policy), + has_view_(false), + context_(nullptr), + current_node_(fragment), + is_currently_parsing8_bit_chunk_(false), + saw_error_(false), + saw_css_(false), + saw_xsl_transform_(false), + saw_first_element_(false), + is_xhtml_document_(false), + parser_paused_(false), + requesting_script_(false), + finish_called_(false), + xml_errors_(&fragment->GetDocument()), + script_start_position_(TextPosition::BelowRangePosition()), + parsing_fragment_(true) { // Add namespaces based on the parent node - HeapVector<Member<Element>> elemStack; - while (parentElement) { - elemStack.push_back(parentElement); + HeapVector<Member<Element>> elem_stack; + while (parent_element) { + elem_stack.push_back(parent_element); - Element* grandParentElement = parentElement->parentElement(); - if (!grandParentElement) + Element* grand_parent_element = parent_element->parentElement(); + if (!grand_parent_element) break; - parentElement = grandParentElement; + parent_element = grand_parent_element; } - if (elemStack.isEmpty()) + if (elem_stack.IsEmpty()) return; - for (; !elemStack.isEmpty(); elemStack.pop_back()) { - Element* element = elemStack.back(); - AttributeCollection attributes = element->attributes(); + for (; !elem_stack.IsEmpty(); elem_stack.pop_back()) { + Element* element = elem_stack.back(); + AttributeCollection attributes = element->Attributes(); for (auto& attribute : attributes) { - if (attribute.localName() == xmlnsAtom) - m_defaultNamespaceURI = attribute.value(); - else if (attribute.prefix() == xmlnsAtom) - m_prefixToNamespaceMap.set(attribute.localName(), attribute.value()); + if (attribute.LocalName() == g_xmlns_atom) + default_namespace_uri_ = attribute.Value(); + else if (attribute.Prefix() == g_xmlns_atom) + prefix_to_namespace_map_.Set(attribute.LocalName(), attribute.Value()); } } // If the parent element is not in document tree, there may be no xmlns // attribute; just default to the parent's namespace. - if (m_defaultNamespaceURI.isNull() && !parentElement->isConnected()) - m_defaultNamespaceURI = parentElement->namespaceURI(); + if (default_namespace_uri_.IsNull() && !parent_element->isConnected()) + default_namespace_uri_ = parent_element->namespaceURI(); } XMLParserContext::~XMLParserContext() { - if (m_context->myDoc) - xmlFreeDoc(m_context->myDoc); - xmlFreeParserCtxt(m_context); + if (context_->myDoc) + xmlFreeDoc(context_->myDoc); + xmlFreeParserCtxt(context_); } XMLDocumentParser::~XMLDocumentParser() { - DCHECK(!m_pendingScript); + DCHECK(!pending_script_); } DEFINE_TRACE(XMLDocumentParser) { - visitor->trace(m_currentNode); - visitor->trace(m_currentNodeStack); - visitor->trace(m_leafTextNode); - visitor->trace(m_xmlErrors); - visitor->trace(m_pendingScript); - visitor->trace(m_scriptElement); - ScriptableDocumentParser::trace(visitor); - ScriptResourceClient::trace(visitor); + visitor->Trace(current_node_); + visitor->Trace(current_node_stack_); + visitor->Trace(leaf_text_node_); + visitor->Trace(xml_errors_); + visitor->Trace(pending_script_); + visitor->Trace(script_element_); + ScriptableDocumentParser::Trace(visitor); + ScriptResourceClient::Trace(visitor); } -void XMLDocumentParser::doWrite(const String& parseString) { +void XMLDocumentParser::DoWrite(const String& parse_string) { TRACE_EVENT0("blink", "XMLDocumentParser::doWrite"); - DCHECK(!isDetached()); - if (!m_context) - initializeParserContext(); + DCHECK(!IsDetached()); + if (!context_) + InitializeParserContext(); // Protect the libxml context from deletion during a callback - RefPtr<XMLParserContext> context = m_context; + RefPtr<XMLParserContext> context = context_; // libXML throws an error if you try to switch the encoding for an empty // string. - if (parseString.length()) { - XMLDocumentParserScope scope(document()); - AutoReset<bool> encodingScope(&m_isCurrentlyParsing8BitChunk, - parseString.is8Bit()); - parseChunk(context->context(), parseString); + if (parse_string.length()) { + XMLDocumentParserScope scope(GetDocument()); + AutoReset<bool> encoding_scope(&is_currently_parsing8_bit_chunk_, + parse_string.Is8Bit()); + ParseChunk(context->Context(), parse_string); // JavaScript (which may be run under the parseChunk callstack) may // cause the parser to be stopped or detached. - if (isStopped()) + if (IsStopped()) return; } // FIXME: Why is this here? And why is it after we process the passed // source? - if (document()->sawDecodingError()) { + if (GetDocument()->SawDecodingError()) { // If the decoder saw an error, report it as fatal (stops parsing) TextPosition position( - OrdinalNumber::fromOneBasedInt(context->context()->input->line), - OrdinalNumber::fromOneBasedInt(context->context()->input->col)); - handleError(XMLErrors::ErrorTypeFatal, "Encoding error", position); + OrdinalNumber::FromOneBasedInt(context->Context()->input->line), + OrdinalNumber::FromOneBasedInt(context->Context()->input->col)); + HandleError(XMLErrors::kErrorTypeFatal, "Encoding error", position); } } @@ -893,26 +892,26 @@ struct xmlSAX2Namespace { const xmlChar* uri; }; -static inline void handleNamespaceAttributes( - Vector<Attribute>& prefixedAttributes, - const xmlChar** libxmlNamespaces, - int nbNamespaces, - ExceptionState& exceptionState) { +static inline void HandleNamespaceAttributes( + Vector<Attribute>& prefixed_attributes, + const xmlChar** libxml_namespaces, + int nb_namespaces, + ExceptionState& exception_state) { xmlSAX2Namespace* namespaces = - reinterpret_cast<xmlSAX2Namespace*>(libxmlNamespaces); - for (int i = 0; i < nbNamespaces; ++i) { - AtomicString namespaceQName = xmlnsAtom; - AtomicString namespaceURI = toAtomicString(namespaces[i].uri); + reinterpret_cast<xmlSAX2Namespace*>(libxml_namespaces); + for (int i = 0; i < nb_namespaces; ++i) { + AtomicString namespace_q_name = g_xmlns_atom; + AtomicString namespace_uri = ToAtomicString(namespaces[i].uri); if (namespaces[i].prefix) - namespaceQName = - WTF::xmlnsWithColon + toAtomicString(namespaces[i].prefix); + namespace_q_name = + WTF::g_xmlns_with_colon + ToAtomicString(namespaces[i].prefix); - QualifiedName parsedName = anyName; - if (!Element::parseAttributeName(parsedName, XMLNSNames::xmlnsNamespaceURI, - namespaceQName, exceptionState)) + QualifiedName parsed_name = g_any_name; + if (!Element::ParseAttributeName(parsed_name, XMLNSNames::xmlnsNamespaceURI, + namespace_q_name, exception_state)) return; - prefixedAttributes.push_back(Attribute(parsedName, namespaceURI)); + prefixed_attributes.push_back(Attribute(parsed_name, namespace_uri)); } } @@ -924,349 +923,357 @@ struct xmlSAX2Attributes { const xmlChar* end; }; -static inline void handleElementAttributes( - Vector<Attribute>& prefixedAttributes, - const xmlChar** libxmlAttributes, - int nbAttributes, - const HashMap<AtomicString, AtomicString>& initialPrefixToNamespaceMap, - ExceptionState& exceptionState) { +static inline void HandleElementAttributes( + Vector<Attribute>& prefixed_attributes, + const xmlChar** libxml_attributes, + int nb_attributes, + const HashMap<AtomicString, AtomicString>& initial_prefix_to_namespace_map, + ExceptionState& exception_state) { xmlSAX2Attributes* attributes = - reinterpret_cast<xmlSAX2Attributes*>(libxmlAttributes); - for (int i = 0; i < nbAttributes; ++i) { - int valueLength = static_cast<int>(attributes[i].end - attributes[i].value); - AtomicString attrValue = toAtomicString(attributes[i].value, valueLength); - AtomicString attrPrefix = toAtomicString(attributes[i].prefix); - AtomicString attrURI; - if (!attrPrefix.isEmpty()) { + reinterpret_cast<xmlSAX2Attributes*>(libxml_attributes); + for (int i = 0; i < nb_attributes; ++i) { + int value_length = + static_cast<int>(attributes[i].end - attributes[i].value); + AtomicString attr_value = ToAtomicString(attributes[i].value, value_length); + AtomicString attr_prefix = ToAtomicString(attributes[i].prefix); + AtomicString attr_uri; + if (!attr_prefix.IsEmpty()) { // If provided, use the namespace URI from libxml2 because libxml2 // updates its namespace table as it parses whereas the // initialPrefixToNamespaceMap is the initial map from namespace // prefixes to namespace URIs created by the XMLDocumentParser // constructor (in the case where we are parsing an XML fragment). if (attributes[i].uri) { - attrURI = toAtomicString(attributes[i].uri); + attr_uri = ToAtomicString(attributes[i].uri); } else { const HashMap<AtomicString, AtomicString>::const_iterator it = - initialPrefixToNamespaceMap.find(attrPrefix); - if (it != initialPrefixToNamespaceMap.end()) - attrURI = it->value; + initial_prefix_to_namespace_map.Find(attr_prefix); + if (it != initial_prefix_to_namespace_map.end()) + attr_uri = it->value; else - attrURI = AtomicString(); + attr_uri = AtomicString(); } } - AtomicString attrQName = - attrPrefix.isEmpty() - ? toAtomicString(attributes[i].localname) - : attrPrefix + ":" + toString(attributes[i].localname); - - QualifiedName parsedName = anyName; - if (!Element::parseAttributeName(parsedName, attrURI, attrQName, - exceptionState)) + AtomicString attr_q_name = + attr_prefix.IsEmpty() + ? ToAtomicString(attributes[i].localname) + : attr_prefix + ":" + ToString(attributes[i].localname); + + QualifiedName parsed_name = g_any_name; + if (!Element::ParseAttributeName(parsed_name, attr_uri, attr_q_name, + exception_state)) return; - prefixedAttributes.push_back(Attribute(parsedName, attrValue)); + prefixed_attributes.push_back(Attribute(parsed_name, attr_value)); } } -void XMLDocumentParser::startElementNs(const AtomicString& localName, +void XMLDocumentParser::StartElementNs(const AtomicString& local_name, const AtomicString& prefix, const AtomicString& uri, - int nbNamespaces, - const xmlChar** libxmlNamespaces, - int nbAttributes, - int nbDefaulted, - const xmlChar** libxmlAttributes) { - if (isStopped()) + int nb_namespaces, + const xmlChar** libxml_namespaces, + int nb_attributes, + int nb_defaulted, + const xmlChar** libxml_attributes) { + if (IsStopped()) return; - if (m_parserPaused) { - m_scriptStartPosition = textPosition(); - m_pendingCallbacks.append(WTF::wrapUnique(new PendingStartElementNSCallback( - localName, prefix, uri, nbNamespaces, libxmlNamespaces, nbAttributes, - nbDefaulted, libxmlAttributes))); + if (parser_paused_) { + script_start_position_ = GetTextPosition(); + pending_callbacks_.push_back( + WTF::WrapUnique(new PendingStartElementNSCallback( + local_name, prefix, uri, nb_namespaces, libxml_namespaces, + nb_attributes, nb_defaulted, libxml_attributes))); return; } - if (!updateLeafTextNode()) + if (!UpdateLeafTextNode()) return; - AtomicString adjustedURI = uri; - if (m_parsingFragment && adjustedURI.isNull()) { - if (!prefix.isNull()) - adjustedURI = m_prefixToNamespaceMap.at(prefix); + AtomicString adjusted_uri = uri; + if (parsing_fragment_ && adjusted_uri.IsNull()) { + if (!prefix.IsNull()) + adjusted_uri = prefix_to_namespace_map_.at(prefix); else - adjustedURI = m_defaultNamespaceURI; + adjusted_uri = default_namespace_uri_; } - bool isFirstElement = !m_sawFirstElement; - m_sawFirstElement = true; + bool is_first_element = !saw_first_element_; + saw_first_element_ = true; - QualifiedName qName(prefix, localName, adjustedURI); - Element* newElement = - m_currentNode->document().createElement(qName, CreatedByParser); - if (!newElement) { - stopParsing(); + QualifiedName q_name(prefix, local_name, adjusted_uri); + Element* new_element = + current_node_->GetDocument().createElement(q_name, kCreatedByParser); + if (!new_element) { + StopParsing(); return; } - Vector<Attribute> prefixedAttributes; - DummyExceptionStateForTesting exceptionState; - handleNamespaceAttributes(prefixedAttributes, libxmlNamespaces, nbNamespaces, - exceptionState); - if (exceptionState.hadException()) { - setAttributes(newElement, prefixedAttributes, getParserContentPolicy()); - stopParsing(); + Vector<Attribute> prefixed_attributes; + DummyExceptionStateForTesting exception_state; + HandleNamespaceAttributes(prefixed_attributes, libxml_namespaces, + nb_namespaces, exception_state); + if (exception_state.HadException()) { + SetAttributes(new_element, prefixed_attributes, GetParserContentPolicy()); + StopParsing(); return; } - handleElementAttributes(prefixedAttributes, libxmlAttributes, nbAttributes, - m_prefixToNamespaceMap, exceptionState); - setAttributes(newElement, prefixedAttributes, getParserContentPolicy()); - if (exceptionState.hadException()) { - stopParsing(); + HandleElementAttributes(prefixed_attributes, libxml_attributes, nb_attributes, + prefix_to_namespace_map_, exception_state); + SetAttributes(new_element, prefixed_attributes, GetParserContentPolicy()); + if (exception_state.HadException()) { + StopParsing(); return; } - newElement->beginParsingChildren(); + new_element->BeginParsingChildren(); - ScriptLoader* scriptLoader = toScriptLoaderIfPossible(newElement); - if (scriptLoader) - m_scriptStartPosition = textPosition(); + if (new_element->IsScriptElement()) + script_start_position_ = GetTextPosition(); - m_currentNode->parserAppendChild(newElement); + current_node_->ParserAppendChild(new_element); // Event handlers may synchronously trigger removal of the // document and cancellation of this parser. - if (isStopped()) { - stopParsing(); + if (IsStopped()) { + StopParsing(); return; } - if (isHTMLTemplateElement(*newElement)) - pushCurrentNode(toHTMLTemplateElement(*newElement).content()); + if (isHTMLTemplateElement(*new_element)) + PushCurrentNode(toHTMLTemplateElement(*new_element).content()); else - pushCurrentNode(newElement); + PushCurrentNode(new_element); // Note: |insertedByParser| will perform dispatching if this is an // HTMLHtmlElement. - if (isHTMLHtmlElement(*newElement) && isFirstElement) { - toHTMLHtmlElement(*newElement).insertedByParser(); - } else if (!m_parsingFragment && isFirstElement && document()->frame()) { - document()->frame()->loader().dispatchDocumentElementAvailable(); - document()->frame()->loader().runScriptsAtDocumentElementAvailable(); + if (isHTMLHtmlElement(*new_element) && is_first_element) { + toHTMLHtmlElement(*new_element).InsertedByParser(); + } else if (!parsing_fragment_ && is_first_element && + GetDocument()->GetFrame()) { + GetDocument()->GetFrame()->Loader().DispatchDocumentElementAvailable(); + GetDocument()->GetFrame()->Loader().RunScriptsAtDocumentElementAvailable(); // runScriptsAtDocumentElementAvailable might have invalidated the document. } } -void XMLDocumentParser::endElementNs() { - if (isStopped()) +void XMLDocumentParser::EndElementNs() { + if (IsStopped()) return; - if (m_parserPaused) { - m_pendingCallbacks.append( - WTF::makeUnique<PendingEndElementNSCallback>(m_scriptStartPosition)); + if (parser_paused_) { + pending_callbacks_.push_back( + WTF::MakeUnique<PendingEndElementNSCallback>(script_start_position_)); return; } - if (!updateLeafTextNode()) + if (!UpdateLeafTextNode()) return; - ContainerNode* n = m_currentNode; - if (m_currentNode->isElementNode()) - toElement(n)->finishParsingChildren(); - - if (!scriptingContentIsAllowed(getParserContentPolicy()) && - n->isElementNode() && toScriptLoaderIfPossible(toElement(n))) { - popCurrentNode(); + ContainerNode* n = current_node_; + if (current_node_->IsElementNode()) + ToElement(n)->FinishParsingChildren(); + + ScriptElementBase* script_element_base = + n->IsElementNode() + ? ScriptElementBase::FromElementIfPossible(ToElement(n)) + : nullptr; + if (!ScriptingContentIsAllowed(GetParserContentPolicy()) && + script_element_base) { + PopCurrentNode(); n->remove(IGNORE_EXCEPTION_FOR_TESTING); return; } - if (!n->isElementNode() || !m_hasView) { - popCurrentNode(); + if (!n->IsElementNode() || !has_view_) { + PopCurrentNode(); return; } - Element* element = toElement(n); + Element* element = ToElement(n); // The element's parent may have already been removed from document. // Parsing continues in this case, but scripts aren't executed. if (!element->isConnected()) { - popCurrentNode(); + PopCurrentNode(); return; } - ScriptLoader* scriptLoader = toScriptLoaderIfPossible(element); - if (!scriptLoader) { - popCurrentNode(); + ScriptLoader* script_loader = + script_element_base ? script_element_base->Loader() : nullptr; + if (!script_loader) { + PopCurrentNode(); return; } // Don't load external scripts for standalone documents (for now). - DCHECK(!m_pendingScript); - m_requestingScript = true; + DCHECK(!pending_script_); + requesting_script_ = true; - if (scriptLoader->prepareScript( - m_scriptStartPosition, - ScriptLoader::AllowLegacyTypeInTypeAttribute)) { + if (script_loader->PrepareScript( + script_start_position_, + ScriptLoader::kAllowLegacyTypeInTypeAttribute)) { // FIXME: Script execution should be shared between // the libxml2 and Qt XMLDocumentParser implementations. - if (scriptLoader->readyToBeParserExecuted()) { - if (!scriptLoader->executeScript( - ScriptSourceCode(scriptLoader->scriptContent(), document()->url(), - m_scriptStartPosition))) { - scriptLoader->dispatchErrorEvent(); + if (script_loader->ReadyToBeParserExecuted()) { + if (!script_loader->ExecuteScript(ClassicScript::Create(ScriptSourceCode( + script_loader->ScriptContent(), GetDocument()->Url(), + script_start_position_)))) { + script_loader->DispatchErrorEvent(); return; } - } else if (scriptLoader->willBeParserExecuted()) { - m_pendingScript = scriptLoader->resource(); - DCHECK_EQ(m_parserBlockingPendingScriptLoadStartTime, 0.0); - m_parserBlockingPendingScriptLoadStartTime = - monotonicallyIncreasingTime(); - m_scriptElement = element; - m_pendingScript->addClient(this); + } else if (script_loader->WillBeParserExecuted()) { + pending_script_ = script_loader->GetResource(); + DCHECK_EQ(parser_blocking_pending_script_load_start_time_, 0.0); + parser_blocking_pending_script_load_start_time_ = + MonotonicallyIncreasingTime(); + script_element_ = element; + pending_script_->AddClient(this); // m_pendingScript will be 0 if script was already loaded and // addClient() executed it. - if (m_pendingScript) - pauseParsing(); + if (pending_script_) + PauseParsing(); } else { - m_scriptElement = nullptr; + script_element_ = nullptr; } // JavaScript may have detached the parser - if (isDetached()) + if (IsDetached()) return; } - m_requestingScript = false; - popCurrentNode(); + requesting_script_ = false; + PopCurrentNode(); } -void XMLDocumentParser::setScriptStartPosition(TextPosition textPosition) { - m_scriptStartPosition = textPosition; +void XMLDocumentParser::SetScriptStartPosition(TextPosition text_position) { + script_start_position_ = text_position; } -void XMLDocumentParser::characters(const xmlChar* chars, int length) { - if (isStopped()) +void XMLDocumentParser::Characters(const xmlChar* chars, int length) { + if (IsStopped()) return; - if (m_parserPaused) { - m_pendingCallbacks.append( - WTF::makeUnique<PendingCharactersCallback>(chars, length)); + if (parser_paused_) { + pending_callbacks_.push_back( + WTF::MakeUnique<PendingCharactersCallback>(chars, length)); return; } - createLeafTextNodeIfNeeded(); - m_bufferedText.append(chars, length); + CreateLeafTextNodeIfNeeded(); + buffered_text_.Append(chars, length); } -void XMLDocumentParser::error(XMLErrors::ErrorType type, - const char* message, - va_list args) { - if (isStopped()) +void XMLDocumentParser::GetError(XMLErrors::ErrorType type, + const char* message, + va_list args) { + if (IsStopped()) return; - char formattedMessage[1024]; - vsnprintf(formattedMessage, sizeof(formattedMessage) - 1, message, args); + char formatted_message[1024]; + vsnprintf(formatted_message, sizeof(formatted_message) - 1, message, args); - if (m_parserPaused) { - m_pendingCallbacks.append(WTF::wrapUnique(new PendingErrorCallback( - type, reinterpret_cast<const xmlChar*>(formattedMessage), lineNumber(), - columnNumber()))); + if (parser_paused_) { + pending_callbacks_.push_back(WTF::WrapUnique(new PendingErrorCallback( + type, reinterpret_cast<const xmlChar*>(formatted_message), LineNumber(), + ColumnNumber()))); return; } - handleError(type, formattedMessage, textPosition()); + HandleError(type, formatted_message, GetTextPosition()); } -void XMLDocumentParser::processingInstruction(const String& target, - const String& data) { - if (isStopped()) +void XMLDocumentParser::GetProcessingInstruction(const String& target, + const String& data) { + if (IsStopped()) return; - if (m_parserPaused) { - m_pendingCallbacks.append( - WTF::makeUnique<PendingProcessingInstructionCallback>(target, data)); + if (parser_paused_) { + pending_callbacks_.push_back( + WTF::MakeUnique<PendingProcessingInstructionCallback>(target, data)); return; } - if (!updateLeafTextNode()) + if (!UpdateLeafTextNode()) return; // ### handle exceptions - DummyExceptionStateForTesting exceptionState; + DummyExceptionStateForTesting exception_state; ProcessingInstruction* pi = - m_currentNode->document().createProcessingInstruction(target, data, - exceptionState); - if (exceptionState.hadException()) + current_node_->GetDocument().createProcessingInstruction(target, data, + exception_state); + if (exception_state.HadException()) return; - m_currentNode->parserAppendChild(pi); + current_node_->ParserAppendChild(pi); - if (pi->isCSS()) - m_sawCSS = true; + if (pi->IsCSS()) + saw_css_ = true; if (!RuntimeEnabledFeatures::xsltEnabled()) return; - m_sawXSLTransform = !m_sawFirstElement && pi->isXSL(); - if (m_sawXSLTransform && - !DocumentXSLT::hasTransformSourceDocument(*document())) { + saw_xsl_transform_ = !saw_first_element_ && pi->IsXSL(); + if (saw_xsl_transform_ && + !DocumentXSLT::HasTransformSourceDocument(*GetDocument())) { // This behavior is very tricky. We call stopParsing() here because we // want to stop processing the document until we're ready to apply the // transform, but we actually still want to be fed decoded string pieces // to accumulate in m_originalSourceForTransform. So, we call // stopParsing() here and check isStopped() in element callbacks. // FIXME: This contradicts the contract of DocumentParser. - stopParsing(); + StopParsing(); } } -void XMLDocumentParser::cdataBlock(const String& text) { - if (isStopped()) +void XMLDocumentParser::CdataBlock(const String& text) { + if (IsStopped()) return; - if (m_parserPaused) { - m_pendingCallbacks.append(WTF::makeUnique<PendingCDATABlockCallback>(text)); + if (parser_paused_) { + pending_callbacks_.push_back( + WTF::MakeUnique<PendingCDATABlockCallback>(text)); return; } - if (!updateLeafTextNode()) + if (!UpdateLeafTextNode()) return; - m_currentNode->parserAppendChild( - CDATASection::create(m_currentNode->document(), text)); + current_node_->ParserAppendChild( + CDATASection::Create(current_node_->GetDocument(), text)); } -void XMLDocumentParser::comment(const String& text) { - if (isStopped()) +void XMLDocumentParser::Comment(const String& text) { + if (IsStopped()) return; - if (m_parserPaused) { - m_pendingCallbacks.append(WTF::makeUnique<PendingCommentCallback>(text)); + if (parser_paused_) { + pending_callbacks_.push_back(WTF::MakeUnique<PendingCommentCallback>(text)); return; } - if (!updateLeafTextNode()) + if (!UpdateLeafTextNode()) return; - m_currentNode->parserAppendChild( - Comment::create(m_currentNode->document(), text)); + current_node_->ParserAppendChild( + Comment::Create(current_node_->GetDocument(), text)); } enum StandaloneInfo { - StandaloneUnspecified = -2, - NoXMlDeclaration, - StandaloneNo, - StandaloneYes + kStandaloneUnspecified = -2, + kNoXMlDeclaration, + kStandaloneNo, + kStandaloneYes }; -void XMLDocumentParser::startDocument(const String& version, +void XMLDocumentParser::StartDocument(const String& version, const String& encoding, int standalone) { - StandaloneInfo standaloneInfo = static_cast<StandaloneInfo>(standalone); - if (standaloneInfo == NoXMlDeclaration) { - document()->setHasXMLDeclaration(false); + StandaloneInfo standalone_info = static_cast<StandaloneInfo>(standalone); + if (standalone_info == kNoXMlDeclaration) { + GetDocument()->SetHasXMLDeclaration(false); return; } @@ -1276,155 +1283,157 @@ void XMLDocumentParser::startDocument(const String& version, // version number other than '1.0', it will process it as a 1.0 document. This // means that an XML 1.0 processor will accept 1.x documents provided they do // not use any non-1.0 features." - if (!version.isNull() && supportsXMLVersion(version)) { - document()->setXMLVersion(version, ASSERT_NO_EXCEPTION); + if (!version.IsNull() && SupportsXMLVersion(version)) { + GetDocument()->setXMLVersion(version, ASSERT_NO_EXCEPTION); } - if (standalone != StandaloneUnspecified) - document()->setXMLStandalone(standaloneInfo == StandaloneYes, - ASSERT_NO_EXCEPTION); - if (!encoding.isNull()) - document()->setXMLEncoding(encoding); - document()->setHasXMLDeclaration(true); + if (standalone != kStandaloneUnspecified) + GetDocument()->setXMLStandalone(standalone_info == kStandaloneYes, + ASSERT_NO_EXCEPTION); + if (!encoding.IsNull()) + GetDocument()->SetXMLEncoding(encoding); + GetDocument()->SetHasXMLDeclaration(true); } -void XMLDocumentParser::endDocument() { - updateLeafTextNode(); +void XMLDocumentParser::EndDocument() { + UpdateLeafTextNode(); } -void XMLDocumentParser::internalSubset(const String& name, - const String& externalID, - const String& systemID) { - if (isStopped()) +void XMLDocumentParser::InternalSubset(const String& name, + const String& external_id, + const String& system_id) { + if (IsStopped()) return; - if (m_parserPaused) { - m_pendingCallbacks.append(WTF::wrapUnique( - new PendingInternalSubsetCallback(name, externalID, systemID))); + if (parser_paused_) { + pending_callbacks_.push_back(WTF::WrapUnique( + new PendingInternalSubsetCallback(name, external_id, system_id))); return; } - if (document()) - document()->parserAppendChild( - DocumentType::create(document(), name, externalID, systemID)); + if (GetDocument()) + GetDocument()->ParserAppendChild( + DocumentType::Create(GetDocument(), name, external_id, system_id)); } -static inline XMLDocumentParser* getParser(void* closure) { +static inline XMLDocumentParser* GetParser(void* closure) { xmlParserCtxtPtr ctxt = static_cast<xmlParserCtxtPtr>(closure); return static_cast<XMLDocumentParser*>(ctxt->_private); } -static void startElementNsHandler(void* closure, - const xmlChar* localName, +static void StartElementNsHandler(void* closure, + const xmlChar* local_name, const xmlChar* prefix, const xmlChar* uri, - int nbNamespaces, + int nb_namespaces, const xmlChar** namespaces, - int nbAttributes, - int nbDefaulted, - const xmlChar** libxmlAttributes) { - getParser(closure)->startElementNs( - toAtomicString(localName), toAtomicString(prefix), toAtomicString(uri), - nbNamespaces, namespaces, nbAttributes, nbDefaulted, libxmlAttributes); + int nb_attributes, + int nb_defaulted, + const xmlChar** libxml_attributes) { + GetParser(closure)->StartElementNs( + ToAtomicString(local_name), ToAtomicString(prefix), ToAtomicString(uri), + nb_namespaces, namespaces, nb_attributes, nb_defaulted, + libxml_attributes); } -static void endElementNsHandler(void* closure, +static void EndElementNsHandler(void* closure, const xmlChar*, const xmlChar*, const xmlChar*) { - getParser(closure)->endElementNs(); + GetParser(closure)->EndElementNs(); } -static void charactersHandler(void* closure, const xmlChar* chars, int length) { - getParser(closure)->characters(chars, length); +static void CharactersHandler(void* closure, const xmlChar* chars, int length) { + GetParser(closure)->Characters(chars, length); } -static void processingInstructionHandler(void* closure, +static void ProcessingInstructionHandler(void* closure, const xmlChar* target, const xmlChar* data) { - getParser(closure)->processingInstruction(toString(target), toString(data)); + GetParser(closure)->GetProcessingInstruction(ToString(target), + ToString(data)); } -static void cdataBlockHandler(void* closure, const xmlChar* text, int length) { - getParser(closure)->cdataBlock(toString(text, length)); +static void CdataBlockHandler(void* closure, const xmlChar* text, int length) { + GetParser(closure)->CdataBlock(ToString(text, length)); } -static void commentHandler(void* closure, const xmlChar* text) { - getParser(closure)->comment(toString(text)); +static void CommentHandler(void* closure, const xmlChar* text) { + GetParser(closure)->Comment(ToString(text)); } PRINTF_FORMAT(2, 3) -static void warningHandler(void* closure, const char* message, ...) { +static void WarningHandler(void* closure, const char* message, ...) { va_list args; va_start(args, message); - getParser(closure)->error(XMLErrors::ErrorTypeWarning, message, args); + GetParser(closure)->GetError(XMLErrors::kErrorTypeWarning, message, args); va_end(args); } PRINTF_FORMAT(2, 3) -static void normalErrorHandler(void* closure, const char* message, ...) { +static void NormalErrorHandler(void* closure, const char* message, ...) { va_list args; va_start(args, message); - getParser(closure)->error(XMLErrors::ErrorTypeNonFatal, message, args); + GetParser(closure)->GetError(XMLErrors::kErrorTypeNonFatal, message, args); va_end(args); } // Using a static entity and marking it XML_INTERNAL_PREDEFINED_ENTITY is a hack // to avoid malloc/free. Using a global variable like this could cause trouble // if libxml implementation details were to change -static xmlChar sharedXHTMLEntityResult[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0}; +static xmlChar g_shared_xhtml_entity_result[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0}; -static xmlEntityPtr sharedXHTMLEntity() { +static xmlEntityPtr SharedXHTMLEntity() { static xmlEntity entity; if (!entity.type) { entity.type = XML_ENTITY_DECL; - entity.orig = sharedXHTMLEntityResult; - entity.content = sharedXHTMLEntityResult; + entity.orig = g_shared_xhtml_entity_result; + entity.content = g_shared_xhtml_entity_result; entity.etype = XML_INTERNAL_PREDEFINED_ENTITY; } return &entity; } -static size_t convertUTF16EntityToUTF8(const UChar* utf16Entity, - size_t numberOfCodeUnits, +static size_t ConvertUTF16EntityToUTF8(const UChar* utf16_entity, + size_t number_of_code_units, char* target, - size_t targetSize) { - const char* originalTarget = target; - WTF::Unicode::ConversionResult conversionResult = - WTF::Unicode::convertUTF16ToUTF8(&utf16Entity, - utf16Entity + numberOfCodeUnits, &target, - target + targetSize); - if (conversionResult != WTF::Unicode::conversionOK) + size_t target_size) { + const char* original_target = target; + WTF::Unicode::ConversionResult conversion_result = + WTF::Unicode::ConvertUTF16ToUTF8(&utf16_entity, + utf16_entity + number_of_code_units, + &target, target + target_size); + if (conversion_result != WTF::Unicode::kConversionOK) return 0; // Even though we must pass the length, libxml expects the entity string to be // null terminated. - DCHECK_GT(target, originalTarget + 1); + DCHECK_GT(target, original_target + 1); *target = '\0'; - return target - originalTarget; + return target - original_target; } -static xmlEntityPtr getXHTMLEntity(const xmlChar* name) { - UChar utf16DecodedEntity[4]; - size_t numberOfCodeUnits = decodeNamedEntityToUCharArray( - reinterpret_cast<const char*>(name), utf16DecodedEntity); - if (!numberOfCodeUnits) +static xmlEntityPtr GetXHTMLEntity(const xmlChar* name) { + UChar utf16_decoded_entity[4]; + size_t number_of_code_units = DecodeNamedEntityToUCharArray( + reinterpret_cast<const char*>(name), utf16_decoded_entity); + if (!number_of_code_units) return 0; - DCHECK_LE(numberOfCodeUnits, 4u); - size_t entityLengthInUTF8 = - convertUTF16EntityToUTF8(utf16DecodedEntity, numberOfCodeUnits, - reinterpret_cast<char*>(sharedXHTMLEntityResult), - WTF_ARRAY_LENGTH(sharedXHTMLEntityResult)); - if (!entityLengthInUTF8) + DCHECK_LE(number_of_code_units, 4u); + size_t entity_length_in_utf8 = ConvertUTF16EntityToUTF8( + utf16_decoded_entity, number_of_code_units, + reinterpret_cast<char*>(g_shared_xhtml_entity_result), + WTF_ARRAY_LENGTH(g_shared_xhtml_entity_result)); + if (!entity_length_in_utf8) return 0; - xmlEntityPtr entity = sharedXHTMLEntity(); - entity->length = entityLengthInUTF8; + xmlEntityPtr entity = SharedXHTMLEntity(); + entity->length = entity_length_in_utf8; entity->name = name; return entity; } -static xmlEntityPtr getEntityHandler(void* closure, const xmlChar* name) { +static xmlEntityPtr GetEntityHandler(void* closure, const xmlChar* name) { xmlParserCtxtPtr ctxt = static_cast<xmlParserCtxtPtr>(closure); xmlEntityPtr ent = xmlGetPredefinedEntity(name); if (ent) { @@ -1433,8 +1442,8 @@ static xmlEntityPtr getEntityHandler(void* closure, const xmlChar* name) { } ent = xmlGetDocEntity(ctxt->myDoc, name); - if (!ent && getParser(closure)->isXHTMLDocument()) { - ent = getXHTMLEntity(name); + if (!ent && GetParser(closure)->IsXHTMLDocument()) { + ent = GetXHTMLEntity(name); if (ent) ent->etype = XML_INTERNAL_GENERAL_ENTITY; } @@ -1442,56 +1451,56 @@ static xmlEntityPtr getEntityHandler(void* closure, const xmlChar* name) { return ent; } -static void startDocumentHandler(void* closure) { +static void StartDocumentHandler(void* closure) { xmlParserCtxt* ctxt = static_cast<xmlParserCtxt*>(closure); - XMLDocumentParser* parser = getParser(closure); - switchEncoding(ctxt, parser->isCurrentlyParsing8BitChunk()); - parser->startDocument(toString(ctxt->version), toString(ctxt->encoding), + XMLDocumentParser* parser = GetParser(closure); + SwitchEncoding(ctxt, parser->IsCurrentlyParsing8BitChunk()); + parser->StartDocument(ToString(ctxt->version), ToString(ctxt->encoding), ctxt->standalone); xmlSAX2StartDocument(closure); } -static void endDocumentHandler(void* closure) { - getParser(closure)->endDocument(); +static void EndDocumentHandler(void* closure) { + GetParser(closure)->EndDocument(); xmlSAX2EndDocument(closure); } -static void internalSubsetHandler(void* closure, +static void InternalSubsetHandler(void* closure, const xmlChar* name, - const xmlChar* externalID, - const xmlChar* systemID) { - getParser(closure)->internalSubset(toString(name), toString(externalID), - toString(systemID)); - xmlSAX2InternalSubset(closure, name, externalID, systemID); + const xmlChar* external_id, + const xmlChar* system_id) { + GetParser(closure)->InternalSubset(ToString(name), ToString(external_id), + ToString(system_id)); + xmlSAX2InternalSubset(closure, name, external_id, system_id); } -static void externalSubsetHandler(void* closure, +static void ExternalSubsetHandler(void* closure, const xmlChar*, - const xmlChar* externalId, + const xmlChar* external_id, const xmlChar*) { - String extId = toString(externalId); - if (extId == "-//W3C//DTD XHTML 1.0 Transitional//EN" || - extId == "-//W3C//DTD XHTML 1.1//EN" || - extId == "-//W3C//DTD XHTML 1.0 Strict//EN" || - extId == "-//W3C//DTD XHTML 1.0 Frameset//EN" || - extId == "-//W3C//DTD XHTML Basic 1.0//EN" || - extId == "-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN" || - extId == "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" || - extId == "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" || - extId == "-//WAPFORUM//DTD XHTML Mobile 1.1//EN" || - extId == "-//WAPFORUM//DTD XHTML Mobile 1.2//EN") { + String ext_id = ToString(external_id); + if (ext_id == "-//W3C//DTD XHTML 1.0 Transitional//EN" || + ext_id == "-//W3C//DTD XHTML 1.1//EN" || + ext_id == "-//W3C//DTD XHTML 1.0 Strict//EN" || + ext_id == "-//W3C//DTD XHTML 1.0 Frameset//EN" || + ext_id == "-//W3C//DTD XHTML Basic 1.0//EN" || + ext_id == "-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN" || + ext_id == "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" || + ext_id == "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" || + ext_id == "-//WAPFORUM//DTD XHTML Mobile 1.1//EN" || + ext_id == "-//WAPFORUM//DTD XHTML Mobile 1.2//EN") { // Controls if we replace entities or not. - getParser(closure)->setIsXHTMLDocument(true); + GetParser(closure)->SetIsXHTMLDocument(true); } } -static void ignorableWhitespaceHandler(void*, const xmlChar*, int) { +static void IgnorableWhitespaceHandler(void*, const xmlChar*, int) { // Nothing to do, but we need this to work around a crasher. // http://bugzilla.gnome.org/show_bug.cgi?id=172255 // http://bugs.webkit.org/show_bug.cgi?id=5792 } -void XMLDocumentParser::initializeParserContext(const CString& chunk) { +void XMLDocumentParser::InitializeParserContext(const CString& chunk) { xmlSAXHandler sax; memset(&sax, 0, sizeof(sax)); @@ -1499,219 +1508,220 @@ void XMLDocumentParser::initializeParserContext(const CString& chunk) { // http://xmlsoft.org/html/libxml-parser.html#fatalErrorSAXFunc the SAX // fatalError callback is unused; error gets all the errors. Use // normalErrorHandler for both the error and fatalError callbacks. - sax.error = normalErrorHandler; - sax.fatalError = normalErrorHandler; - sax.characters = charactersHandler; - sax.processingInstruction = processingInstructionHandler; - sax.cdataBlock = cdataBlockHandler; - sax.comment = commentHandler; - sax.warning = warningHandler; - sax.startElementNs = startElementNsHandler; - sax.endElementNs = endElementNsHandler; - sax.getEntity = getEntityHandler; - sax.startDocument = startDocumentHandler; - sax.endDocument = endDocumentHandler; - sax.internalSubset = internalSubsetHandler; - sax.externalSubset = externalSubsetHandler; - sax.ignorableWhitespace = ignorableWhitespaceHandler; + sax.error = NormalErrorHandler; + sax.fatalError = NormalErrorHandler; + sax.characters = CharactersHandler; + sax.processingInstruction = ProcessingInstructionHandler; + sax.cdataBlock = CdataBlockHandler; + sax.comment = CommentHandler; + sax.warning = WarningHandler; + sax.startElementNs = StartElementNsHandler; + sax.endElementNs = EndElementNsHandler; + sax.getEntity = GetEntityHandler; + sax.startDocument = StartDocumentHandler; + sax.endDocument = EndDocumentHandler; + sax.internalSubset = InternalSubsetHandler; + sax.externalSubset = ExternalSubsetHandler; + sax.ignorableWhitespace = IgnorableWhitespaceHandler; sax.entityDecl = xmlSAX2EntityDecl; sax.initialized = XML_SAX2_MAGIC; - m_sawError = false; - m_sawCSS = false; - m_sawXSLTransform = false; - m_sawFirstElement = false; - - XMLDocumentParserScope scope(document()); - if (m_parsingFragment) { - m_context = XMLParserContext::createMemoryParser(&sax, this, chunk); + saw_error_ = false; + saw_css_ = false; + saw_xsl_transform_ = false; + saw_first_element_ = false; + + XMLDocumentParserScope scope(GetDocument()); + if (parsing_fragment_) { + context_ = XMLParserContext::CreateMemoryParser(&sax, this, chunk); } else { - DCHECK(!chunk.data()); - m_context = XMLParserContext::createStringParser(&sax, this); + DCHECK(!chunk.Data()); + context_ = XMLParserContext::CreateStringParser(&sax, this); } } -void XMLDocumentParser::doEnd() { - if (!isStopped()) { - if (m_context) { +void XMLDocumentParser::DoEnd() { + if (!IsStopped()) { + if (context_) { // Tell libxml we're done. { - XMLDocumentParserScope scope(document()); - finishParsing(context()); + XMLDocumentParserScope scope(GetDocument()); + FinishParsing(Context()); } - m_context = nullptr; + context_ = nullptr; } } - bool xmlViewerMode = !m_sawError && !m_sawCSS && !m_sawXSLTransform && - hasNoStyleInformation(document()); - if (xmlViewerMode) { - document()->setIsViewSource(true); - transformDocumentToXMLTreeView(*document()); - } else if (m_sawXSLTransform) { - xmlDocPtr doc = - xmlDocPtrForString(document(), m_originalSourceForTransform.toString(), - document()->url().getString()); - document()->setTransformSource(WTF::makeUnique<TransformSource>(doc)); - DocumentParser::stopParsing(); + bool xml_viewer_mode = !saw_error_ && !saw_css_ && !saw_xsl_transform_ && + HasNoStyleInformation(GetDocument()); + if (xml_viewer_mode) { + GetDocument()->SetIsViewSource(true); + TransformDocumentToXMLTreeView(*GetDocument()); + } else if (saw_xsl_transform_) { + xmlDocPtr doc = XmlDocPtrForString( + GetDocument(), original_source_for_transform_.ToString(), + GetDocument()->Url().GetString()); + GetDocument()->SetTransformSource(WTF::MakeUnique<TransformSource>(doc)); + DocumentParser::StopParsing(); } } -xmlDocPtr xmlDocPtrForString(Document* document, +xmlDocPtr XmlDocPtrForString(Document* document, const String& source, const String& url) { - if (source.isEmpty()) + if (source.IsEmpty()) return 0; // Parse in a single chunk into an xmlDocPtr // FIXME: Hook up error handlers so that a failure to parse the main // document results in good error messages. - XMLDocumentParserScope scope(document, errorFunc, 0); + XMLDocumentParserScope scope(document, ErrorFunc, 0); XMLParserInput input(source); - return xmlReadMemory(input.data(), input.size(), url.latin1().data(), - input.encoding(), XSLT_PARSE_OPTIONS); + return xmlReadMemory(input.Data(), input.size(), url.Latin1().Data(), + input.Encoding(), XSLT_PARSE_OPTIONS); } -OrdinalNumber XMLDocumentParser::lineNumber() const { - return OrdinalNumber::fromOneBasedInt(context() ? context()->input->line : 1); +OrdinalNumber XMLDocumentParser::LineNumber() const { + return OrdinalNumber::FromOneBasedInt(Context() ? Context()->input->line : 1); } -OrdinalNumber XMLDocumentParser::columnNumber() const { - return OrdinalNumber::fromOneBasedInt(context() ? context()->input->col : 1); +OrdinalNumber XMLDocumentParser::ColumnNumber() const { + return OrdinalNumber::FromOneBasedInt(Context() ? Context()->input->col : 1); } -TextPosition XMLDocumentParser::textPosition() const { - xmlParserCtxtPtr context = this->context(); +TextPosition XMLDocumentParser::GetTextPosition() const { + xmlParserCtxtPtr context = this->Context(); if (!context) - return TextPosition::minimumPosition(); - return TextPosition(OrdinalNumber::fromOneBasedInt(context->input->line), - OrdinalNumber::fromOneBasedInt(context->input->col)); + return TextPosition::MinimumPosition(); + return TextPosition(OrdinalNumber::FromOneBasedInt(context->input->line), + OrdinalNumber::FromOneBasedInt(context->input->col)); } -void XMLDocumentParser::stopParsing() { - DocumentParser::stopParsing(); - if (context()) - xmlStopParser(context()); +void XMLDocumentParser::StopParsing() { + DocumentParser::StopParsing(); + if (Context()) + xmlStopParser(Context()); } -void XMLDocumentParser::resumeParsing() { - DCHECK(!isDetached()); - DCHECK(m_parserPaused); +void XMLDocumentParser::ResumeParsing() { + DCHECK(!IsDetached()); + DCHECK(parser_paused_); - m_parserPaused = false; + parser_paused_ = false; // First, execute any pending callbacks - while (!m_pendingCallbacks.isEmpty()) { - std::unique_ptr<PendingCallback> callback = m_pendingCallbacks.takeFirst(); - callback->call(this); + while (!pending_callbacks_.IsEmpty()) { + std::unique_ptr<PendingCallback> callback = pending_callbacks_.TakeFirst(); + callback->Call(this); // A callback paused the parser - if (m_parserPaused) + if (parser_paused_) return; } // Then, write any pending data - SegmentedString rest = m_pendingSrc; - m_pendingSrc.clear(); + SegmentedString rest = pending_src_; + pending_src_.Clear(); // There is normally only one string left, so toString() shouldn't copy. // In any case, the XML parser runs on the main thread and it's OK if // the passed string has more than one reference. - append(rest.toString().impl()); + Append(rest.ToString().Impl()); // Finally, if finish() has been called and write() didn't result // in any further callbacks being queued, call end() - if (m_finishCalled && m_pendingCallbacks.isEmpty()) + if (finish_called_ && pending_callbacks_.IsEmpty()) end(); } -bool XMLDocumentParser::appendFragmentSource(const String& chunk) { - DCHECK(!m_context); - DCHECK(m_parsingFragment); +bool XMLDocumentParser::AppendFragmentSource(const String& chunk) { + DCHECK(!context_); + DCHECK(parsing_fragment_); - CString chunkAsUtf8 = chunk.utf8(); + CString chunk_as_utf8 = chunk.Utf8(); // libxml2 takes an int for a length, and therefore can't handle XML chunks // larger than 2 GiB. - if (chunkAsUtf8.length() > INT_MAX) + if (chunk_as_utf8.length() > INT_MAX) return false; TRACE_EVENT0("blink", "XMLDocumentParser::appendFragmentSource"); - initializeParserContext(chunkAsUtf8); - xmlParseContent(context()); - endDocument(); // Close any open text nodes. + InitializeParserContext(chunk_as_utf8); + xmlParseContent(Context()); + EndDocument(); // Close any open text nodes. // FIXME: If this code is actually needed, it should probably move to // finish() // XMLDocumentParserQt has a similar check (m_stream.error() == // QXmlStreamReader::PrematureEndOfDocumentError) in doEnd(). Check if all // the chunk has been processed. - long bytesProcessed = xmlByteConsumed(context()); - if (bytesProcessed == -1 || - static_cast<unsigned long>(bytesProcessed) != chunkAsUtf8.length()) { + long bytes_processed = xmlByteConsumed(Context()); + if (bytes_processed == -1 || + static_cast<unsigned long>(bytes_processed) != chunk_as_utf8.length()) { // FIXME: I don't believe we can hit this case without also having seen // an error or a null byte. If we hit this DCHECK, we've found a test // case which demonstrates the need for this code. - DCHECK(m_sawError || - (bytesProcessed >= 0 && !chunkAsUtf8.data()[bytesProcessed])); + DCHECK(saw_error_ || + (bytes_processed >= 0 && !chunk_as_utf8.Data()[bytes_processed])); return false; } // No error if the chunk is well formed or it is not but we have no error. - return context()->wellFormed || !xmlCtxtGetLastError(context()); + return Context()->wellFormed || !xmlCtxtGetLastError(Context()); } // -------------------------------- struct AttributeParseState { HashMap<String, String> attributes; - bool gotAttributes; + bool got_attributes; }; -static void attributesStartElementNsHandler(void* closure, - const xmlChar* xmlLocalName, +static void AttributesStartElementNsHandler(void* closure, + const xmlChar* xml_local_name, const xmlChar* /*xmlPrefix*/, const xmlChar* /*xmlURI*/, int /*nbNamespaces*/, const xmlChar** /*namespaces*/, - int nbAttributes, + int nb_attributes, int /*nbDefaulted*/, - const xmlChar** libxmlAttributes) { - if (strcmp(reinterpret_cast<const char*>(xmlLocalName), "attrs") != 0) + const xmlChar** libxml_attributes) { + if (strcmp(reinterpret_cast<const char*>(xml_local_name), "attrs") != 0) return; xmlParserCtxtPtr ctxt = static_cast<xmlParserCtxtPtr>(closure); AttributeParseState* state = static_cast<AttributeParseState*>(ctxt->_private); - state->gotAttributes = true; + state->got_attributes = true; xmlSAX2Attributes* attributes = - reinterpret_cast<xmlSAX2Attributes*>(libxmlAttributes); - for (int i = 0; i < nbAttributes; ++i) { - String attrLocalName = toString(attributes[i].localname); - int valueLength = (int)(attributes[i].end - attributes[i].value); - String attrValue = toString(attributes[i].value, valueLength); - String attrPrefix = toString(attributes[i].prefix); - String attrQName = - attrPrefix.isEmpty() ? attrLocalName : attrPrefix + ":" + attrLocalName; - - state->attributes.set(attrQName, attrValue); + reinterpret_cast<xmlSAX2Attributes*>(libxml_attributes); + for (int i = 0; i < nb_attributes; ++i) { + String attr_local_name = ToString(attributes[i].localname); + int value_length = (int)(attributes[i].end - attributes[i].value); + String attr_value = ToString(attributes[i].value, value_length); + String attr_prefix = ToString(attributes[i].prefix); + String attr_q_name = attr_prefix.IsEmpty() + ? attr_local_name + : attr_prefix + ":" + attr_local_name; + + state->attributes.Set(attr_q_name, attr_value); } } -HashMap<String, String> parseAttributes(const String& string, bool& attrsOK) { +HashMap<String, String> ParseAttributes(const String& string, bool& attrs_ok) { AttributeParseState state; - state.gotAttributes = false; + state.got_attributes = false; xmlSAXHandler sax; memset(&sax, 0, sizeof(sax)); - sax.startElementNs = attributesStartElementNsHandler; + sax.startElementNs = AttributesStartElementNsHandler; sax.initialized = XML_SAX2_MAGIC; RefPtr<XMLParserContext> parser = - XMLParserContext::createStringParser(&sax, &state); - String parseString = "<?xml version=\"1.0\"?><attrs " + string + " />"; - parseChunk(parser->context(), parseString); - finishParsing(parser->context()); - attrsOK = state.gotAttributes; + XMLParserContext::CreateStringParser(&sax, &state); + String parse_string = "<?xml version=\"1.0\"?><attrs " + string + " />"; + ParseChunk(parser->Context(), parse_string); + FinishParsing(parser->Context()); + attrs_ok = state.got_attributes; return state.attributes; } diff --git a/chromium/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.h b/chromium/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.h index 132c9fe4ce8..d084b7146cd 100644 --- a/chromium/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.h +++ b/chromium/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.h @@ -26,6 +26,8 @@ #ifndef XMLDocumentParser_h #define XMLDocumentParser_h +#include <libxml/tree.h> +#include <memory> #include "core/dom/ParserContentPolicy.h" #include "core/dom/ScriptableDocumentParser.h" #include "core/loader/resource/ScriptResource.h" @@ -33,13 +35,11 @@ #include "platform/heap/Handle.h" #include "platform/loader/fetch/ResourceClient.h" #include "platform/text/SegmentedString.h" -#include "wtf/Compiler.h" -#include "wtf/HashMap.h" -#include "wtf/RefCounted.h" -#include "wtf/text/CString.h" -#include "wtf/text/StringHash.h" -#include <libxml/tree.h> -#include <memory> +#include "platform/wtf/Compiler.h" +#include "platform/wtf/HashMap.h" +#include "platform/wtf/RefCounted.h" +#include "platform/wtf/text/CString.h" +#include "platform/wtf/text/StringHash.h" namespace blink { @@ -52,18 +52,18 @@ class Text; class XMLParserContext : public RefCounted<XMLParserContext> { public: - static PassRefPtr<XMLParserContext> createMemoryParser(xmlSAXHandlerPtr, - void* userData, + static PassRefPtr<XMLParserContext> CreateMemoryParser(xmlSAXHandlerPtr, + void* user_data, const CString& chunk); - static PassRefPtr<XMLParserContext> createStringParser(xmlSAXHandlerPtr, - void* userData); + static PassRefPtr<XMLParserContext> CreateStringParser(xmlSAXHandlerPtr, + void* user_data); ~XMLParserContext(); - xmlParserCtxtPtr context() const { return m_context; } + xmlParserCtxtPtr Context() const { return context_; } private: - XMLParserContext(xmlParserCtxtPtr context) : m_context(context) {} + XMLParserContext(xmlParserCtxtPtr context) : context_(context) {} - xmlParserCtxtPtr m_context; + xmlParserCtxtPtr context_; }; class XMLDocumentParser final : public ScriptableDocumentParser, @@ -71,47 +71,49 @@ class XMLDocumentParser final : public ScriptableDocumentParser, USING_GARBAGE_COLLECTED_MIXIN(XMLDocumentParser); public: - static XMLDocumentParser* create(Document& document, FrameView* view) { + static XMLDocumentParser* Create(Document& document, FrameView* view) { return new XMLDocumentParser(document, view); } - static XMLDocumentParser* create(DocumentFragment* fragment, + static XMLDocumentParser* Create(DocumentFragment* fragment, Element* element, - ParserContentPolicy parserContentPolicy) { - return new XMLDocumentParser(fragment, element, parserContentPolicy); + ParserContentPolicy parser_content_policy) { + return new XMLDocumentParser(fragment, element, parser_content_policy); } ~XMLDocumentParser() override; DECLARE_VIRTUAL_TRACE(); // Exposed for callbacks: - void handleError(XMLErrors::ErrorType, const char* message, TextPosition); + void HandleError(XMLErrors::ErrorType, const char* message, TextPosition); - void setIsXHTMLDocument(bool isXHTML) { m_isXHTMLDocument = isXHTML; } - bool isXHTMLDocument() const { return m_isXHTMLDocument; } + void SetIsXHTMLDocument(bool is_xhtml) { is_xhtml_document_ = is_xhtml; } + bool IsXHTMLDocument() const { return is_xhtml_document_; } - bool isCurrentlyParsing8BitChunk() { return m_isCurrentlyParsing8BitChunk; } + bool IsCurrentlyParsing8BitChunk() { + return is_currently_parsing8_bit_chunk_; + } - static bool parseDocumentFragment( + static bool ParseDocumentFragment( const String&, DocumentFragment*, Element* parent = 0, - ParserContentPolicy = AllowScriptingContent); + ParserContentPolicy = kAllowScriptingContent); // Used by the XMLHttpRequest to check if the responseXML was well formed. - bool wellFormed() const override { return !m_sawError; } + bool WellFormed() const override { return !saw_error_; } - TextPosition textPosition() const override; + TextPosition GetTextPosition() const override; - static bool supportsXMLVersion(const String&); + static bool SupportsXMLVersion(const String&); class PendingCallback { USING_FAST_MALLOC(PendingCallback); public: virtual ~PendingCallback() {} - virtual void call(XMLDocumentParser*) = 0; + virtual void Call(XMLDocumentParser*) = 0; }; - void setScriptStartPosition(TextPosition); + void SetScriptStartPosition(TextPosition); private: explicit XMLDocumentParser(Document&, FrameView* = 0); @@ -119,110 +121,110 @@ class XMLDocumentParser final : public ScriptableDocumentParser, // From DocumentParser void insert(const SegmentedString&) override; - void append(const String&) override; - void finish() override; - bool isWaitingForScripts() const override; - void stopParsing() override; - void detach() override; - OrdinalNumber lineNumber() const override; - OrdinalNumber columnNumber() const; + void Append(const String&) override; + void Finish() override; + bool IsWaitingForScripts() const override; + void StopParsing() override; + void Detach() override; + OrdinalNumber LineNumber() const override; + OrdinalNumber ColumnNumber() const; // from ResourceClient - void notifyFinished(Resource*) override; - String debugName() const override { return "XMLDocumentParser"; } + void NotifyFinished(Resource*) override; + String DebugName() const override { return "XMLDocumentParser"; } void end(); - void pauseParsing(); - void resumeParsing(); + void PauseParsing(); + void ResumeParsing(); - bool appendFragmentSource(const String&); + bool AppendFragmentSource(const String&); public: // Callbacks from parser SAX PRINTF_FORMAT(3, 0) - void error(XMLErrors::ErrorType, const char* message, va_list args); - void startElementNs(const AtomicString& localName, + void GetError(XMLErrors::ErrorType, const char* message, va_list args); + void StartElementNs(const AtomicString& local_name, const AtomicString& prefix, const AtomicString& uri, - int namespaceCount, + int namespace_count, const xmlChar** namespaces, - int attributeCount, - int defaultedCount, - const xmlChar** libxmlAttributes); - void endElementNs(); - void characters(const xmlChar* chars, int length); - void processingInstruction(const String& target, const String& data); - void cdataBlock(const String&); - void comment(const String&); - void startDocument(const String& version, + int attribute_count, + int defaulted_count, + const xmlChar** libxml_attributes); + void EndElementNs(); + void Characters(const xmlChar* chars, int length); + void GetProcessingInstruction(const String& target, const String& data); + void CdataBlock(const String&); + void Comment(const String&); + void StartDocument(const String& version, const String& encoding, int standalone); - void internalSubset(const String& name, - const String& externalID, - const String& systemID); - void endDocument(); + void InternalSubset(const String& name, + const String& external_id, + const String& system_id); + void EndDocument(); private: - void initializeParserContext(const CString& chunk = CString()); + void InitializeParserContext(const CString& chunk = CString()); - void pushCurrentNode(ContainerNode*); - void popCurrentNode(); - void clearCurrentNodeStack(); + void PushCurrentNode(ContainerNode*); + void PopCurrentNode(); + void ClearCurrentNodeStack(); - void insertErrorMessageBlock(); + void InsertErrorMessageBlock(); - void createLeafTextNodeIfNeeded(); - bool updateLeafTextNode(); + void CreateLeafTextNodeIfNeeded(); + bool UpdateLeafTextNode(); - void doWrite(const String&); - void doEnd(); + void DoWrite(const String&); + void DoEnd(); - bool m_hasView; + bool has_view_; - SegmentedString m_originalSourceForTransform; + SegmentedString original_source_for_transform_; - xmlParserCtxtPtr context() const { - return m_context ? m_context->context() : 0; + xmlParserCtxtPtr Context() const { + return context_ ? context_->Context() : 0; } - RefPtr<XMLParserContext> m_context; - Deque<std::unique_ptr<PendingCallback>> m_pendingCallbacks; - Vector<xmlChar> m_bufferedText; + RefPtr<XMLParserContext> context_; + Deque<std::unique_ptr<PendingCallback>> pending_callbacks_; + Vector<xmlChar> buffered_text_; - Member<ContainerNode> m_currentNode; - HeapVector<Member<ContainerNode>> m_currentNodeStack; + Member<ContainerNode> current_node_; + HeapVector<Member<ContainerNode>> current_node_stack_; - Member<Text> m_leafTextNode; + Member<Text> leaf_text_node_; - bool m_isCurrentlyParsing8BitChunk; - bool m_sawError; - bool m_sawCSS; - bool m_sawXSLTransform; - bool m_sawFirstElement; - bool m_isXHTMLDocument; - bool m_parserPaused; - bool m_requestingScript; - bool m_finishCalled; + bool is_currently_parsing8_bit_chunk_; + bool saw_error_; + bool saw_css_; + bool saw_xsl_transform_; + bool saw_first_element_; + bool is_xhtml_document_; + bool parser_paused_; + bool requesting_script_; + bool finish_called_; - XMLErrors m_xmlErrors; + XMLErrors xml_errors_; - Member<ScriptResource> m_pendingScript; - Member<Element> m_scriptElement; - TextPosition m_scriptStartPosition; - double m_parserBlockingPendingScriptLoadStartTime; + Member<ScriptResource> pending_script_; + Member<Element> script_element_; + TextPosition script_start_position_; + double parser_blocking_pending_script_load_start_time_; - bool m_parsingFragment; - AtomicString m_defaultNamespaceURI; + bool parsing_fragment_; + AtomicString default_namespace_uri_; typedef HashMap<AtomicString, AtomicString> PrefixForNamespaceMap; - PrefixForNamespaceMap m_prefixToNamespaceMap; - SegmentedString m_pendingSrc; + PrefixForNamespaceMap prefix_to_namespace_map_; + SegmentedString pending_src_; }; -xmlDocPtr xmlDocPtrForString(Document*, +xmlDocPtr XmlDocPtrForString(Document*, const String& source, const String& url); -HashMap<String, String> parseAttributes(const String&, bool& attrsOK); +HashMap<String, String> ParseAttributes(const String&, bool& attrs_ok); } // namespace blink diff --git a/chromium/third_party/WebKit/Source/core/xml/parser/XMLDocumentParserScope.cpp b/chromium/third_party/WebKit/Source/core/xml/parser/XMLDocumentParserScope.cpp index f9494fc787c..559cf11a4ce 100644 --- a/chromium/third_party/WebKit/Source/core/xml/parser/XMLDocumentParserScope.cpp +++ b/chromium/third_party/WebKit/Source/core/xml/parser/XMLDocumentParserScope.cpp @@ -27,36 +27,36 @@ namespace blink { -Document* XMLDocumentParserScope::currentDocument = 0; +Document* XMLDocumentParserScope::current_document_ = 0; XMLDocumentParserScope::XMLDocumentParserScope(Document* document) - : m_oldDocument(currentDocument), - m_oldGenericErrorFunc(xmlGenericError), - m_oldStructuredErrorFunc(xmlStructuredError), - m_oldErrorContext(xmlGenericErrorContext) { - currentDocument = document; + : old_document_(current_document_), + old_generic_error_func_(xmlGenericError), + old_structured_error_func_(xmlStructuredError), + old_error_context_(xmlGenericErrorContext) { + current_document_ = document; } XMLDocumentParserScope::XMLDocumentParserScope( Document* document, - xmlGenericErrorFunc genericErrorFunc, - xmlStructuredErrorFunc structuredErrorFunc, - void* errorContext) - : m_oldDocument(currentDocument), - m_oldGenericErrorFunc(xmlGenericError), - m_oldStructuredErrorFunc(xmlStructuredError), - m_oldErrorContext(xmlGenericErrorContext) { - currentDocument = document; - if (genericErrorFunc) - xmlSetGenericErrorFunc(errorContext, genericErrorFunc); - if (structuredErrorFunc) - xmlSetStructuredErrorFunc(errorContext, structuredErrorFunc); + xmlGenericErrorFunc generic_error_func, + xmlStructuredErrorFunc structured_error_func, + void* error_context) + : old_document_(current_document_), + old_generic_error_func_(xmlGenericError), + old_structured_error_func_(xmlStructuredError), + old_error_context_(xmlGenericErrorContext) { + current_document_ = document; + if (generic_error_func) + xmlSetGenericErrorFunc(error_context, generic_error_func); + if (structured_error_func) + xmlSetStructuredErrorFunc(error_context, structured_error_func); } XMLDocumentParserScope::~XMLDocumentParserScope() { - currentDocument = m_oldDocument; - xmlSetGenericErrorFunc(m_oldErrorContext, m_oldGenericErrorFunc); - xmlSetStructuredErrorFunc(m_oldErrorContext, m_oldStructuredErrorFunc); + current_document_ = old_document_; + xmlSetGenericErrorFunc(old_error_context_, old_generic_error_func_); + xmlSetStructuredErrorFunc(old_error_context_, old_structured_error_func_); } } // namespace blink diff --git a/chromium/third_party/WebKit/Source/core/xml/parser/XMLDocumentParserScope.h b/chromium/third_party/WebKit/Source/core/xml/parser/XMLDocumentParserScope.h index d911690afa9..66b29c60ed1 100644 --- a/chromium/third_party/WebKit/Source/core/xml/parser/XMLDocumentParserScope.h +++ b/chromium/third_party/WebKit/Source/core/xml/parser/XMLDocumentParserScope.h @@ -26,9 +26,9 @@ #ifndef XMLDocumentParserScope_h #define XMLDocumentParserScope_h -#include "platform/heap/Handle.h" -#include "wtf/Noncopyable.h" #include <libxml/xmlerror.h> +#include "platform/heap/Handle.h" +#include "platform/wtf/Noncopyable.h" namespace blink { @@ -43,17 +43,17 @@ class XMLDocumentParserScope { XMLDocumentParserScope(Document*, xmlGenericErrorFunc, xmlStructuredErrorFunc = 0, - void* errorContext = 0); + void* error_context = 0); ~XMLDocumentParserScope(); - static Document* currentDocument; + static Document* current_document_; private: - Member<Document> m_oldDocument; + Member<Document> old_document_; - xmlGenericErrorFunc m_oldGenericErrorFunc; - xmlStructuredErrorFunc m_oldStructuredErrorFunc; - void* m_oldErrorContext; + xmlGenericErrorFunc old_generic_error_func_; + xmlStructuredErrorFunc old_structured_error_func_; + void* old_error_context_; }; } // namespace blink diff --git a/chromium/third_party/WebKit/Source/core/xml/parser/XMLErrors.cpp b/chromium/third_party/WebKit/Source/core/xml/parser/XMLErrors.cpp index 4fcb54a67c0..f2ddc1fb69c 100644 --- a/chromium/third_party/WebKit/Source/core/xml/parser/XMLErrors.cpp +++ b/chromium/third_party/WebKit/Source/core/xml/parser/XMLErrors.cpp @@ -34,159 +34,159 @@ #include "core/dom/Element.h" #include "core/dom/Text.h" #include "core/xml/DocumentXSLT.h" -#include "wtf/text/WTFString.h" +#include "platform/wtf/text/WTFString.h" namespace blink { using namespace HTMLNames; -const int maxErrors = 25; +const int kMaxErrors = 25; XMLErrors::XMLErrors(Document* document) - : m_document(document), - m_errorCount(0), - m_lastErrorPosition(TextPosition::belowRangePosition()) {} + : document_(document), + error_count_(0), + last_error_position_(TextPosition::BelowRangePosition()) {} DEFINE_TRACE(XMLErrors) { - visitor->trace(m_document); + visitor->Trace(document_); } -void XMLErrors::handleError(ErrorType type, +void XMLErrors::HandleError(ErrorType type, const char* message, - int lineNumber, - int columnNumber) { - handleError(type, message, - TextPosition(OrdinalNumber::fromOneBasedInt(lineNumber), - OrdinalNumber::fromOneBasedInt(columnNumber))); + int line_number, + int column_number) { + HandleError(type, message, + TextPosition(OrdinalNumber::FromOneBasedInt(line_number), + OrdinalNumber::FromOneBasedInt(column_number))); } -void XMLErrors::handleError(ErrorType type, +void XMLErrors::HandleError(ErrorType type, const char* message, TextPosition position) { - if (type == ErrorTypeFatal || - (m_errorCount < maxErrors && - m_lastErrorPosition.m_line != position.m_line && - m_lastErrorPosition.m_column != position.m_column)) { + if (type == kErrorTypeFatal || + (error_count_ < kMaxErrors && + last_error_position_.line_ != position.line_ && + last_error_position_.column_ != position.column_)) { switch (type) { - case ErrorTypeWarning: - appendErrorMessage("warning", position, message); + case kErrorTypeWarning: + AppendErrorMessage("warning", position, message); break; - case ErrorTypeFatal: - case ErrorTypeNonFatal: - appendErrorMessage("error", position, message); + case kErrorTypeFatal: + case kErrorTypeNonFatal: + AppendErrorMessage("error", position, message); } - m_lastErrorPosition = position; - ++m_errorCount; + last_error_position_ = position; + ++error_count_; } } -void XMLErrors::appendErrorMessage(const String& typeString, +void XMLErrors::AppendErrorMessage(const String& type_string, TextPosition position, const char* message) { // <typeString> on line <lineNumber> at column <columnNumber>: <message> - m_errorMessages.append(typeString); - m_errorMessages.append(" on line "); - m_errorMessages.appendNumber(position.m_line.oneBasedInt()); - m_errorMessages.append(" at column "); - m_errorMessages.appendNumber(position.m_column.oneBasedInt()); - m_errorMessages.append(": "); - m_errorMessages.append(message); + error_messages_.Append(type_string); + error_messages_.Append(" on line "); + error_messages_.AppendNumber(position.line_.OneBasedInt()); + error_messages_.Append(" at column "); + error_messages_.AppendNumber(position.column_.OneBasedInt()); + error_messages_.Append(": "); + error_messages_.Append(message); } -static inline Element* createXHTMLParserErrorHeader( +static inline Element* CreateXHTMLParserErrorHeader( Document* doc, - const String& errorMessages) { - Element* reportElement = doc->createElement( - QualifiedName(nullAtom, "parsererror", xhtmlNamespaceURI), - CreatedByParser); + const String& error_messages) { + Element* report_element = doc->createElement( + QualifiedName(g_null_atom, "parsererror", xhtmlNamespaceURI), + kCreatedByParser); - Vector<Attribute> reportAttributes; - reportAttributes.push_back(Attribute( + Vector<Attribute> report_attributes; + report_attributes.push_back(Attribute( styleAttr, "display: block; white-space: pre; border: 2px solid #c77; padding: 0 " "1em 0 1em; margin: 1em; background-color: #fdd; color: black")); - reportElement->parserSetAttributes(reportAttributes); + report_element->ParserSetAttributes(report_attributes); - Element* h3 = doc->createElement(h3Tag, CreatedByParser); - reportElement->parserAppendChild(h3); - h3->parserAppendChild( + Element* h3 = doc->createElement(h3Tag, kCreatedByParser); + report_element->ParserAppendChild(h3); + h3->ParserAppendChild( doc->createTextNode("This page contains the following errors:")); - Element* fixed = doc->createElement(divTag, CreatedByParser); - Vector<Attribute> fixedAttributes; - fixedAttributes.push_back( + Element* fixed = doc->createElement(divTag, kCreatedByParser); + Vector<Attribute> fixed_attributes; + fixed_attributes.push_back( Attribute(styleAttr, "font-family:monospace;font-size:12px")); - fixed->parserSetAttributes(fixedAttributes); - reportElement->parserAppendChild(fixed); + fixed->ParserSetAttributes(fixed_attributes); + report_element->ParserAppendChild(fixed); - fixed->parserAppendChild(doc->createTextNode(errorMessages)); + fixed->ParserAppendChild(doc->createTextNode(error_messages)); - h3 = doc->createElement(h3Tag, CreatedByParser); - reportElement->parserAppendChild(h3); - h3->parserAppendChild(doc->createTextNode( + h3 = doc->createElement(h3Tag, kCreatedByParser); + report_element->ParserAppendChild(h3); + h3->ParserAppendChild(doc->createTextNode( "Below is a rendering of the page up to the first error.")); - return reportElement; + return report_element; } -void XMLErrors::insertErrorMessageBlock() { +void XMLErrors::InsertErrorMessageBlock() { // One or more errors occurred during parsing of the code. Display an error // block to the user above the normal content (the DOM tree is created // manually and includes line/col info regarding where the errors are located) // Create elements for display - Element* documentElement = m_document->documentElement(); - if (!documentElement) { - Element* rootElement = m_document->createElement(htmlTag, CreatedByParser); - Element* body = m_document->createElement(bodyTag, CreatedByParser); - rootElement->parserAppendChild(body); - m_document->parserAppendChild(rootElement); - documentElement = body; - } else if (documentElement->namespaceURI() == SVGNames::svgNamespaceURI) { - Element* rootElement = m_document->createElement(htmlTag, CreatedByParser); - Element* head = m_document->createElement(headTag, CreatedByParser); - Element* style = m_document->createElement(styleTag, CreatedByParser); - head->parserAppendChild(style); - style->parserAppendChild( - m_document->createTextNode("html, body { height: 100% } parsererror + " - "svg { width: 100%; height: 100% }")); - style->finishParsingChildren(); - rootElement->parserAppendChild(head); - Element* body = m_document->createElement(bodyTag, CreatedByParser); - rootElement->parserAppendChild(body); - - m_document->parserRemoveChild(*documentElement); - - body->parserAppendChild(documentElement); - m_document->parserAppendChild(rootElement); - - documentElement = body; + Element* document_element = document_->documentElement(); + if (!document_element) { + Element* root_element = document_->createElement(htmlTag, kCreatedByParser); + Element* body = document_->createElement(bodyTag, kCreatedByParser); + root_element->ParserAppendChild(body); + document_->ParserAppendChild(root_element); + document_element = body; + } else if (document_element->namespaceURI() == SVGNames::svgNamespaceURI) { + Element* root_element = document_->createElement(htmlTag, kCreatedByParser); + Element* head = document_->createElement(headTag, kCreatedByParser); + Element* style = document_->createElement(styleTag, kCreatedByParser); + head->ParserAppendChild(style); + style->ParserAppendChild( + document_->createTextNode("html, body { height: 100% } parsererror + " + "svg { width: 100%; height: 100% }")); + style->FinishParsingChildren(); + root_element->ParserAppendChild(head); + Element* body = document_->createElement(bodyTag, kCreatedByParser); + root_element->ParserAppendChild(body); + + document_->ParserRemoveChild(*document_element); + + body->ParserAppendChild(document_element); + document_->ParserAppendChild(root_element); + + document_element = body; } - String errorMessages = m_errorMessages.toString(); - Element* reportElement = - createXHTMLParserErrorHeader(m_document, errorMessages); + String error_messages = error_messages_.ToString(); + Element* report_element = + CreateXHTMLParserErrorHeader(document_, error_messages); - if (DocumentXSLT::hasTransformSourceDocument(*m_document)) { + if (DocumentXSLT::HasTransformSourceDocument(*document_)) { Vector<Attribute> attributes; attributes.push_back(Attribute(styleAttr, "white-space: normal")); - Element* paragraph = m_document->createElement(pTag, CreatedByParser); - paragraph->parserSetAttributes(attributes); - paragraph->parserAppendChild(m_document->createTextNode( + Element* paragraph = document_->createElement(pTag, kCreatedByParser); + paragraph->ParserSetAttributes(attributes); + paragraph->ParserAppendChild(document_->createTextNode( "This document was created as the result of an XSL transformation. The " "line and column numbers given are from the transformed result.")); - reportElement->parserAppendChild(paragraph); + report_element->ParserAppendChild(paragraph); } - Node* firstChild = documentElement->firstChild(); - if (firstChild) - documentElement->parserInsertBefore(reportElement, *firstChild); + Node* first_child = document_element->FirstChild(); + if (first_child) + document_element->ParserInsertBefore(report_element, *first_child); else - documentElement->parserAppendChild(reportElement); + document_element->ParserAppendChild(report_element); // FIXME: Why do we need to call this manually? - m_document->updateStyleAndLayoutTree(); + document_->UpdateStyleAndLayoutTree(); } } // namespace blink diff --git a/chromium/third_party/WebKit/Source/core/xml/parser/XMLErrors.h b/chromium/third_party/WebKit/Source/core/xml/parser/XMLErrors.h index 6e0d28b4db1..669282a1b7e 100644 --- a/chromium/third_party/WebKit/Source/core/xml/parser/XMLErrors.h +++ b/chromium/third_party/WebKit/Source/core/xml/parser/XMLErrors.h @@ -30,8 +30,8 @@ #define XMLErrors_h #include "platform/heap/Handle.h" -#include "wtf/text/StringBuilder.h" -#include "wtf/text/TextPosition.h" +#include "platform/wtf/text/StringBuilder.h" +#include "platform/wtf/text/TextPosition.h" namespace blink { @@ -45,25 +45,25 @@ class XMLErrors { DECLARE_TRACE(); // Exposed for callbacks: - enum ErrorType { ErrorTypeWarning, ErrorTypeNonFatal, ErrorTypeFatal }; - void handleError(ErrorType, + enum ErrorType { kErrorTypeWarning, kErrorTypeNonFatal, kErrorTypeFatal }; + void HandleError(ErrorType, const char* message, - int lineNumber, - int columnNumber); - void handleError(ErrorType, const char* message, TextPosition); + int line_number, + int column_number); + void HandleError(ErrorType, const char* message, TextPosition); - void insertErrorMessageBlock(); + void InsertErrorMessageBlock(); private: - void appendErrorMessage(const String& typeString, + void AppendErrorMessage(const String& type_string, TextPosition, const char* message); - Member<Document> m_document; + Member<Document> document_; - int m_errorCount; - TextPosition m_lastErrorPosition; - StringBuilder m_errorMessages; + int error_count_; + TextPosition last_error_position_; + StringBuilder error_messages_; }; } // namespace blink diff --git a/chromium/third_party/WebKit/Source/core/xml/parser/XMLParserInput.h b/chromium/third_party/WebKit/Source/core/xml/parser/XMLParserInput.h index 8d3c8e01d96..21d91c35a8c 100644 --- a/chromium/third_party/WebKit/Source/core/xml/parser/XMLParserInput.h +++ b/chromium/third_party/WebKit/Source/core/xml/parser/XMLParserInput.h @@ -31,8 +31,8 @@ #ifndef XMLParserInput_h #define XMLParserInput_h -#include "wtf/Allocator.h" -#include "wtf/text/WTFString.h" +#include "platform/wtf/Allocator.h" +#include "platform/wtf/text/WTFString.h" namespace blink { @@ -41,34 +41,34 @@ class XMLParserInput { public: explicit XMLParserInput(const String& source) - : m_source(source), m_encoding(0), m_data(0), m_size(0) { - if (m_source.isEmpty()) + : source_(source), encoding_(0), data_(0), size_(0) { + if (source_.IsEmpty()) return; - const UChar BOM = 0xFEFF; - const unsigned char BOMHighByte = - *reinterpret_cast<const unsigned char*>(&BOM); + const UChar kBOM = 0xFEFF; + const unsigned char bom_high_byte = + *reinterpret_cast<const unsigned char*>(&kBOM); - if (m_source.is8Bit()) { - m_encoding = "iso-8859-1"; - m_data = reinterpret_cast<const char*>(m_source.characters8()); - m_size = m_source.length() * sizeof(LChar); + if (source_.Is8Bit()) { + encoding_ = "iso-8859-1"; + data_ = reinterpret_cast<const char*>(source_.Characters8()); + size_ = source_.length() * sizeof(LChar); } else { - m_encoding = BOMHighByte == 0xFF ? "UTF-16LE" : "UTF-16BE"; - m_data = reinterpret_cast<const char*>(m_source.characters16()); - m_size = m_source.length() * sizeof(UChar); + encoding_ = bom_high_byte == 0xFF ? "UTF-16LE" : "UTF-16BE"; + data_ = reinterpret_cast<const char*>(source_.Characters16()); + size_ = source_.length() * sizeof(UChar); } } - const char* encoding() const { return m_encoding; } - const char* data() const { return m_data; } - int size() const { return m_size; } + const char* Encoding() const { return encoding_; } + const char* Data() const { return data_; } + int size() const { return size_; } private: - String m_source; - const char* m_encoding; - const char* m_data; - int m_size; + String source_; + const char* encoding_; + const char* data_; + int size_; }; } // namespace blink |