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"
33 #include "ExceptionCode.h"
34 #include "XPathEvaluator.h"
35 #include "XPathException.h"
36 #include "XPathNSResolver.h"
37 #include "XPathStep.h"
38 #include <wtf/StdLibExtras.h>
39 #include <wtf/text/StringHash.h>
41 int xpathyyparse(void*);
44 using namespace Unicode;
51 #include "XPathGrammar.h"
53 Parser* Parser::currentParser = 0;
55 enum XMLCat { NameStart, NameCont, NotPartOfName };
57 typedef HashMap<String, Step::Axis> AxisNamesMap;
59 static XMLCat charCat(UChar aChar)
61 //### might need to add some special cases from the XML spec.
66 if (aChar == '.' || aChar == '-')
68 CharCategory category = Unicode::category(aChar);
69 if (category & (Letter_Uppercase | Letter_Lowercase | Letter_Other | Letter_Titlecase | Number_Letter))
71 if (category & (Mark_NonSpacing | Mark_SpacingCombining | Mark_Enclosing | Letter_Modifier | Number_DecimalDigit))
76 static void setUpAxisNamesMap(AxisNamesMap& axisNames)
82 const AxisName axisNameList[] = {
83 { "ancestor", Step::AncestorAxis },
84 { "ancestor-or-self", Step::AncestorOrSelfAxis },
85 { "attribute", Step::AttributeAxis },
86 { "child", Step::ChildAxis },
87 { "descendant", Step::DescendantAxis },
88 { "descendant-or-self", Step::DescendantOrSelfAxis },
89 { "following", Step::FollowingAxis },
90 { "following-sibling", Step::FollowingSiblingAxis },
91 { "namespace", Step::NamespaceAxis },
92 { "parent", Step::ParentAxis },
93 { "preceding", Step::PrecedingAxis },
94 { "preceding-sibling", Step::PrecedingSiblingAxis },
95 { "self", Step::SelfAxis }
97 for (unsigned i = 0; i < sizeof(axisNameList) / sizeof(axisNameList[0]); ++i)
98 axisNames.set(axisNameList[i].name, axisNameList[i].axis);
101 static bool isAxisName(const String& name, Step::Axis& type)
103 DEFINE_STATIC_LOCAL(AxisNamesMap, axisNames, ());
105 if (axisNames.isEmpty())
106 setUpAxisNamesMap(axisNames);
108 AxisNamesMap::iterator it = axisNames.find(name);
109 if (it == axisNames.end())
115 static bool isNodeTypeName(const String& name)
117 DEFINE_STATIC_LOCAL(HashSet<String>, nodeTypeNames, ());
118 if (nodeTypeNames.isEmpty()) {
119 nodeTypeNames.add("comment");
120 nodeTypeNames.add("text");
121 nodeTypeNames.add("processing-instruction");
122 nodeTypeNames.add("node");
124 return nodeTypeNames.contains(name);
127 // Returns whether the current token can possibly be a binary operator, given
128 // the previous token. Necessary to disambiguate some of the operators
129 // (* (multiply), div, and, or, mod) in the [32] Operator rule
130 // (check http://www.w3.org/TR/xpath#exprlex).
131 bool Parser::isBinaryOperatorContext() const
133 switch (m_lastTokenType) {
135 case '@': case AXISNAME: case '(': case '[': case ',':
136 case AND: case OR: case MULOP:
137 case '/': case SLASHSLASH: case '|': case PLUS: case MINUS:
138 case EQOP: case RELOP:
145 void Parser::skipWS()
147 while (m_nextPos < m_data.length() && isSpaceOrNewline(m_data[m_nextPos]))
151 Token Parser::makeTokenAndAdvance(int code, int advance)
153 m_nextPos += advance;
157 Token Parser::makeTokenAndAdvance(int code, NumericOp::Opcode val, int advance)
159 m_nextPos += advance;
160 return Token(code, val);
163 Token Parser::makeTokenAndAdvance(int code, EqTestOp::Opcode val, int advance)
165 m_nextPos += advance;
166 return Token(code, val);
169 // Returns next char if it's there and interesting, 0 otherwise
170 char Parser::peekAheadHelper()
172 if (m_nextPos + 1 >= m_data.length())
174 UChar next = m_data[m_nextPos + 1];
180 char Parser::peekCurHelper()
182 if (m_nextPos >= m_data.length())
184 UChar next = m_data[m_nextPos];
190 Token Parser::lexString()
192 UChar delimiter = m_data[m_nextPos];
193 int startPos = m_nextPos + 1;
195 for (m_nextPos = startPos; m_nextPos < m_data.length(); ++m_nextPos) {
196 if (m_data[m_nextPos] == delimiter) {
197 String value = m_data.substring(startPos, m_nextPos - startPos);
200 ++m_nextPos; // Consume the char.
201 return Token(LITERAL, value);
205 // Ouch, went off the end -- report error.
206 return Token(XPATH_ERROR);
209 Token Parser::lexNumber()
211 int startPos = m_nextPos;
212 bool seenDot = false;
214 // Go until end or a non-digits character.
215 for (; m_nextPos < m_data.length(); ++m_nextPos) {
216 UChar aChar = m_data[m_nextPos];
217 if (aChar >= 0xff) break;
219 if (aChar < '0' || aChar > '9') {
220 if (aChar == '.' && !seenDot)
227 return Token(NUMBER, m_data.substring(startPos, m_nextPos - startPos));
230 bool Parser::lexNCName(String& name)
232 int startPos = m_nextPos;
233 if (m_nextPos >= m_data.length())
236 if (charCat(m_data[m_nextPos]) != NameStart)
239 // Keep going until we get a character that's not good for names.
240 for (; m_nextPos < m_data.length(); ++m_nextPos)
241 if (charCat(m_data[m_nextPos]) == NotPartOfName)
244 name = m_data.substring(startPos, m_nextPos - startPos);
248 bool Parser::lexQName(String& name)
256 // If the next character is :, what we just got it the prefix, if not,
257 // it's the whole thing.
258 if (peekAheadHelper() != ':') {
267 name = n1 + ":" + n2;
271 Token Parser::nextTokenInternal()
275 if (m_nextPos >= m_data.length())
278 char code = peekCurHelper();
280 case '(': case ')': case '[': case ']':
281 case '@': case ',': case '|':
282 return makeTokenAndAdvance(code);
286 case '0': case '1': case '2': case '3': case '4':
287 case '5': case '6': case '7': case '8': case '9':
290 char next = peekAheadHelper();
292 return makeTokenAndAdvance(DOTDOT, 2);
293 if (next >= '0' && next <= '9')
295 return makeTokenAndAdvance('.');
298 if (peekAheadHelper() == '/')
299 return makeTokenAndAdvance(SLASHSLASH, 2);
300 return makeTokenAndAdvance('/');
302 return makeTokenAndAdvance(PLUS);
304 return makeTokenAndAdvance(MINUS);
306 return makeTokenAndAdvance(EQOP, EqTestOp::OP_EQ);
308 if (peekAheadHelper() == '=')
309 return makeTokenAndAdvance(EQOP, EqTestOp::OP_NE, 2);
310 return Token(XPATH_ERROR);
312 if (peekAheadHelper() == '=')
313 return makeTokenAndAdvance(RELOP, EqTestOp::OP_LE, 2);
314 return makeTokenAndAdvance(RELOP, EqTestOp::OP_LT);
316 if (peekAheadHelper() == '=')
317 return makeTokenAndAdvance(RELOP, EqTestOp::OP_GE, 2);
318 return makeTokenAndAdvance(RELOP, EqTestOp::OP_GT);
320 if (isBinaryOperatorContext())
321 return makeTokenAndAdvance(MULOP, NumericOp::OP_Mul);
323 return Token(NAMETEST, "*");
324 case '$': { // $ QName
328 return Token(XPATH_ERROR);
329 return Token(VARIABLEREFERENCE, name);
334 if (!lexNCName(name))
335 return Token(XPATH_ERROR);
338 // If we're in an operator context, check for any operator names
339 if (isBinaryOperatorContext()) {
340 if (name == "and") //### hash?
345 return Token(MULOP, NumericOp::OP_Mod);
347 return Token(MULOP, NumericOp::OP_Div);
350 // See whether we are at a :
351 if (peekCurHelper() == ':') {
353 // Any chance it's an axis name?
354 if (peekCurHelper() == ':') {
357 //It might be an axis name.
359 if (isAxisName(name, axis))
360 return Token(AXISNAME, axis);
361 // Ugh, :: is only valid in axis names -> error
362 return Token(XPATH_ERROR);
365 // Seems like this is a fully qualified qname, or perhaps the * modified one from NameTest
367 if (peekCurHelper() == '*') {
369 return Token(NAMETEST, name + ":*");
372 // Make a full qname.
375 return Token(XPATH_ERROR);
377 name = name + ":" + n2;
381 if (peekCurHelper() == '(') {
382 //note: we don't swallow the (here!
384 //either node type of function name
385 if (isNodeTypeName(name)) {
386 if (name == "processing-instruction")
387 return Token(PI, name);
389 return Token(NODETYPE, name);
391 //must be a function name.
392 return Token(FUNCTIONNAME, name);
395 // At this point, it must be NAMETEST.
396 return Token(NAMETEST, name);
399 Token Parser::nextToken()
401 Token toRet = nextTokenInternal();
402 m_lastTokenType = toRet.type;
415 void Parser::reset(const String& data)
422 m_gotNamespaceError = false;
425 int Parser::lex(void* data)
427 YYSTYPE* yylval = static_cast<YYSTYPE*>(data);
428 Token tok = nextToken();
432 yylval->axis = tok.axis;
435 yylval->numop = tok.numop;
439 yylval->eqop = tok.eqop;
445 case VARIABLEREFERENCE:
448 yylval->str = new String(tok.str);
449 registerString(yylval->str);
456 bool Parser::expandQName(const String& qName, String& localName, String& namespaceURI)
458 size_t colon = qName.find(':');
459 if (colon != notFound) {
462 namespaceURI = m_resolver->lookupNamespaceURI(qName.left(colon));
463 if (namespaceURI.isNull())
465 localName = qName.substring(colon + 1);
472 Expression* Parser::parseStatement(const String& statement, PassRefPtr<XPathNSResolver> resolver, ExceptionCode& ec)
476 m_resolver = resolver;
478 Parser* oldParser = currentParser;
479 currentParser = this;
480 int parseError = xpathyyparse(this);
481 currentParser = oldParser;
484 deleteAllValues(m_parseNodes);
485 m_parseNodes.clear();
487 HashSet<Vector<Predicate*>*>::iterator pend = m_predicateVectors.end();
488 for (HashSet<Vector<Predicate*>*>::iterator it = m_predicateVectors.begin(); it != pend; ++it) {
489 deleteAllValues(**it);
492 m_predicateVectors.clear();
494 HashSet<Vector<Expression*>*>::iterator eend = m_expressionVectors.end();
495 for (HashSet<Vector<Expression*>*>::iterator it = m_expressionVectors.begin(); it != eend; ++it) {
496 deleteAllValues(**it);
499 m_expressionVectors.clear();
501 deleteAllValues(m_strings);
504 deleteAllValues(m_nodeTests);
509 if (m_gotNamespaceError)
512 ec = XPathException::INVALID_EXPRESSION_ERR;
516 ASSERT(m_parseNodes.size() == 1);
517 ASSERT(*m_parseNodes.begin() == m_topExpr);
518 ASSERT(m_expressionVectors.size() == 0);
519 ASSERT(m_predicateVectors.size() == 0);
520 ASSERT(m_strings.size() == 0);
521 ASSERT(m_nodeTests.size() == 0);
523 m_parseNodes.clear();
524 Expression* result = m_topExpr;
530 void Parser::registerParseNode(ParseNode* node)
535 ASSERT(!m_parseNodes.contains(node));
537 m_parseNodes.add(node);
540 void Parser::unregisterParseNode(ParseNode* node)
545 ASSERT(m_parseNodes.contains(node));
547 m_parseNodes.remove(node);
550 void Parser::registerPredicateVector(Vector<Predicate*>* vector)
555 ASSERT(!m_predicateVectors.contains(vector));
557 m_predicateVectors.add(vector);
560 void Parser::deletePredicateVector(Vector<Predicate*>* vector)
565 ASSERT(m_predicateVectors.contains(vector));
567 m_predicateVectors.remove(vector);
572 void Parser::registerExpressionVector(Vector<Expression*>* vector)
577 ASSERT(!m_expressionVectors.contains(vector));
579 m_expressionVectors.add(vector);
582 void Parser::deleteExpressionVector(Vector<Expression*>* vector)
587 ASSERT(m_expressionVectors.contains(vector));
589 m_expressionVectors.remove(vector);
593 void Parser::registerString(String* s)
598 ASSERT(!m_strings.contains(s));
603 void Parser::deleteString(String* s)
608 ASSERT(m_strings.contains(s));
614 void Parser::registerNodeTest(Step::NodeTest* t)
619 ASSERT(!m_nodeTests.contains(t));
624 void Parser::deleteNodeTest(Step::NodeTest* t)
629 ASSERT(m_nodeTests.contains(t));
631 m_nodeTests.remove(t);
638 #endif // ENABLE(XPATH)