2 * Copyright 2005 Maksim Orlovich <maksim@kde.org>
3 * Copyright (C) 2006 Apple Computer, Inc.
4 * Copyright (C) 2007 Alexey Proskuryakov <ap@webkit.org>
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 #include "XPathParser.h"
31 #include "ExceptionCode.h"
32 #include "XPathEvaluator.h"
33 #include "XPathException.h"
34 #include "XPathNSResolver.h"
35 #include "XPathStep.h"
36 #include <wtf/StdLibExtras.h>
37 #include <wtf/text/StringHash.h>
39 int xpathyyparse(void*);
42 using namespace Unicode;
49 #include "XPathGrammar.h"
51 Parser* Parser::currentParser = 0;
53 enum XMLCat { NameStart, NameCont, NotPartOfName };
55 typedef HashMap<String, Step::Axis> AxisNamesMap;
57 static XMLCat charCat(UChar aChar)
59 //### might need to add some special cases from the XML spec.
64 if (aChar == '.' || aChar == '-')
66 CharCategory category = Unicode::category(aChar);
67 if (category & (Letter_Uppercase | Letter_Lowercase | Letter_Other | Letter_Titlecase | Number_Letter))
69 if (category & (Mark_NonSpacing | Mark_SpacingCombining | Mark_Enclosing | Letter_Modifier | Number_DecimalDigit))
74 static void setUpAxisNamesMap(AxisNamesMap& axisNames)
80 const AxisName axisNameList[] = {
81 { "ancestor", Step::AncestorAxis },
82 { "ancestor-or-self", Step::AncestorOrSelfAxis },
83 { "attribute", Step::AttributeAxis },
84 { "child", Step::ChildAxis },
85 { "descendant", Step::DescendantAxis },
86 { "descendant-or-self", Step::DescendantOrSelfAxis },
87 { "following", Step::FollowingAxis },
88 { "following-sibling", Step::FollowingSiblingAxis },
89 { "namespace", Step::NamespaceAxis },
90 { "parent", Step::ParentAxis },
91 { "preceding", Step::PrecedingAxis },
92 { "preceding-sibling", Step::PrecedingSiblingAxis },
93 { "self", Step::SelfAxis }
95 for (unsigned i = 0; i < sizeof(axisNameList) / sizeof(axisNameList[0]); ++i)
96 axisNames.set(axisNameList[i].name, axisNameList[i].axis);
99 static bool isAxisName(const String& name, Step::Axis& type)
101 DEFINE_STATIC_LOCAL(AxisNamesMap, axisNames, ());
103 if (axisNames.isEmpty())
104 setUpAxisNamesMap(axisNames);
106 AxisNamesMap::iterator it = axisNames.find(name);
107 if (it == axisNames.end())
113 static bool isNodeTypeName(const String& name)
115 DEFINE_STATIC_LOCAL(HashSet<String>, nodeTypeNames, ());
116 if (nodeTypeNames.isEmpty()) {
117 nodeTypeNames.add("comment");
118 nodeTypeNames.add("text");
119 nodeTypeNames.add("processing-instruction");
120 nodeTypeNames.add("node");
122 return nodeTypeNames.contains(name);
125 // Returns whether the current token can possibly be a binary operator, given
126 // the previous token. Necessary to disambiguate some of the operators
127 // (* (multiply), div, and, or, mod) in the [32] Operator rule
128 // (check http://www.w3.org/TR/xpath#exprlex).
129 bool Parser::isBinaryOperatorContext() const
131 switch (m_lastTokenType) {
133 case '@': case AXISNAME: case '(': case '[': case ',':
134 case AND: case OR: case MULOP:
135 case '/': case SLASHSLASH: case '|': case PLUS: case MINUS:
136 case EQOP: case RELOP:
143 void Parser::skipWS()
145 while (m_nextPos < m_data.length() && isSpaceOrNewline(m_data[m_nextPos]))
149 Token Parser::makeTokenAndAdvance(int code, int advance)
151 m_nextPos += advance;
155 Token Parser::makeTokenAndAdvance(int code, NumericOp::Opcode val, int advance)
157 m_nextPos += advance;
158 return Token(code, val);
161 Token Parser::makeTokenAndAdvance(int code, EqTestOp::Opcode val, int advance)
163 m_nextPos += advance;
164 return Token(code, val);
167 // Returns next char if it's there and interesting, 0 otherwise
168 char Parser::peekAheadHelper()
170 if (m_nextPos + 1 >= m_data.length())
172 UChar next = m_data[m_nextPos + 1];
178 char Parser::peekCurHelper()
180 if (m_nextPos >= m_data.length())
182 UChar next = m_data[m_nextPos];
188 Token Parser::lexString()
190 UChar delimiter = m_data[m_nextPos];
191 int startPos = m_nextPos + 1;
193 for (m_nextPos = startPos; m_nextPos < m_data.length(); ++m_nextPos) {
194 if (m_data[m_nextPos] == delimiter) {
195 String value = m_data.substring(startPos, m_nextPos - startPos);
198 ++m_nextPos; // Consume the char.
199 return Token(LITERAL, value);
203 // Ouch, went off the end -- report error.
204 return Token(XPATH_ERROR);
207 Token Parser::lexNumber()
209 int startPos = m_nextPos;
210 bool seenDot = false;
212 // Go until end or a non-digits character.
213 for (; m_nextPos < m_data.length(); ++m_nextPos) {
214 UChar aChar = m_data[m_nextPos];
215 if (aChar >= 0xff) break;
217 if (aChar < '0' || aChar > '9') {
218 if (aChar == '.' && !seenDot)
225 return Token(NUMBER, m_data.substring(startPos, m_nextPos - startPos));
228 bool Parser::lexNCName(String& name)
230 int startPos = m_nextPos;
231 if (m_nextPos >= m_data.length())
234 if (charCat(m_data[m_nextPos]) != NameStart)
237 // Keep going until we get a character that's not good for names.
238 for (; m_nextPos < m_data.length(); ++m_nextPos)
239 if (charCat(m_data[m_nextPos]) == NotPartOfName)
242 name = m_data.substring(startPos, m_nextPos - startPos);
246 bool Parser::lexQName(String& name)
254 // If the next character is :, what we just got it the prefix, if not,
255 // it's the whole thing.
256 if (peekAheadHelper() != ':') {
265 name = n1 + ":" + n2;
269 Token Parser::nextTokenInternal()
273 if (m_nextPos >= m_data.length())
276 char code = peekCurHelper();
278 case '(': case ')': case '[': case ']':
279 case '@': case ',': case '|':
280 return makeTokenAndAdvance(code);
284 case '0': case '1': case '2': case '3': case '4':
285 case '5': case '6': case '7': case '8': case '9':
288 char next = peekAheadHelper();
290 return makeTokenAndAdvance(DOTDOT, 2);
291 if (next >= '0' && next <= '9')
293 return makeTokenAndAdvance('.');
296 if (peekAheadHelper() == '/')
297 return makeTokenAndAdvance(SLASHSLASH, 2);
298 return makeTokenAndAdvance('/');
300 return makeTokenAndAdvance(PLUS);
302 return makeTokenAndAdvance(MINUS);
304 return makeTokenAndAdvance(EQOP, EqTestOp::OP_EQ);
306 if (peekAheadHelper() == '=')
307 return makeTokenAndAdvance(EQOP, EqTestOp::OP_NE, 2);
308 return Token(XPATH_ERROR);
310 if (peekAheadHelper() == '=')
311 return makeTokenAndAdvance(RELOP, EqTestOp::OP_LE, 2);
312 return makeTokenAndAdvance(RELOP, EqTestOp::OP_LT);
314 if (peekAheadHelper() == '=')
315 return makeTokenAndAdvance(RELOP, EqTestOp::OP_GE, 2);
316 return makeTokenAndAdvance(RELOP, EqTestOp::OP_GT);
318 if (isBinaryOperatorContext())
319 return makeTokenAndAdvance(MULOP, NumericOp::OP_Mul);
321 return Token(NAMETEST, "*");
322 case '$': { // $ QName
326 return Token(XPATH_ERROR);
327 return Token(VARIABLEREFERENCE, name);
332 if (!lexNCName(name))
333 return Token(XPATH_ERROR);
336 // If we're in an operator context, check for any operator names
337 if (isBinaryOperatorContext()) {
338 if (name == "and") //### hash?
343 return Token(MULOP, NumericOp::OP_Mod);
345 return Token(MULOP, NumericOp::OP_Div);
348 // See whether we are at a :
349 if (peekCurHelper() == ':') {
351 // Any chance it's an axis name?
352 if (peekCurHelper() == ':') {
355 //It might be an axis name.
357 if (isAxisName(name, axis))
358 return Token(AXISNAME, axis);
359 // Ugh, :: is only valid in axis names -> error
360 return Token(XPATH_ERROR);
363 // Seems like this is a fully qualified qname, or perhaps the * modified one from NameTest
365 if (peekCurHelper() == '*') {
367 return Token(NAMETEST, name + ":*");
370 // Make a full qname.
373 return Token(XPATH_ERROR);
375 name = name + ":" + n2;
379 if (peekCurHelper() == '(') {
380 //note: we don't swallow the (here!
382 //either node type of function name
383 if (isNodeTypeName(name)) {
384 if (name == "processing-instruction")
385 return Token(PI, name);
387 return Token(NODETYPE, name);
389 //must be a function name.
390 return Token(FUNCTIONNAME, name);
393 // At this point, it must be NAMETEST.
394 return Token(NAMETEST, name);
397 Token Parser::nextToken()
399 Token toRet = nextTokenInternal();
400 m_lastTokenType = toRet.type;
413 void Parser::reset(const String& data)
420 m_gotNamespaceError = false;
423 int Parser::lex(void* data)
425 YYSTYPE* yylval = static_cast<YYSTYPE*>(data);
426 Token tok = nextToken();
430 yylval->axis = tok.axis;
433 yylval->numop = tok.numop;
437 yylval->eqop = tok.eqop;
443 case VARIABLEREFERENCE:
446 yylval->str = new String(tok.str);
447 registerString(yylval->str);
454 bool Parser::expandQName(const String& qName, String& localName, String& namespaceURI)
456 size_t colon = qName.find(':');
457 if (colon != notFound) {
460 namespaceURI = m_resolver->lookupNamespaceURI(qName.left(colon));
461 if (namespaceURI.isNull())
463 localName = qName.substring(colon + 1);
470 Expression* Parser::parseStatement(const String& statement, PassRefPtr<XPathNSResolver> resolver, ExceptionCode& ec)
474 m_resolver = resolver;
476 Parser* oldParser = currentParser;
477 currentParser = this;
478 int parseError = xpathyyparse(this);
479 currentParser = oldParser;
482 deleteAllValues(m_parseNodes);
483 m_parseNodes.clear();
485 HashSet<Vector<Predicate*>*>::iterator pend = m_predicateVectors.end();
486 for (HashSet<Vector<Predicate*>*>::iterator it = m_predicateVectors.begin(); it != pend; ++it) {
487 deleteAllValues(**it);
490 m_predicateVectors.clear();
492 HashSet<Vector<Expression*>*>::iterator eend = m_expressionVectors.end();
493 for (HashSet<Vector<Expression*>*>::iterator it = m_expressionVectors.begin(); it != eend; ++it) {
494 deleteAllValues(**it);
497 m_expressionVectors.clear();
499 deleteAllValues(m_strings);
502 deleteAllValues(m_nodeTests);
507 if (m_gotNamespaceError)
510 ec = XPathException::INVALID_EXPRESSION_ERR;
514 ASSERT(m_parseNodes.size() == 1);
515 ASSERT(*m_parseNodes.begin() == m_topExpr);
516 ASSERT(m_expressionVectors.size() == 0);
517 ASSERT(m_predicateVectors.size() == 0);
518 ASSERT(m_strings.size() == 0);
519 ASSERT(m_nodeTests.size() == 0);
521 m_parseNodes.clear();
522 Expression* result = m_topExpr;
528 void Parser::registerParseNode(ParseNode* node)
533 ASSERT(!m_parseNodes.contains(node));
535 m_parseNodes.add(node);
538 void Parser::unregisterParseNode(ParseNode* node)
543 ASSERT(m_parseNodes.contains(node));
545 m_parseNodes.remove(node);
548 void Parser::registerPredicateVector(Vector<Predicate*>* vector)
553 ASSERT(!m_predicateVectors.contains(vector));
555 m_predicateVectors.add(vector);
558 void Parser::deletePredicateVector(Vector<Predicate*>* vector)
563 ASSERT(m_predicateVectors.contains(vector));
565 m_predicateVectors.remove(vector);
570 void Parser::registerExpressionVector(Vector<Expression*>* vector)
575 ASSERT(!m_expressionVectors.contains(vector));
577 m_expressionVectors.add(vector);
580 void Parser::deleteExpressionVector(Vector<Expression*>* vector)
585 ASSERT(m_expressionVectors.contains(vector));
587 m_expressionVectors.remove(vector);
591 void Parser::registerString(String* s)
596 ASSERT(!m_strings.contains(s));
601 void Parser::deleteString(String* s)
606 ASSERT(m_strings.contains(s));
612 void Parser::registerNodeTest(Step::NodeTest* t)
617 ASSERT(!m_nodeTests.contains(t));
622 void Parser::deleteNodeTest(Step::NodeTest* t)
627 ASSERT(m_nodeTests.contains(t));
629 m_nodeTests.remove(t);