Parser.php 80.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
<?php
/*
 *  $Id$
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information, see
 * <http://www.doctrine-project.org>.
 */

namespace Doctrine\ORM\Query;

24
use Doctrine\Common\DoctrineException,
25
    Doctrine\ORM\Query;
26 27 28 29 30

/**
 * An LL(*) parser for the context-free grammar of the Doctrine Query Language.
 * Parses a DQL query, reports any errors in it, and generates an AST.
 *
31 32 33 34 35 36 37 38
 * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @link    www.doctrine-project.org
 * @since   2.0
 * @version $Revision: 3938 $
 * @author  Guilherme Blanco <guilhermeblanco@hotmail.com>
 * @author  Jonathan Wage <jonwage@gmail.com>
 * @author  Roman Borschel <roman@code-factory.org>
 * @author  Janne Vanhala <jpvanhal@cc.hut.fi>
39 40 41 42 43 44 45 46 47 48
 */
class Parser
{
    /** Maps registered string function names to class names. */
    private static $_STRING_FUNCTIONS = array(
        'concat' => 'Doctrine\ORM\Query\AST\Functions\ConcatFunction',
        'substring' => 'Doctrine\ORM\Query\AST\Functions\SubstringFunction',
        'trim' => 'Doctrine\ORM\Query\AST\Functions\TrimFunction',
        'lower' => 'Doctrine\ORM\Query\AST\Functions\LowerFunction',
        'upper' => 'Doctrine\ORM\Query\AST\Functions\UpperFunction'
49
    );
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76

    /** Maps registered numeric function names to class names. */
    private static $_NUMERIC_FUNCTIONS = array(
        'length' => 'Doctrine\ORM\Query\AST\Functions\LengthFunction',
        'locate' => 'Doctrine\ORM\Query\AST\Functions\LocateFunction',
        'abs' => 'Doctrine\ORM\Query\AST\Functions\AbsFunction',
        'sqrt' => 'Doctrine\ORM\Query\AST\Functions\SqrtFunction',
        'mod' => 'Doctrine\ORM\Query\AST\Functions\ModFunction',
        'size' => 'Doctrine\ORM\Query\AST\Functions\SizeFunction'
    );

    /** Maps registered datetime function names to class names. */
    private static $_DATETIME_FUNCTIONS = array(
        'current_date' => 'Doctrine\ORM\Query\AST\Functions\CurrentDateFunction',
        'current_time' => 'Doctrine\ORM\Query\AST\Functions\CurrentTimeFunction',
        'current_timestamp' => 'Doctrine\ORM\Query\AST\Functions\CurrentTimestampFunction'
    );

    /**
     * Path expressions that were encountered during parsing of SelectExpressions
     * and still need to be validated.
     *
     * @var array
     */
    private $_deferredPathExpressionStacks = array();

    /**
romanb's avatar
romanb committed
77
     * The lexer.
78 79 80 81 82 83
     *
     * @var Doctrine\ORM\Query\Lexer
     */
    private $_lexer;

    /**
romanb's avatar
romanb committed
84
     * The parser result.
85 86 87 88
     *
     * @var Doctrine\ORM\Query\ParserResult
     */
    private $_parserResult;
romanb's avatar
romanb committed
89

90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
    /**
     * The EntityManager.
     *
     * @var EnityManager
     */
    private $_em;

    /**
     * The Query to parse.
     *
     * @var Query
     */
    private $_query;

    /**
romanb's avatar
romanb committed
105
     * Map of declared query components in the parsed query.
106 107 108 109
     *
     * @var array
     */
    private $_queryComponents = array();
romanb's avatar
romanb committed
110
    
111 112 113 114 115 116 117
    /**
     * Keeps the nesting level of defined ResultVariables
     *
     * @var integer
     */
    private $_nestingLevel = 0;
    
118
    /**
119
     * Any additional custom tree walkers that modify the AST.
120
     *
121 122 123 124 125 126 127
     * @var array
     */
    private $_customTreeWalkers = array();
    
    /**
     * The custom last tree walker, if any, that is responsible for producing the output.
     * 
128
     * @var TreeWalker
129
     */
130
    private $_customOutputWalker;
131 132 133 134 135 136 137 138 139 140 141

    /**
     * Creates a new query parser object.
     *
     * @param Query $query The Query to parse.
     */
    public function __construct(Query $query)
    {
        $this->_query = $query;
        $this->_em = $query->getEntityManager();
        $this->_lexer = new Lexer($query->getDql());
142
        $this->_parserResult = new ParserResult();
143 144
    }

145
    /**
146 147
     * Sets a custom tree walker that produces output.
     * This tree walker will be run last over the AST, after any other walkers.
148
     * 
149
     * @param string $className
150
     */
151
    public function setCustomOutputTreeWalker($className)
152
    {
153 154 155 156 157 158 159 160 161 162 163
        $this->_customOutputWalker = $className;
    }
    
    /**
     * Adds a custom tree walker for modifying the AST.
     * 
     * @param string $className
     */
    public function addCustomTreeWalker($className)
    {
        $this->_customTreeWalkers[] = $className;
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
    }

    /**
     * Gets the lexer used by the parser.
     *
     * @return Doctrine\ORM\Query\Lexer
     */
    public function getLexer()
    {
        return $this->_lexer;
    }

    /**
     * Gets the ParserResult that is being filled with information during parsing.
     *
     * @return Doctrine\ORM\Query\ParserResult
     */
    public function getParserResult()
    {
        return $this->_parserResult;
    }
    
    /**
     * Gets the EntityManager used by the parser.
     *
     * @return EntityManager
     */
    public function getEntityManager()
    {
        return $this->_em;
    }
    
    /**
     * Registers a custom function that returns strings.
     *
     * @param string $name The function name.
     * @param string $class The class name of the function implementation.
     */
    public static function registerStringFunction($name, $class)
    {
        self::$_STRING_FUNCTIONS[$name] = $class;
    }

    /**
     * Registers a custom function that returns numerics.
     *
     * @param string $name The function name.
     * @param string $class The class name of the function implementation.
     */
    public static function registerNumericFunction($name, $class)
    {
        self::$_NUMERIC_FUNCTIONS[$name] = $class;
    }

    /**
     * Registers a custom function that returns date/time values.
     *
     * @param string $name The function name.
     * @param string $class The class name of the function implementation.
     */
    public static function registerDatetimeFunction($name, $class)
    {
        self::$_DATETIME_FUNCTIONS[$name] = $class;
    }

229 230 231 232 233 234 235 236 237 238 239
    /**
     * Attempts to match the given token with the current lookahead token.
     *
     * If they match, updates the lookahead token; otherwise raises a syntax
     * error.
     *
     * @param int|string token type or value
     * @return bool True, if tokens match; false otherwise.
     */
    public function match($token)
    {
240 241
        $key = (is_string($token)) ? 'value' : 'type';
        
242
        if ( ! ($this->_lexer->lookahead[$key] === $token)) {
243
            $this->syntaxError($this->_lexer->getLiteral($token));
244
        }
245 246 247 248 249

        $this->_lexer->moveNext();
    }

    /**
romanb's avatar
romanb committed
250 251 252 253
     * Free this parser enabling it to be reused
     *
     * @param boolean $deep     Whether to clean peek and reset errors
     * @param integer $position Position to reset
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
     */
    public function free($deep = false, $position = 0)
    {
        // WARNING! Use this method with care. It resets the scanner!
        $this->_lexer->resetPosition($position);

        // Deep = true cleans peek and also any previously defined errors
        if ($deep) {
            $this->_lexer->resetPeek();
        }

        $this->_lexer->token = null;
        $this->_lexer->lookahead = null;
    }

    /**
     * Parses a query string.
romanb's avatar
romanb committed
271
     *
272 273 274 275 276
     * @return ParserResult
     */
    public function parse()
    {
        // Parse & build AST
romanb's avatar
romanb committed
277
        $AST = $this->QueryLanguage();
278
        
279 280 281 282
        // Check for end of string
        if ($this->_lexer->lookahead !== null) {
            $this->syntaxError('end of string');
        }
283 284 285 286
        
        if ($customWalkers = $this->_query->getHint(Query::HINT_CUSTOM_TREE_WALKERS)) {
            $this->_customTreeWalkers = $customWalkers;
        }
287

288 289 290 291 292
        // Run any custom tree walkers over the AST
        if ($this->_customTreeWalkers) {
            $treeWalkerChain = new TreeWalkerChain($this->_query, $this->_parserResult, $this->_queryComponents);
            foreach ($this->_customTreeWalkers as $walker) {
                $treeWalkerChain->addTreeWalker($walker);
293
            }
294 295 296 297 298 299 300 301 302 303 304 305 306
            if ($AST instanceof AST\SelectStatement) {
                $treeWalkerChain->walkSelectStatement($AST);
            } else if ($AST instanceof AST\UpdateStatement) {
                $treeWalkerChain->walkUpdateStatement($AST);
            } else {
                $treeWalkerChain->walkDeleteStatement($AST);
            }
        }
        
        if ($this->_customOutputWalker) {
            $outputWalker = new $this->_customOutputWalker(
                $this->_query, $this->_parserResult, $this->_queryComponents
            );
307
        } else {
308
            $outputWalker = new SqlWalker(
309 310
                $this->_query, $this->_parserResult, $this->_queryComponents
            );
311
        }
312 313

        // Assign an SQL executor to the parser result
314
        $this->_parserResult->setSqlExecutor($outputWalker->getExecutor($AST));
315 316 317

        return $this->_parserResult;
    }
318
    
319 320 321 322 323
    /**
     * Generates a new syntax error.
     *
     * @param string $expected Optional expected string.
     * @param array $token Optional token.
324 325
     *
     * @throws \Doctrine\ORM\Query\QueryException
326 327 328 329 330 331 332
     */
    public function syntaxError($expected = '', $token = null)
    {
        if ($token === null) {
            $token = $this->_lexer->lookahead;
        }

333 334
        $tokenPos = (isset($token['position'])) ? $token['position'] : '-1';
        $message  = "line 0, col {$tokenPos}: Error: ";
335 336

        if ($expected !== '') {
337
            $message .= "Expected '{$expected}', got ";
338 339 340 341 342 343 344
        } else {
            $message .= 'Unexpected ';
        }

        if ($this->_lexer->lookahead === null) {
            $message .= 'end of string.';
        } else {
345
            $message .= "'{$token['value']}'";
346 347
        }

348
        throw \Doctrine\ORM\Query\QueryException::syntaxError($message);
349 350 351 352 353 354 355
    }

    /**
     * Generates a new semantical error.
     *
     * @param string $message Optional message.
     * @param array $token Optional token.
356 357
     *
     * @throws \Doctrine\ORM\Query\QueryException
358 359 360 361
     */
    public function semanticalError($message = '', $token = null)
    {
        if ($token === null) {
362
            $token = $this->_lexer->lookahead;
363
        }
364
        
365 366 367
        // Minimum exposed chars ahead of token
        $distance = 12;
        
368 369
        // Find a position of a final word to display in error string
        $dql = $this->_query->getDql();
370 371 372 373
        $length = strlen($dql);
        $pos = $token['position'] + $distance;
        $pos = strpos($dql, ' ', ($length > $pos) ? $pos : $length);
        $length = ($pos !== false) ? $pos - $token['position'] : $distance;
374 375
        
        // Building informative message
376 377 378
        $message = 'line 0, col ' . (
            (isset($token['position']) && $token['position'] > 0) ? $token['position'] : '-1'
        ) . " near '" . substr($dql, $token['position'], $length) . "': Error: " . $message;
guilhermeblanco's avatar
guilhermeblanco committed
379

380
        throw \Doctrine\ORM\Query\QueryException::semanticalError($message);
381
    }
382
    
383
    /**
384
     * Peeks beyond the specified token and returns the first token after that one.
385 386 387
     *
     * @param array $token
     * @return array
388
     */
389 390 391 392 393 394 395 396 397 398
    private function _peekBeyond($token)
    {
        $peek = $this->_lexer->peek();

        while ($peek['value'] != $token) {
            $peek = $this->_lexer->peek();
        }

        $peek = $this->_lexer->peek();
        $this->_lexer->resetPeek();
romanb's avatar
romanb committed
399

400 401
        return $peek;
    }
402 403

    /**
404
     * Checks if the next-next (after lookahead) token starts a function.
405
     *
406
     * @return boolean TRUE if the next-next tokens start a function, FALSE otherwise.
407
     */
408
    private function _isFunction()
409
    {
410 411 412 413 414 415
        $peek     = $this->_lexer->peek();
        $nextpeek = $this->_lexer->peek();
        $this->_lexer->resetPeek();
        
        // We deny the COUNT(SELECT * FROM User u) here. COUNT won't be considered a function
        return ($peek['value'] === '(' && $nextpeek['type'] !== Lexer::T_SELECT);
416
    }
417
    
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
    /**
     * Checks whether the function with the given name is a string function
     * (a function that returns strings).
     *
     * @return boolean TRUE if the token type is a string function, FALSE otherwise.
     */
    private function _isStringFunction($funcName)
    {
        return isset(self::$_STRING_FUNCTIONS[strtolower($funcName)]);
    }

    /**
     * Checks whether the function with the given name is a numeric function
     * (a function that returns numerics).
     *
     * @return boolean TRUE if the token type is a numeric function, FALSE otherwise.
     */
    private function _isNumericFunction($funcName)
    {
        return isset(self::$_NUMERIC_FUNCTIONS[strtolower($funcName)]);
    }

    /**
     * Checks whether the function with the given name is a datetime function
     * (a function that returns date/time values).
     *
     * @return boolean TRUE if the token type is a datetime function, FALSE otherwise.
     */
    private function _isDatetimeFunction($funcName)
    {
        return isset(self::$_DATETIME_FUNCTIONS[strtolower($funcName)]);
    }
    
451
    /**
452
     * Checks whether the given token type indicates an aggregate function.
453
     *
454
     * @return boolean TRUE if the token type is an aggregate function, FALSE otherwise.
455
     */
456
    private function _isAggregateFunction($tokenType)
457
    {
458 459 460
        return $tokenType == Lexer::T_AVG || $tokenType == Lexer::T_MIN ||
               $tokenType == Lexer::T_MAX || $tokenType == Lexer::T_SUM ||
               $tokenType == Lexer::T_COUNT;
461 462
    }

463 464 465 466 467 468 469 470 471 472 473 474 475
    /**
     * Checks whether the current lookahead token of the lexer has the type
     * T_ALL, T_ANY or T_SOME.
     *
     * @return boolean
     */
    private function _isNextAllAnySome()
    {
        return $this->_lexer->lookahead['type'] === Lexer::T_ALL ||
               $this->_lexer->lookahead['type'] === Lexer::T_ANY ||
               $this->_lexer->lookahead['type'] === Lexer::T_SOME;
    }

476 477 478 479 480 481 482 483 484
    /**
     * Checks whether the next 2 tokens start a subselect.
     *
     * @return boolean TRUE if the next 2 tokens start a subselect, FALSE otherwise.
     */
    private function _isSubselect()
    {
        $la = $this->_lexer->lookahead;
        $next = $this->_lexer->glimpse();
guilhermeblanco's avatar
guilhermeblanco committed
485

486 487
        return ($la['value'] === '(' && $next['type'] === Lexer::T_SELECT);
    }
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
    
    /**
     * Begins a new stack of deferred path expressions.
     */
    private function _beginDeferredPathExpressionStack()
    {
        $this->_deferredPathExpressionStacks[] = array();
    }

    /**
     * Processes the topmost stack of deferred path expressions.
     */
    private function _processDeferredPathExpressionStack()
    {
        $exprStack = array_pop($this->_deferredPathExpressionStacks);

504
        foreach ($exprStack as $item) {
505 506 507
            $this->_validatePathExpression(
                $item['pathExpression'], $item['nestingLevel'], $item['token']
            );
508 509 510 511 512 513 514 515 516 517 518 519 520
        }
    }
    
    /**
     * Validates that the given <tt>PathExpression</tt> is a semantically correct for grammar rules:
     *
     * AssociationPathExpression             ::= CollectionValuedPathExpression | SingleValuedAssociationPathExpression
     * SingleValuedPathExpression            ::= StateFieldPathExpression | SingleValuedAssociationPathExpression
     * StateFieldPathExpression              ::= IdentificationVariable "." StateField | SingleValuedAssociationPathExpression "." StateField
     * SingleValuedAssociationPathExpression ::= IdentificationVariable "." {SingleValuedAssociationField "."}* SingleValuedAssociationField
     * CollectionValuedPathExpression        ::= IdentificationVariable "." {SingleValuedAssociationField "."}* CollectionValuedAssociationField
     *
     * @param PathExpression $pathExpression
521
     * @param integer $nestingLevel
522
     * @param array $token
523
     * @return integer
524
     */
525
    private function _validatePathExpression(AST\PathExpression $pathExpression, $nestingLevel = null, $token = null)
526
    {
527
        $identVariable = $pathExpression->identificationVariable;
528 529
        $nestingLevel = ($nestingLevel !== null) ?: $this->_nestingLevel;
        $token = ($token) ?: $this->_lexer->lookahead;
530
        
531
        $this->_validateIdentificationVariable($identVariable, $nestingLevel, $token);
532
        
533
        $class = $this->_queryComponents[$identVariable]['metadata'];
534 535
        $stateField = $collectionField = null;

536
        foreach ($pathExpression->parts as $field) {
537 538
            // Check if it is not in a state field
            if ($stateField !== null) {
539 540 541
                $this->semanticalError(
                    'Cannot navigate through state field named ' . $stateField, $token
                );
542 543 544 545
            }
            
            // Check if it is not a collection field
            if ($collectionField !== null) {
546 547 548 549
                $this->semanticalError(
                    'Cannot navigate through collection-valued field named ' . $collectionField, 
                    $token
                );
550 551 552 553
            }
            
            // Check if field exists
            if ( ! isset($class->associationMappings[$field]) && ! isset($class->fieldMappings[$field])) {
554 555 556
                $this->semanticalError(
                    'Class ' . $class->name . ' has no field named ' . $field, $token
                );
557 558 559 560 561 562 563 564 565 566 567
            }
            
            if (isset($class->fieldMappings[$field])) {
                $stateField = $field;
            } else if ($class->associationMappings[$field]->isOneToOne()) {
                $class = $this->_em->getClassMetadata($class->associationMappings[$field]->targetEntityName);
            } else {
                $collectionField = $field;
            }
        }
        
568
        // Recognize correct expression type
569 570 571 572 573 574 575 576
        $expressionType = null;
        
        if ($stateField !== null) {
        	$expressionType = AST\PathExpression::TYPE_STATE_FIELD;
        } else if ($collectionField !== null) {
        	$expressionType = AST\PathExpression::TYPE_COLLECTION_VALUED_ASSOCIATION;
        } else {
            $expressionType = AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION;
577 578 579
        } 
        
        // Validate if PathExpression is one of the expected types
580
        $expectedType = $pathExpression->expectedType;
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609

        if ( ! ($expectedType & $expressionType)) {
            // We need to recognize which was expected type(s)
            $expectedStringTypes = array();
				
            // Validate state field type (field/column)
            if ($expectedType & AST\PathExpression::TYPE_STATE_FIELD) {
                $expectedStringTypes[] = 'StateFieldPathExpression';
            }
                
            // Validate single valued association (*-to-one)
            if ($expectedType & AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION) {
                $expectedStringTypes[] = 'SingleValuedAssociationField';
            }
                
            // Validate single valued association (*-to-many)
            if ($expectedType & AST\PathExpression::TYPE_COLLECTION_VALUED_ASSOCIATION) {
                $expectedStringTypes[] = 'CollectionValuedAssociationField';
            }
                
            // Build the error message
            $semanticalError = 'Invalid PathExpression.';
            
            if (count($expectedStringTypes) == 1) {
                $semanticalError .= ' Must be a ' . $expectedStringTypes[0] . '.';
            } else {
                $semanticalError .= ' ' . implode(' or ', $expectedStringTypes) . ' expected.';
            }
            
610
            $this->semanticalError($semanticalError, $token);
611
        }
612 613
        
        // We need to force the type in PathExpression
614
        $pathExpression->type = $expressionType;
615 616 617 618 619
        
        return $expressionType;
    }
    
    /**
620 621
     * Validates that the given <tt>IdentificationVariable</tt> is a semantically correct. 
     * It must exist in query components list.
622
     *
623
     * @param string $identVariable
624
     * @param integer $nestingLevel
625
     * @param array $token
626
     * @return array Query Component
627
     */
628
    private function _validateIdentificationVariable($identVariable, $nestingLevel = null, $token = null)
629
    {
630 631 632
        $nestingLevel = ($nestingLevel !== null) ?: $this->_nestingLevel;
        $token = ($token) ?: $this->_lexer->lookahead;
    
633
        if ( ! isset($this->_queryComponents[$identVariable])) {
634
            $this->semanticalError("'$identVariable' is not defined", $token);
635
        }
636
        
637
        // Validate if identification variable nesting level is lower or equal than the current one
638
        if ($this->_queryComponents[$identVariable]['nestingLevel'] > $nestingLevel) {
639
            $this->semanticalError(
640
                "'$idVariable' is used outside the scope of its declaration",
641
                $token
642 643 644
            );
        }
        
645
        return $this->_queryComponents[$identVariable];
646 647 648
    }

    
649 650
    /**
     * QueryLanguage ::= SelectStatement | UpdateStatement | DeleteStatement
651 652 653 654
     *
     * @return \Doctrine\ORM\Query\AST\SelectStatement | 
     *         \Doctrine\ORM\Query\AST\UpdateStatement | 
     *         \Doctrine\ORM\Query\AST\DeleteStatement
655
     */
romanb's avatar
romanb committed
656
    public function QueryLanguage()
657 658
    {
        $this->_lexer->moveNext();
guilhermeblanco's avatar
guilhermeblanco committed
659

660 661
        switch ($this->_lexer->lookahead['type']) {
            case Lexer::T_SELECT:
romanb's avatar
romanb committed
662
                return $this->SelectStatement();
guilhermeblanco's avatar
guilhermeblanco committed
663

664
            case Lexer::T_UPDATE:
romanb's avatar
romanb committed
665
                return $this->UpdateStatement();
guilhermeblanco's avatar
guilhermeblanco committed
666

667
            case Lexer::T_DELETE:
romanb's avatar
romanb committed
668
                return $this->DeleteStatement();
guilhermeblanco's avatar
guilhermeblanco committed
669

670 671
            default:
                $this->syntaxError('SELECT, UPDATE or DELETE');
672
                break;
673 674
        }
    }
675
    
676 677 678

    /**
     * SelectStatement ::= SelectClause FromClause [WhereClause] [GroupByClause] [HavingClause] [OrderByClause]
679 680
     *
     * @return \Doctrine\ORM\Query\AST\SelectStatement
681
     */
romanb's avatar
romanb committed
682
    public function SelectStatement()
683
    {
684 685
        // We need to prevent semantical checks on SelectClause, 
        // since we do not have any IdentificationVariable yet
686
        $this->_beginDeferredPathExpressionStack();
687
        
688
        $selectStatement = new AST\SelectStatement($this->SelectClause(), $this->FromClause());
689 690
        
        // Activate semantical checks after this point. Process all deferred checks in pipeline
691 692
        $this->_processDeferredPathExpressionStack();

693
        $selectStatement->whereClause = $this->_lexer->isNextToken(Lexer::T_WHERE)
guilhermeblanco's avatar
guilhermeblanco committed
694
            ? $this->WhereClause() : null;
695

696
        $selectStatement->groupByClause = $this->_lexer->isNextToken(Lexer::T_GROUP)
guilhermeblanco's avatar
guilhermeblanco committed
697
            ? $this->GroupByClause() : null;
698

699
        $selectStatement->havingClause = $this->_lexer->isNextToken(Lexer::T_HAVING)
guilhermeblanco's avatar
guilhermeblanco committed
700
            ? $this->HavingClause() : null;
701

702
        $selectStatement->orderByClause = $this->_lexer->isNextToken(Lexer::T_ORDER)
guilhermeblanco's avatar
guilhermeblanco committed
703
            ? $this->OrderByClause() : null;
704

705
        return $selectStatement;
706 707 708
    }

    /**
709
     * UpdateStatement ::= UpdateClause [WhereClause]
710 711
     *
     * @return \Doctrine\ORM\Query\AST\UpdateStatement
712
     */
713
    public function UpdateStatement()
714
    {
715
        $updateStatement = new AST\UpdateStatement($this->UpdateClause());
716 717
        $updateStatement->whereClause = $this->_lexer->isNextToken(Lexer::T_WHERE) 
            ? $this->WhereClause() : null;
718 719

        return $updateStatement;
720
    }
721 722 723
    
    /**
     * DeleteStatement ::= DeleteClause [WhereClause]
724 725
     *
     * @return \Doctrine\ORM\Query\AST\DeleteStatement
726 727 728 729
     */
    public function DeleteStatement()
    {
        $deleteStatement = new AST\DeleteStatement($this->DeleteClause());
730 731
        $deleteStatement->whereClause = $this->_lexer->isNextToken(Lexer::T_WHERE) 
            ? $this->WhereClause() : null;
732

733 734 735 736
        return $deleteStatement;
    }
    
    
737
    /**
738
     * IdentificationVariable ::= identifier
739 740
     *
     * @return string
741
     */
742
    public function IdentificationVariable()
743
    {
744
        $this->match(Lexer::T_IDENTIFIER);
guilhermeblanco's avatar
guilhermeblanco committed
745

746 747 748 749 750
        return $this->_lexer->token['value'];
    }
    
    /**
     * AliasIdentificationVariable = identifier
751 752
     *
     * @return string
753 754 755 756
     */
    public function AliasIdentificationVariable()
    {
        $this->match(Lexer::T_IDENTIFIER);
guilhermeblanco's avatar
guilhermeblanco committed
757

758 759 760 761 762
        return $this->_lexer->token['value'];
    }
    
    /**
     * AbstractSchemaName ::= identifier
763 764
     *
     * @return string
765 766 767 768
     */
    public function AbstractSchemaName()
    {
        $this->match(Lexer::T_IDENTIFIER);
guilhermeblanco's avatar
guilhermeblanco committed
769

770 771 772 773 774
        return $this->_lexer->token['value'];
    }
    
    /**
     * ResultVariable ::= identifier
775 776
     *
     * @return string
777 778 779 780 781 782 783 784
     */
    public function ResultVariable()
    {
        $this->match(Lexer::T_IDENTIFIER);
    
        return $this->_lexer->token['value'];
    }
    
guilhermeblanco's avatar
guilhermeblanco committed
785

786
    /**
787
     * JoinAssociationPathExpression ::= IdentificationVariable "." (CollectionValuedAssociationField | SingleValuedAssociationField)
788 789
     *
     * @return \Doctrine\ORM\Query\AST\JoinAssociationPathExpression
790
     */
791
    public function JoinAssociationPathExpression()
792
    {
793
        $token = $this->_lexer->lookahead;
794
        $identVariable = $this->IdentificationVariable();
795 796
        $this->match('.');
        $this->match(Lexer::T_IDENTIFIER);
797 798 799
        $field = $this->_lexer->token['value'];
        
        // Validating IdentificationVariable (it was already defined previously)
800
        $this->_validateIdentificationVariable($identVariable, null, $token);
801 802
        
        // Validating association field (*-to-one or *-to-many)
803
        $class = $this->_queryComponents[$identVariable]['metadata'];
804 805 806 807 808
        
        if ( ! isset($class->associationMappings[$field])) {
            $this->semanticalError('Class ' . $class->name . ' has no field named ' . $field);
        }
        
809
        return new AST\JoinAssociationPathExpression($identVariable, $field);
810 811 812
    }  

    /**
813 814
     * Parses an arbitrary path expression. Applies or defer semantical validation 
     * based on expected types.
815 816 817
     *
     * PathExpression ::= IdentificationVariable "." {identifier "."}* identifier
     *
818
     * @param integer $expectedType
819
     * @return \Doctrine\ORM\Query\AST\PathExpression
820
     */
821
    public function PathExpression($expectedType)
822
    {
823
        $token = $this->_lexer->lookahead;
824
        $identVariable = $this->IdentificationVariable();
825 826 827 828 829 830 831 832 833
        $parts = array();

        do {
            $this->match('.');
            $this->match(Lexer::T_IDENTIFIER);
            
            $parts[] = $this->_lexer->token['value'];
        } while ($this->_lexer->isNextToken('.'));
        
834
        // Creating AST node
835
        $pathExpr = new AST\PathExpression($expectedType, $identVariable, $parts);
836 837 838 839
        
        // Defer PathExpression validation if requested to be defered
        if ( ! empty($this->_deferredPathExpressionStacks)) {
            $exprStack = array_pop($this->_deferredPathExpressionStacks);
840 841 842
            $exprStack[] = array(
                'pathExpression' => $pathExpr,
                'nestingLevel'   => $this->_nestingLevel,
843
                'token'          => $token,
844
            );
845 846 847 848 849 850
            array_push($this->_deferredPathExpressionStacks, $exprStack);

            return $pathExpr;
        }

        // Apply PathExpression validation normally (not in defer mode)
851
        $this->_validatePathExpression($pathExpr, $this->_nestingLevel, $token);
852 853
        
        return $pathExpr;
854 855 856 857
    }
    
    /**
     * AssociationPathExpression ::= CollectionValuedPathExpression | SingleValuedAssociationPathExpression
858 859
     *
     * @return \Doctrine\ORM\Query\AST\PathExpression
860 861 862
     */
    public function AssociationPathExpression()
    {
863 864 865 866
        return $this->PathExpression(
            AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION |
            AST\PathExpression::TYPE_COLLECTION_VALUED_ASSOCIATION
        );
867 868 869 870
    }
    
    /**
     * SingleValuedPathExpression ::= StateFieldPathExpression | SingleValuedAssociationPathExpression
871 872
     *
     * @return \Doctrine\ORM\Query\AST\PathExpression
873 874 875
     */
    public function SingleValuedPathExpression()
    {
876 877 878 879
        return $this->PathExpression(
            AST\PathExpression::TYPE_STATE_FIELD |
            AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION
        );
880
    }
881 882 883
    
    /**
     * StateFieldPathExpression ::= SimpleStateFieldPathExpression | SimpleStateFieldAssociationPathExpression
884 885
     *
     * @return \Doctrine\ORM\Query\AST\PathExpression
886 887 888
     */
    public function StateFieldPathExpression()
    {
889
        return $this->PathExpression(AST\PathExpression::TYPE_STATE_FIELD);
890 891
    }
    
892
    /**
893
     * SingleValuedAssociationPathExpression ::= IdentificationVariable "." {SingleValuedAssociationField "."}* SingleValuedAssociationField
894 895
     *
     * @return \Doctrine\ORM\Query\AST\PathExpression
896
     */
897
    public function SingleValuedAssociationPathExpression()
898
    {
899
        return $this->PathExpression(AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION);
900 901 902 903
    }
    
    /**
     * CollectionValuedPathExpression ::= IdentificationVariable "." {SingleValuedAssociationField "."}* CollectionValuedAssociationField
904 905
     *
     * @return \Doctrine\ORM\Query\AST\PathExpression
906 907 908
     */
    public function CollectionValuedPathExpression()
    {
909
        return $this->PathExpression(AST\PathExpression::TYPE_COLLECTION_VALUED_ASSOCIATION);
910
    }
911 912 913
    
    /**
     * SimpleStateFieldPathExpression ::= IdentificationVariable "." StateField
914 915
     *
     * @return \Doctrine\ORM\Query\AST\PathExpression
916 917 918
     */
    public function SimpleStateFieldPathExpression()
    {
919
        $pathExpression = $this->PathExpression(AST\PathExpression::TYPE_STATE_FIELD);
920
        $parts = $pathExpression->parts;
921 922 923 924 925 926 927 928 929
        
        if (count($parts) > 1) {
            $this->semanticalError(
                "Invalid SimpleStateFieldPathExpression. " . 
                "Expected state field, got association '{$parts[0]}'."
            );
        }
        
        return $pathExpression;
930 931 932
    }

    
933 934
    /**
     * SelectClause ::= "SELECT" ["DISTINCT"] SelectExpression {"," SelectExpression}
935 936
     *
     * @return \Doctrine\ORM\Query\AST\SelectClause
937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962
     */
    public function SelectClause()
    {
        $isDistinct = false;
        $this->match(Lexer::T_SELECT);

        // Check for DISTINCT
        if ($this->_lexer->isNextToken(Lexer::T_DISTINCT)) {
            $this->match(Lexer::T_DISTINCT);
            $isDistinct = true;
        }

        // Process SelectExpressions (1..N)
        $selectExpressions = array();
        $selectExpressions[] = $this->SelectExpression();

        while ($this->_lexer->isNextToken(',')) {
            $this->match(',');
            $selectExpressions[] = $this->SelectExpression();
        }

        return new AST\SelectClause($selectExpressions, $isDistinct);
    }

    /**
     * SimpleSelectClause ::= "SELECT" ["DISTINCT"] SimpleSelectExpression
963 964
     *
     * @return \Doctrine\ORM\Query\AST\SimpleSelectClause
965 966 967
     */
    public function SimpleSelectClause()
    {
968
        $isDistinct = false;
969 970 971 972
        $this->match(Lexer::T_SELECT);

        if ($this->_lexer->isNextToken(Lexer::T_DISTINCT)) {
            $this->match(Lexer::T_DISTINCT);
973
            $isDistinct = true;
974 975
        }

976
        return new AST\SimpleSelectClause($this->SimpleSelectExpression(), $isDistinct);
977 978
    }

979 980
    /**
     * UpdateClause ::= "UPDATE" AbstractSchemaName [["AS"] AliasIdentificationVariable] "SET" UpdateItem {"," UpdateItem}*
981 982
     *
     * @return \Doctrine\ORM\Query\AST\UpdateClause
983
     */
romanb's avatar
romanb committed
984
    public function UpdateClause()
985 986
    {
        $this->match(Lexer::T_UPDATE);
987
        $token = $this->_lexer->lookahead;
romanb's avatar
romanb committed
988
        $abstractSchemaName = $this->AbstractSchemaName();
989
        $aliasIdentificationVariable = null;
guilhermeblanco's avatar
guilhermeblanco committed
990

991 992 993
        if ($this->_lexer->isNextToken(Lexer::T_AS)) {
            $this->match(Lexer::T_AS);
        }
guilhermeblanco's avatar
guilhermeblanco committed
994

995
        if ($this->_lexer->isNextToken(Lexer::T_IDENTIFIER)) {
996
            $token = $this->_lexer->lookahead;
997
            $aliasIdentificationVariable = $this->AliasIdentificationVariable();
998 999 1000
        } else {
            $aliasIdentificationVariable = $abstractSchemaName;
        }
1001 1002
        
        $class = $this->_em->getClassMetadata($abstractSchemaName);
guilhermeblanco's avatar
guilhermeblanco committed
1003

1004 1005
        // Building queryComponent
        $queryComponent = array(
1006
            'metadata'     => $class,
1007 1008 1009 1010
            'parent'       => null,
            'relation'     => null,
            'map'          => null,
            'nestingLevel' => $this->_nestingLevel,
1011
            'token'        => $token,
1012 1013 1014
        );
        $this->_queryComponents[$aliasIdentificationVariable] = $queryComponent;

1015 1016 1017 1018 1019 1020 1021 1022 1023
        $this->match(Lexer::T_SET);
        $updateItems = array();
        $updateItems[] = $this->UpdateItem();

        while ($this->_lexer->isNextToken(',')) {
            $this->match(',');
            $updateItems[] = $this->UpdateItem();
        }

1024
        $updateClause = new AST\UpdateClause($abstractSchemaName, $updateItems);
1025
        $updateClause->aliasIdentificationVariable = $aliasIdentificationVariable;
1026 1027 1028 1029 1030 1031

        return $updateClause;
    }

    /**
     * DeleteClause ::= "DELETE" ["FROM"] AbstractSchemaName [["AS"] AliasIdentificationVariable]
1032 1033
     *
     * @return \Doctrine\ORM\Query\AST\DeleteClause
1034
     */
romanb's avatar
romanb committed
1035
    public function DeleteClause()
1036 1037
    {
        $this->match(Lexer::T_DELETE);
guilhermeblanco's avatar
guilhermeblanco committed
1038

1039 1040 1041
        if ($this->_lexer->isNextToken(Lexer::T_FROM)) {
            $this->match(Lexer::T_FROM);
        }
guilhermeblanco's avatar
guilhermeblanco committed
1042

1043
        $token = $this->_lexer->lookahead;
romanb's avatar
romanb committed
1044
        $deleteClause = new AST\DeleteClause($this->AbstractSchemaName());
1045
        $aliasIdentificationVariable = null;
guilhermeblanco's avatar
guilhermeblanco committed
1046

1047 1048 1049
        if ($this->_lexer->isNextToken(Lexer::T_AS)) {
            $this->match(Lexer::T_AS);
        }
guilhermeblanco's avatar
guilhermeblanco committed
1050

1051
        if ($this->_lexer->isNextToken(Lexer::T_IDENTIFIER)) {
1052 1053
            $token = $this->_lexer->lookahead;
            $aliasIdentificationVariable = $this->AliasIdentificationVariable();
1054
        } else {
1055
            $aliasIdentificationVariable = $deleteClause->abstractSchemaName;
1056
        }
1057
        
1058 1059
        $deleteClause->aliasIdentificationVariable = $aliasIdentificationVariable;
        $class = $this->_em->getClassMetadata($deleteClause->abstractSchemaName);
1060 1061
        
        // Building queryComponent
1062
        $queryComponent = array(
1063
            'metadata'     => $class,
1064 1065 1066 1067
            'parent'       => null,
            'relation'     => null,
            'map'          => null,
            'nestingLevel' => $this->_nestingLevel,
1068
            'token'        => $token,
1069
        );
1070
        $this->_queryComponents[$aliasIdentificationVariable] = $queryComponent;
1071 1072 1073 1074 1075

        return $deleteClause;
    }

    /**
1076
     * FromClause ::= "FROM" IdentificationVariableDeclaration {"," IdentificationVariableDeclaration}*
1077 1078
     *
     * @return \Doctrine\ORM\Query\AST\FromClause
1079
     */
1080
    public function FromClause()
1081
    {
1082 1083 1084 1085 1086 1087 1088
        $this->match(Lexer::T_FROM);
        $identificationVariableDeclarations = array();
        $identificationVariableDeclarations[] = $this->IdentificationVariableDeclaration();

        while ($this->_lexer->isNextToken(',')) {
            $this->match(',');
            $identificationVariableDeclarations[] = $this->IdentificationVariableDeclaration();
1089 1090
        }

1091 1092 1093 1094 1095
        return new AST\FromClause($identificationVariableDeclarations);
    }

    /**
     * SubselectFromClause ::= "FROM" SubselectIdentificationVariableDeclaration {"," SubselectIdentificationVariableDeclaration}*
1096 1097
     *
     * @return \Doctrine\ORM\Query\AST\SubselectFromClause
1098 1099 1100 1101 1102 1103
     */
    public function SubselectFromClause()
    {
        $this->match(Lexer::T_FROM);
        $identificationVariables = array();
        $identificationVariables[] = $this->SubselectIdentificationVariableDeclaration();
guilhermeblanco's avatar
guilhermeblanco committed
1104

1105 1106
        while ($this->_lexer->isNextToken(',')) {
            $this->match(',');
1107
            $identificationVariables[] = $this->SubselectIdentificationVariableDeclaration();
1108 1109
        }

1110
        return new AST\SubselectFromClause($identificationVariables);
1111 1112 1113
    }

    /**
1114
     * WhereClause ::= "WHERE" ConditionalExpression
1115 1116
     *
     * @return \Doctrine\ORM\Query\AST\WhereClause
1117
     */
1118
    public function WhereClause()
1119
    {
1120 1121 1122 1123 1124 1125 1126
        $this->match(Lexer::T_WHERE);

        return new AST\WhereClause($this->ConditionalExpression());
    }

    /**
     * HavingClause ::= "HAVING" ConditionalExpression
1127 1128
     *
     * @return \Doctrine\ORM\Query\AST\HavingClause
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
     */
    public function HavingClause()
    {
        $this->match(Lexer::T_HAVING);

        return new AST\HavingClause($this->ConditionalExpression());
    }

    /**
     * GroupByClause ::= "GROUP" "BY" GroupByItem {"," GroupByItem}*
1139 1140
     *
     * @return \Doctrine\ORM\Query\AST\GroupByClause
1141 1142 1143 1144 1145 1146 1147
     */
    public function GroupByClause()
    {
        $this->match(Lexer::T_GROUP);
        $this->match(Lexer::T_BY);

        $groupByItems = array($this->GroupByItem());
1148 1149 1150

        while ($this->_lexer->isNextToken(',')) {
            $this->match(',');
1151
            $groupByItems[] = $this->GroupByItem();
1152 1153
        }

1154 1155 1156 1157 1158
        return new AST\GroupByClause($groupByItems);
    }
    
    /**
     * OrderByClause ::= "ORDER" "BY" OrderByItem {"," OrderByItem}*
1159 1160
     *
     * @return \Doctrine\ORM\Query\AST\OrderByClause
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
     */
    public function OrderByClause()
    {
        $this->match(Lexer::T_ORDER);
        $this->match(Lexer::T_BY);

        $orderByItems = array();
        $orderByItems[] = $this->OrderByItem();

        while ($this->_lexer->isNextToken(',')) {
            $this->match(',');
            $orderByItems[] = $this->OrderByItem();
        }

        return new AST\OrderByClause($orderByItems);
1176 1177 1178
    }

    /**
1179
     * Subselect ::= SimpleSelectClause SubselectFromClause [WhereClause] [GroupByClause] [HavingClause] [OrderByClause]
1180 1181
     *
     * @return \Doctrine\ORM\Query\AST\Subselect
1182
     */
1183 1184
    public function Subselect()
    {
1185 1186 1187
        // Increase query nesting level
        $this->_nestingLevel++;
        
1188
        $this->_beginDeferredPathExpressionStack();
1189
        
1190
        $subselect = new AST\Subselect($this->SimpleSelectClause(), $this->SubselectFromClause());
1191
        
1192 1193
        $this->_processDeferredPathExpressionStack();

1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
        $subselect->whereClause = $this->_lexer->isNextToken(Lexer::T_WHERE) 
            ? $this->WhereClause() : null;
            
        $subselect->groupByClause = $this->_lexer->isNextToken(Lexer::T_GROUP) 
            ? $this->GroupByClause() : null;
            
        $subselect->havingClause = $this->_lexer->isNextToken(Lexer::T_HAVING) 
            ? $this->HavingClause() : null;
            
        $subselect->orderByClause = $this->_lexer->isNextToken(Lexer::T_ORDER) 
            ? $this->OrderByClause() : null;
            
1206 1207
        // Decrease query nesting level
        $this->_nestingLevel--;
1208 1209 1210 1211 1212 1213

        return $subselect;
    }

    
    /**
1214
     * UpdateItem ::= IdentificationVariable "." {StateField | SingleValuedAssociationField} "=" NewValue
1215 1216
     *
     * @return \Doctrine\ORM\Query\AST\UpdateItem
1217 1218
     */
    public function UpdateItem()
1219
    {
1220
        $token = $this->_lexer->lookahead;
1221
        $identVariable = $this->IdentificationVariable();
1222 1223
            
        // Validate if IdentificationVariable is defined
1224
        $queryComponent = $this->_validateIdentificationVariable($identVariable, null, $token);
1225 1226
            
        $this->match('.');
1227 1228 1229
        $this->match(Lexer::T_IDENTIFIER);
        $field = $this->_lexer->token['value'];
        
1230 1231 1232 1233 1234 1235 1236 1237 1238
        // Check if field exists
        $class = $queryComponent['metadata'];
        
        if ( ! isset($class->associationMappings[$field]) && ! isset($class->fieldMappings[$field])) {
            $this->semanticalError(
                'Class ' . $class->name . ' has no field named ' . $field, $token
            );
        }
        
1239 1240 1241
        $this->match('=');
        
        $newValue = $this->NewValue();
guilhermeblanco's avatar
guilhermeblanco committed
1242

1243
        $updateItem = new AST\UpdateItem($field, $newValue);
1244
        $updateItem->identificationVariable = $identVariable;
1245 1246 1247 1248 1249 1250

        return $updateItem;
    }

    /**
     * GroupByItem ::= IdentificationVariable | SingleValuedPathExpression
1251 1252
     *
     * @return string | \Doctrine\ORM\Query\AST\PathExpression
1253 1254 1255
     */
    public function GroupByItem()
    {
1256 1257 1258 1259
        // We need to check if we are in a IdentificationVariable or SingleValuedPathExpression
        $glimpse = $this->_lexer->glimpse();
        
        if ($glimpse['value'] != '.') {
1260
            $token = $this->_lexer->lookahead;
1261
            $identVariable = $this->IdentificationVariable();
1262 1263
            
            // Validate if IdentificationVariable is defined
1264
            $this->_validateIdentificationVariable($identVariable, null, $token);
1265
            
1266
            return $identVariable;
1267 1268
        }
        
1269 1270 1271 1272 1273 1274
        return $this->SingleValuedPathExpression();
    }

    /**
     * OrderByItem ::= (ResultVariable | StateFieldPathExpression) ["ASC" | "DESC"]
     *
1275 1276
     * @todo Post 2.0 release. Support general SingleValuedPathExpression instead 
     * of only StateFieldPathExpression.
1277 1278
     *
     * @return \Doctrine\ORM\Query\AST\OrderByItem
1279 1280 1281
     */
    public function OrderByItem()
    {
1282 1283
        $type = 'ASC';
        
1284 1285 1286 1287
        // We need to check if we are in a ResultVariable or StateFieldPathExpression
        $glimpse = $this->_lexer->glimpse();
        
        if ($glimpse['value'] != '.') {
1288
            $token = $this->_lexer->lookahead;
1289
            $expr = $this->ResultVariable();
1290
            
1291
            // Check if ResultVariable is defined in query components
1292
            $queryComponent = $this->_validateIdentificationVariable($expr, null, $token);
1293
            
1294
            // Outer defininition used in inner subselect is not enough.
1295 1296 1297
            // ResultVariable exists in queryComponents, check nesting level
            if ($queryComponent['nestingLevel'] != $this->_nestingLevel) {
                $this->semanticalError(
1298
                    "'$expr' is used outside the scope of its declaration"
1299 1300
                );
            }
1301
        } else {
1302 1303 1304 1305
            $expr = $this->StateFieldPathExpression();
        }
    
        $item = new AST\OrderByItem($expr);
1306

1307 1308
        if ($this->_lexer->isNextToken(Lexer::T_ASC)) {
            $this->match(Lexer::T_ASC);
1309
        } else if ($this->_lexer->isNextToken(Lexer::T_DESC)) {
1310
            $this->match(Lexer::T_DESC);
1311
            $type = 'DESC';
1312
        }
1313
        
1314
        $item->type = $type;
1315 1316
        return $item;
    }
guilhermeblanco's avatar
guilhermeblanco committed
1317

1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
    /**
     * NewValue ::= SimpleArithmeticExpression | StringPrimary | DatetimePrimary | BooleanPrimary |
     *      EnumPrimary | SimpleEntityExpression | "NULL"
     *
     * NOTE: Since it is not possible to correctly recognize individual types, here is the full
     * grammar that needs to be supported:
     * 
     * NewValue ::= SimpleArithmeticExpression | "NULL"
     *
     * SimpleArithmeticExpression covers all *Primary grammar rules and also SimplEntityExpression
     */
    public function NewValue()
    {
        if ($this->_lexer->isNextToken(Lexer::T_NULL)) {
            $this->match(Lexer::T_NULL);
            return null;
        } else if ($this->_lexer->isNextToken(Lexer::T_INPUT_PARAMETER)) {
            $this->match(Lexer::T_INPUT_PARAMETER);
            return new AST\InputParameter($this->_lexer->token['value']);
        }
        
        return $this->SimpleArithmeticExpression();
1340 1341
    }

1342
    
1343 1344
    /**
     * IdentificationVariableDeclaration ::= RangeVariableDeclaration [IndexBy] {JoinVariableDeclaration}*
1345 1346
     *
     * @return \Doctrine\ORM\Query\AST\IdentificationVariableDeclaration
1347
     */
romanb's avatar
romanb committed
1348
    public function IdentificationVariableDeclaration()
1349
    {
romanb's avatar
romanb committed
1350 1351
        $rangeVariableDeclaration = $this->RangeVariableDeclaration();
        $indexBy = $this->_lexer->isNextToken(Lexer::T_INDEX) ? $this->IndexBy() : null;
1352
        $joinVariableDeclarations = array();
guilhermeblanco's avatar
guilhermeblanco committed
1353

1354
        while (
guilhermeblanco's avatar
guilhermeblanco committed
1355 1356 1357
            $this->_lexer->isNextToken(Lexer::T_LEFT) ||
            $this->_lexer->isNextToken(Lexer::T_INNER) ||
            $this->_lexer->isNextToken(Lexer::T_JOIN)
1358
        ) {
romanb's avatar
romanb committed
1359
            $joinVariableDeclarations[] = $this->JoinVariableDeclaration();
1360 1361 1362
        }

        return new AST\IdentificationVariableDeclaration(
guilhermeblanco's avatar
guilhermeblanco committed
1363
            $rangeVariableDeclaration, $indexBy, $joinVariableDeclarations
1364 1365 1366
        );
    }

1367 1368
    /**
     * SubselectIdentificationVariableDeclaration ::= IdentificationVariableDeclaration | (AssociationPathExpression ["AS"] AliasIdentificationVariable)
1369 1370 1371
     *
     * @return \Doctrine\ORM\Query\AST\SubselectIdentificationVariableDeclaration |
     *         \Doctrine\ORM\Query\AST\IdentificationVariableDeclaration
1372 1373 1374 1375 1376 1377
     */
    public function SubselectIdentificationVariableDeclaration()
    {
        $peek = $this->_lexer->glimpse();

        if ($peek['value'] == '.') {
1378 1379
            $subselectIdVarDecl = new AST\SubselectIdentificationVariableDeclaration();
            $subselectIdVarDecl->associationPathExpression = $this->AssociationPathExpression();
1380
            $this->match(Lexer::T_AS);
1381
            $subselectIdVarDecl->aliasIdentificationVariable = $this->AliasIdentificationVariable();
1382

1383
            return $subselectIdVarDecl;
1384 1385 1386 1387 1388 1389 1390
        }

        return $this->IdentificationVariableDeclaration();
    }

    /**
     * JoinVariableDeclaration ::= Join [IndexBy]
1391 1392
     *
     * @return \Doctrine\ORM\Query\AST\JoinVariableDeclaration
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
     */
    public function JoinVariableDeclaration()
    {
        $join = $this->Join();
        $indexBy = $this->_lexer->isNextToken(Lexer::T_INDEX)
            ? $this->IndexBy() : null;

        return new AST\JoinVariableDeclaration($join, $indexBy);
    }

1403 1404
    /**
     * RangeVariableDeclaration ::= AbstractSchemaName ["AS"] AliasIdentificationVariable
1405 1406
     *
     * @return \Doctrine\ORM\Query\AST\RangeVariableDeclaration
1407
     */
romanb's avatar
romanb committed
1408
    public function RangeVariableDeclaration()
1409
    {
romanb's avatar
romanb committed
1410
        $abstractSchemaName = $this->AbstractSchemaName();
1411 1412 1413 1414

        if ($this->_lexer->isNextToken(Lexer::T_AS)) {
            $this->match(Lexer::T_AS);
        }
guilhermeblanco's avatar
guilhermeblanco committed
1415

1416
        $token = $this->_lexer->lookahead;
romanb's avatar
romanb committed
1417
        $aliasIdentificationVariable = $this->AliasIdentificationVariable();
1418 1419 1420 1421
        $classMetadata = $this->_em->getClassMetadata($abstractSchemaName);

        // Building queryComponent
        $queryComponent = array(
1422 1423 1424 1425 1426
            'metadata'     => $classMetadata,
            'parent'       => null,
            'relation'     => null,
            'map'          => null,
            'nestingLevel' => $this->_nestingLevel,
1427
            'token'        => $token,
1428 1429
        );
        $this->_queryComponents[$aliasIdentificationVariable] = $queryComponent;
guilhermeblanco's avatar
guilhermeblanco committed
1430

1431
        return new AST\RangeVariableDeclaration($abstractSchemaName, $aliasIdentificationVariable);
1432 1433 1434
    }

    /**
1435
     * Join ::= ["LEFT" ["OUTER"] | "INNER"] "JOIN" JoinAssociationPathExpression
1436
     *          ["AS"] AliasIdentificationVariable [("ON" | "WITH") ConditionalExpression]
1437 1438
     *
     * @return \Doctrine\ORM\Query\AST\Join
1439
     */
romanb's avatar
romanb committed
1440
    public function Join()
1441 1442 1443
    {
        // Check Join type
        $joinType = AST\Join::JOIN_TYPE_INNER;
guilhermeblanco's avatar
guilhermeblanco committed
1444

1445 1446
        if ($this->_lexer->isNextToken(Lexer::T_LEFT)) {
            $this->match(Lexer::T_LEFT);
guilhermeblanco's avatar
guilhermeblanco committed
1447

1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
            // Possible LEFT OUTER join
            if ($this->_lexer->isNextToken(Lexer::T_OUTER)) {
                $this->match(Lexer::T_OUTER);
                $joinType = AST\Join::JOIN_TYPE_LEFTOUTER;
            } else {
                $joinType = AST\Join::JOIN_TYPE_LEFT;
            }
        } else if ($this->_lexer->isNextToken(Lexer::T_INNER)) {
            $this->match(Lexer::T_INNER);
        }

        $this->match(Lexer::T_JOIN);
1460
        
1461
        $joinPathExpression = $this->JoinAssociationPathExpression();
guilhermeblanco's avatar
guilhermeblanco committed
1462

1463 1464 1465 1466
        if ($this->_lexer->isNextToken(Lexer::T_AS)) {
            $this->match(Lexer::T_AS);
        }

1467
        $token = $this->_lexer->lookahead;
romanb's avatar
romanb committed
1468
        $aliasIdentificationVariable = $this->AliasIdentificationVariable();
1469 1470

        // Verify that the association exists.
1471 1472
        $parentClass = $this->_queryComponents[$joinPathExpression->identificationVariable]['metadata'];
        $assocField = $joinPathExpression->associationField;
guilhermeblanco's avatar
guilhermeblanco committed
1473

1474
        if ( ! $parentClass->hasAssociation($assocField)) {
guilhermeblanco's avatar
guilhermeblanco committed
1475 1476 1477
            $this->semanticalError(
                "Class " . $parentClass->name . " has no association named '$assocField'."
            );
1478
        }
guilhermeblanco's avatar
guilhermeblanco committed
1479

1480 1481 1482 1483
        $targetClassName = $parentClass->getAssociationMapping($assocField)->getTargetEntityName();

        // Building queryComponent
        $joinQueryComponent = array(
1484
            'metadata'     => $this->_em->getClassMetadata($targetClassName),
1485
            'parent'       => $joinPathExpression->identificationVariable,
1486 1487 1488
            'relation'     => $parentClass->getAssociationMapping($assocField),
            'map'          => null,
            'nestingLevel' => $this->_nestingLevel,
1489
            'token'        => $token,
1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
        );
        $this->_queryComponents[$aliasIdentificationVariable] = $joinQueryComponent;

        // Create AST node
        $join = new AST\Join($joinType, $joinPathExpression, $aliasIdentificationVariable);

        // Check for ad-hoc Join conditions
        if ($this->_lexer->isNextToken(Lexer::T_ON) || $this->_lexer->isNextToken(Lexer::T_WITH)) {
            if ($this->_lexer->isNextToken(Lexer::T_ON)) {
                $this->match(Lexer::T_ON);
1500
                $join->whereType = AST\Join::JOIN_WHERE_ON;
1501 1502 1503
            } else {
                $this->match(Lexer::T_WITH);
            }
guilhermeblanco's avatar
guilhermeblanco committed
1504

1505
            $join->conditionalExpression = $this->ConditionalExpression();
1506 1507 1508 1509 1510 1511 1512
        }

        return $join;
    }

    /**
     * IndexBy ::= "INDEX" "BY" SimpleStateFieldPathExpression
1513 1514
     *
     * @return \Doctrine\ORM\Query\AST\IndexBy
1515
     */
romanb's avatar
romanb committed
1516
    public function IndexBy()
1517 1518 1519
    {
        $this->match(Lexer::T_INDEX);
        $this->match(Lexer::T_BY);
romanb's avatar
romanb committed
1520
        $pathExp = $this->SimpleStateFieldPathExpression();
guilhermeblanco's avatar
guilhermeblanco committed
1521

1522
        // Add the INDEX BY info to the query component
1523 1524
        $parts = $pathExp->parts;
        $this->_queryComponents[$pathExp->identificationVariable]['map'] = $parts[0];
guilhermeblanco's avatar
guilhermeblanco committed
1525

1526 1527 1528
        return $pathExp;
    }

1529 1530
    
    /**
1531 1532 1533
     * SelectExpression ::=
     *      IdentificationVariable | StateFieldPathExpression |
     *      (AggregateExpression | "(" Subselect ")" | FunctionDeclaration) [["AS"] ResultVariable]
1534 1535
     *
     * @return \Doctrine\ORM\Query\AST\SelectExpression
1536
     */
1537
    public function SelectExpression()
1538
    {
1539 1540 1541
        $expression = null;
        $fieldAliasIdentificationVariable = null;
        $peek = $this->_lexer->glimpse();
guilhermeblanco's avatar
guilhermeblanco committed
1542

1543 1544 1545 1546 1547 1548 1549 1550 1551 1552
        // First we recognize for an IdentificationVariable (DQL class alias)
        if ($peek['value'] != '.' && $peek['value'] != '(' && $this->_lexer->lookahead['type'] === Lexer::T_IDENTIFIER) {
            $expression = $this->IdentificationVariable();
        } else if (($isFunction = $this->_isFunction()) !== false || $this->_isSubselect()) {
            if ($isFunction) {
                if ($this->_isAggregateFunction($this->_lexer->lookahead['type'])) {
                    $expression = $this->AggregateExpression();
                } else {
                    $expression = $this->FunctionDeclaration();
                }
1553
            } else {
1554 1555 1556
                $this->match('(');
                $expression = $this->Subselect();
                $this->match(')');
1557
            }
guilhermeblanco's avatar
guilhermeblanco committed
1558

1559 1560 1561
            if ($this->_lexer->isNextToken(Lexer::T_AS)) {
                $this->match(Lexer::T_AS);
            }
guilhermeblanco's avatar
guilhermeblanco committed
1562

1563
            if ($this->_lexer->isNextToken(Lexer::T_IDENTIFIER)) {
1564
                $token = $this->_lexer->lookahead;
1565
                $fieldAliasIdentificationVariable = $this->ResultVariable();
1566 1567
                
                // Include ResultVariable in query components.
1568
                $this->_queryComponents[$fieldAliasIdentificationVariable] = array(
1569 1570
                    'resultvariable' => $expression,
                    'nestingLevel'   => $this->_nestingLevel,
1571
                    'token'          => $token,
1572
                );
1573 1574 1575 1576 1577
            }
        } else {
            // Deny hydration of partial objects if doctrine.forcePartialLoad query hint not defined 
            if (
                $this->_query->getHydrationMode() == Query::HYDRATE_OBJECT &&
1578
                ! $this->_query->getHint(Query::HINT_FORCE_PARTIAL_LOAD)
1579 1580 1581
            ) {
            	throw DoctrineException::partialObjectsAreDangerous();
            }
guilhermeblanco's avatar
guilhermeblanco committed
1582

1583
            $expression = $this->StateFieldPathExpression();
1584
        }
guilhermeblanco's avatar
guilhermeblanco committed
1585

1586
        return new AST\SelectExpression($expression, $fieldAliasIdentificationVariable);
1587 1588 1589
    }

    /**
1590
     * SimpleSelectExpression ::= StateFieldPathExpression | IdentificationVariable | (AggregateExpression [["AS"] ResultVariable])
1591 1592
     *
     * @return \Doctrine\ORM\Query\AST\SimpleSelectExpression
1593
     */
1594
    public function SimpleSelectExpression()
1595
    {
1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
        if ($this->_lexer->isNextToken(Lexer::T_IDENTIFIER)) {
            // SingleValuedPathExpression | IdentificationVariable
            $peek = $this->_lexer->glimpse();

            if ($peek['value'] == '.') {
                return new AST\SimpleSelectExpression($this->StateFieldPathExpression());
            }

            $this->match($this->_lexer->lookahead['value']);

            return new AST\SimpleSelectExpression($this->_lexer->token['value']);
1607 1608 1609
        }
        
        $expr = new AST\SimpleSelectExpression($this->AggregateExpression());
guilhermeblanco's avatar
guilhermeblanco committed
1610

1611 1612 1613
        if ($this->_lexer->isNextToken(Lexer::T_AS)) {
            $this->match(Lexer::T_AS);
        }
1614

1615
        if ($this->_lexer->isNextToken(Lexer::T_IDENTIFIER)) {
1616
            $token = $this->_lexer->lookahead;
1617
            $resultVariable = $this->ResultVariable();
1618
            $expr->fieldIdentificationVariable = $resultVariable;
1619
                
1620 1621
            // Include ResultVariable in query components.
            $this->_queryComponents[$resultVariable] = array(
1622 1623
                'resultvariable' => $expr,
                'nestingLevel'   => $this->_nestingLevel,
1624
                'token'          => $token,
1625
            );
1626
        }
1627 1628

        return $expr;
1629 1630
    }

1631
    
1632 1633
    /**
     * ConditionalExpression ::= ConditionalTerm {"OR" ConditionalTerm}*
1634 1635
     *
     * @return \Doctrine\ORM\Query\AST\ConditionalExpression
1636
     */
romanb's avatar
romanb committed
1637
    public function ConditionalExpression()
1638 1639
    {
        $conditionalTerms = array();
romanb's avatar
romanb committed
1640
        $conditionalTerms[] = $this->ConditionalTerm();
guilhermeblanco's avatar
guilhermeblanco committed
1641

1642 1643
        while ($this->_lexer->isNextToken(Lexer::T_OR)) {
            $this->match(Lexer::T_OR);
romanb's avatar
romanb committed
1644
            $conditionalTerms[] = $this->ConditionalTerm();
1645
        }
guilhermeblanco's avatar
guilhermeblanco committed
1646

1647 1648 1649 1650 1651
        return new AST\ConditionalExpression($conditionalTerms);
    }

    /**
     * ConditionalTerm ::= ConditionalFactor {"AND" ConditionalFactor}*
1652 1653
     *
     * @return \Doctrine\ORM\Query\AST\ConditionalTerm
1654
     */
romanb's avatar
romanb committed
1655
    public function ConditionalTerm()
1656 1657
    {
        $conditionalFactors = array();
romanb's avatar
romanb committed
1658
        $conditionalFactors[] = $this->ConditionalFactor();
guilhermeblanco's avatar
guilhermeblanco committed
1659

1660 1661
        while ($this->_lexer->isNextToken(Lexer::T_AND)) {
            $this->match(Lexer::T_AND);
romanb's avatar
romanb committed
1662
            $conditionalFactors[] = $this->ConditionalFactor();
1663
        }
guilhermeblanco's avatar
guilhermeblanco committed
1664

1665 1666 1667 1668 1669
        return new AST\ConditionalTerm($conditionalFactors);
    }

    /**
     * ConditionalFactor ::= ["NOT"] ConditionalPrimary
1670 1671
     *
     * @return \Doctrine\ORM\Query\AST\ConditionalFactor
1672
     */
romanb's avatar
romanb committed
1673
    public function ConditionalFactor()
1674 1675
    {
        $not = false;
guilhermeblanco's avatar
guilhermeblanco committed
1676

1677 1678 1679 1680
        if ($this->_lexer->isNextToken(Lexer::T_NOT)) {
            $this->match(Lexer::T_NOT);
            $not = true;
        }
guilhermeblanco's avatar
guilhermeblanco committed
1681

1682 1683 1684 1685
        $condFactor = new AST\ConditionalFactor($this->ConditionalPrimary());
        $condFactor->not = $not;
        
        return $condFactor;
1686 1687 1688 1689
    }

    /**
     * ConditionalPrimary ::= SimpleConditionalExpression | "(" ConditionalExpression ")"
1690
     *
1691
     * @return Doctrine\ORM\Query\AST\ConditionalPrimary
1692
     */
romanb's avatar
romanb committed
1693
    public function ConditionalPrimary()
1694 1695
    {
        $condPrimary = new AST\ConditionalPrimary;
1696
        
1697
        if ($this->_lexer->isNextToken('(')) {
1698 1699 1700 1701 1702 1703 1704 1705
            // Peek beyond the matching closing paranthesis ')'
            $numUnmatched = 1;
            $peek = $this->_lexer->peek();
            while ($numUnmatched > 0 && $peek !== null) {
                if ($peek['value'] == ')') {
                    --$numUnmatched;
                } else if ($peek['value'] == '(') {
                    ++$numUnmatched;
1706
                }
1707
                $peek = $this->_lexer->peek();
1708
            }
1709 1710 1711 1712 1713 1714 1715 1716 1717
            $this->_lexer->resetPeek();
       
            if (in_array($peek['value'], array("=",  "<", "<=", "<>", ">", ">=", "!=")) ||
                    $peek['type'] === Lexer::T_NOT ||
                    $peek['type'] === Lexer::T_BETWEEN ||
                    $peek['type'] === Lexer::T_LIKE ||
                    $peek['type'] === Lexer::T_IN ||
                    $peek['type'] === Lexer::T_IS ||
                    $peek['type'] === Lexer::T_EXISTS) {
1718
                $condPrimary->simpleConditionalExpression = $this->SimpleConditionalExpression();
1719 1720
            } else {
                $this->match('(');
romanb's avatar
romanb committed
1721
                $condPrimary->conditionalExpression = $this->ConditionalExpression();
1722 1723 1724
                $this->match(')');
            }
        } else {
1725
            $condPrimary->simpleConditionalExpression = $this->SimpleConditionalExpression();
1726
        }
1727
        
1728 1729 1730 1731 1732 1733 1734 1735 1736
        return $condPrimary;
    }

    /**
     * SimpleConditionalExpression ::=
     *      ComparisonExpression | BetweenExpression | LikeExpression |
     *      InExpression | NullComparisonExpression | ExistsExpression |
     *      EmptyCollectionComparisonExpression | CollectionMemberExpression
     */
romanb's avatar
romanb committed
1737
    public function SimpleConditionalExpression()
1738 1739 1740 1741 1742 1743
    {
        if ($this->_lexer->isNextToken(Lexer::T_NOT)) {
            $token = $this->_lexer->glimpse();
        } else {
            $token = $this->_lexer->lookahead;
        }
guilhermeblanco's avatar
guilhermeblanco committed
1744

1745
        if ($token['type'] === Lexer::T_EXISTS) {
romanb's avatar
romanb committed
1746
            return $this->ExistsExpression();
1747 1748
        }

romanb's avatar
romanb committed
1749
        $pathExprOrInputParam = false;
guilhermeblanco's avatar
guilhermeblanco committed
1750

romanb's avatar
romanb committed
1751
        if ($token['type'] === Lexer::T_IDENTIFIER || $token['type'] === Lexer::T_INPUT_PARAMETER) {
1752
            // Peek beyond the PathExpression
romanb's avatar
romanb committed
1753
            $pathExprOrInputParam = true;
1754
            $peek = $this->_lexer->peek();
guilhermeblanco's avatar
guilhermeblanco committed
1755

1756 1757 1758 1759 1760 1761 1762 1763 1764
            while ($peek['value'] === '.') {
                $this->_lexer->peek();
                $peek = $this->_lexer->peek();
            }

            // Also peek beyond a NOT if there is one
            if ($peek['type'] === Lexer::T_NOT) {
                $peek = $this->_lexer->peek();
            }
1765
            
1766
            $token = $peek;
1767 1768 1769 1770 1771 1772 1773 1774 1775 1776
            
            // We need to go even further in case of IS (differenciate between NULL and EMPTY)
            $lookahead = $this->_lexer->peek();
                
            // Also peek beyond a NOT if there is one
            if ($lookahead['type'] === Lexer::T_NOT) {
                $lookahead = $this->_lexer->peek();
            }
            
            $this->_lexer->resetPeek();
1777 1778
        }

romanb's avatar
romanb committed
1779
        if ($pathExprOrInputParam) {            
1780
            switch ($token['type']) {
romanb's avatar
romanb committed
1781 1782
                case Lexer::T_NONE:
                    return $this->ComparisonExpression();
guilhermeblanco's avatar
guilhermeblanco committed
1783

1784
                case Lexer::T_BETWEEN:
romanb's avatar
romanb committed
1785
                    return $this->BetweenExpression();
guilhermeblanco's avatar
guilhermeblanco committed
1786

1787
                case Lexer::T_LIKE:
romanb's avatar
romanb committed
1788
                    return $this->LikeExpression();
guilhermeblanco's avatar
guilhermeblanco committed
1789

1790
                case Lexer::T_IN:
romanb's avatar
romanb committed
1791
                    return $this->InExpression();
guilhermeblanco's avatar
guilhermeblanco committed
1792

1793
                case Lexer::T_IS:
1794 1795 1796 1797 1798
                	if ($lookahead['type'] == Lexer::T_NULL) {
                        return $this->NullComparisonExpression();
                    }
                    
                    return $this->EmptyCollectionComparisonExpression();
guilhermeblanco's avatar
guilhermeblanco committed
1799

romanb's avatar
romanb committed
1800 1801
                case Lexer::T_MEMBER:
                    return $this->CollectionMemberExpression();
guilhermeblanco's avatar
guilhermeblanco committed
1802

1803 1804 1805 1806
                default:
                    $this->syntaxError();
            }
        }
1807 1808
        
        return $this->ComparisonExpression();
1809
    }
romanb's avatar
romanb committed
1810
    
1811
    
1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825
    /**
     * EmptyCollectionComparisonExpression ::= CollectionValuedPathExpression "IS" ["NOT"] "EMPTY"
     *
     * @return \Doctrine\ORM\Query\AST\EmptyCollectionComparisonExpression
     */
    public function EmptyCollectionComparisonExpression()
    {
        $emptyColletionCompExpr = new AST\EmptyCollectionComparisonExpression(
            $this->CollectionValuedPathExpression()
        );
        $this->match(Lexer::T_IS);

        if ($this->_lexer->isNextToken(Lexer::T_NOT)) {
            $this->match(Lexer::T_NOT);
1826
            $emptyColletionCompExpr->not = true;
1827 1828 1829 1830 1831 1832 1833
        }

        $this->match(Lexer::T_EMPTY);

        return $emptyColletionCompExpr;
    }
    
1834
    /**
romanb's avatar
romanb committed
1835
     * CollectionMemberExpression ::= EntityExpression ["NOT"] "MEMBER" ["OF"] CollectionValuedPathExpression
1836
     * 
romanb's avatar
romanb committed
1837 1838 1839
     * EntityExpression ::= SingleValuedAssociationPathExpression | SimpleEntityExpression
     * SimpleEntityExpression ::= IdentificationVariable | InputParameter
     * 
1840
     * @return \Doctrine\ORM\Query\AST\CollectionMemberExpression
1841
     */
romanb's avatar
romanb committed
1842
    public function CollectionMemberExpression()
1843
    {
1844
        $not = false;
guilhermeblanco's avatar
guilhermeblanco committed
1845

1846
        $entityExpr = $this->EntityExpression(); 
guilhermeblanco's avatar
guilhermeblanco committed
1847

1848
        if ($this->_lexer->isNextToken(Lexer::T_NOT)) {
1849
            $not = true;
1850 1851
            $this->match(Lexer::T_NOT);
        }
guilhermeblanco's avatar
guilhermeblanco committed
1852

1853
        $this->match(Lexer::T_MEMBER);
guilhermeblanco's avatar
guilhermeblanco committed
1854

1855 1856
        if ($this->_lexer->isNextToken(Lexer::T_OF)) {
            $this->match(Lexer::T_OF);
romanb's avatar
romanb committed
1857
        }
1858

1859 1860
        $collMemberExpr = new AST\CollectionMemberExpression(
            $entityExpr, $this->CollectionValuedPathExpression()
1861
        );
1862 1863 1864
        $collMemberExpr->not = $not;
        
        return $collMemberExpr;
romanb's avatar
romanb committed
1865 1866
    }

1867
    
romanb's avatar
romanb committed
1868
    /**
1869
     * Literal ::= string | char | integer | float | boolean
romanb's avatar
romanb committed
1870
     *
1871
     * @return string
romanb's avatar
romanb committed
1872
     */
1873
    public function Literal()
romanb's avatar
romanb committed
1874
    {
1875 1876
        switch ($this->_lexer->lookahead['type']) {
            case Lexer::T_STRING:
romanb's avatar
romanb committed
1877 1878
                $this->match($this->_lexer->lookahead['value']);
                return new AST\Literal(AST\Literal::STRING, $this->_lexer->token['value']);
1879 1880 1881
            case Lexer::T_INTEGER:
            case Lexer::T_FLOAT:
                $this->match($this->_lexer->lookahead['value']);
romanb's avatar
romanb committed
1882 1883 1884 1885 1886
                return new AST\Literal(AST\Literal::NUMERIC, $this->_lexer->token['value']);
            case Lexer::T_TRUE:
            case Lexer::T_FALSE:
                $this->match($this->_lexer->lookahead['value']);
                return new AST\Literal(AST\Literal::BOOLEAN, $this->_lexer->token['value']);
1887 1888
            default:
                $this->syntaxError('Literal');
1889 1890
        }
    }
1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914
    
    /**
     * InParameter ::= Literal | InputParameter
     *
     * @return string | \Doctrine\ORM\Query\AST\InputParameter
     */
    public function InParameter()
    {
        if ($this->_lexer->lookahead['type'] == Lexer::T_INPUT_PARAMETER) {
            return $this->InputParameter();
        }
        
        return $this->Literal();
    }
    
    
    /**
     * InputParameter ::= PositionalParameter | NamedParameter
     *
     * @return \Doctrine\ORM\Query\AST\InputParameter
     */
    public function InputParameter()
    {
        $this->match($this->_lexer->lookahead['value']);
1915

1916 1917 1918
        return new AST\InputParameter($this->_lexer->token['value']);
    }
    
1919
    
1920 1921
    /**
     * ArithmeticExpression ::= SimpleArithmeticExpression | "(" Subselect ")"
1922 1923
     *
     * @return \Doctrine\ORM\Query\AST\ArithmeticExpression
1924
     */
romanb's avatar
romanb committed
1925
    public function ArithmeticExpression()
1926 1927
    {
        $expr = new AST\ArithmeticExpression;
guilhermeblanco's avatar
guilhermeblanco committed
1928

1929 1930
        if ($this->_lexer->lookahead['value'] === '(') {
            $peek = $this->_lexer->glimpse();
guilhermeblanco's avatar
guilhermeblanco committed
1931

1932 1933
            if ($peek['type'] === Lexer::T_SELECT) {
                $this->match('(');
1934
                $expr->subselect = $this->Subselect();
1935
                $this->match(')');
guilhermeblanco's avatar
guilhermeblanco committed
1936

1937 1938 1939
                return $expr;
            }
        }
guilhermeblanco's avatar
guilhermeblanco committed
1940

1941
        $expr->simpleArithmeticExpression = $this->SimpleArithmeticExpression();
guilhermeblanco's avatar
guilhermeblanco committed
1942

1943 1944 1945 1946 1947
        return $expr;
    }

    /**
     * SimpleArithmeticExpression ::= ArithmeticTerm {("+" | "-") ArithmeticTerm}*
1948 1949
     *
     * @return \Doctrine\ORM\Query\AST\SimpleArithmeticExpression
1950
     */
romanb's avatar
romanb committed
1951
    public function SimpleArithmeticExpression()
1952 1953
    {
        $terms = array();
romanb's avatar
romanb committed
1954
        $terms[] = $this->ArithmeticTerm();
guilhermeblanco's avatar
guilhermeblanco committed
1955

1956 1957 1958 1959 1960 1961
        while ($this->_lexer->lookahead['value'] == '+' || $this->_lexer->lookahead['value'] == '-') {
            if ($this->_lexer->lookahead['value'] == '+') {
                $this->match('+');
            } else {
                $this->match('-');
            }
guilhermeblanco's avatar
guilhermeblanco committed
1962

1963
            $terms[] = $this->_lexer->token['value'];
romanb's avatar
romanb committed
1964
            $terms[] = $this->ArithmeticTerm();
1965
        }
1966
        
1967 1968 1969 1970 1971
        return new AST\SimpleArithmeticExpression($terms);
    }

    /**
     * ArithmeticTerm ::= ArithmeticFactor {("*" | "/") ArithmeticFactor}*
1972 1973
     *
     * @return \Doctrine\ORM\Query\AST\ArithmeticTerm
1974
     */
romanb's avatar
romanb committed
1975
    public function ArithmeticTerm()
1976 1977
    {
        $factors = array();
romanb's avatar
romanb committed
1978
        $factors[] = $this->ArithmeticFactor();
guilhermeblanco's avatar
guilhermeblanco committed
1979

1980 1981 1982 1983 1984 1985
        while ($this->_lexer->lookahead['value'] == '*' || $this->_lexer->lookahead['value'] == '/') {
            if ($this->_lexer->lookahead['value'] == '*') {
                $this->match('*');
            } else {
                $this->match('/');
            }
guilhermeblanco's avatar
guilhermeblanco committed
1986

1987
            $factors[] = $this->_lexer->token['value'];
romanb's avatar
romanb committed
1988
            $factors[] = $this->ArithmeticFactor();
1989
        }
guilhermeblanco's avatar
guilhermeblanco committed
1990

1991 1992 1993 1994 1995
        return new AST\ArithmeticTerm($factors);
    }

    /**
     * ArithmeticFactor ::= [("+" | "-")] ArithmeticPrimary
1996 1997
     *
     * @return \Doctrine\ORM\Query\AST\ArithmeticFactor
1998
     */
romanb's avatar
romanb committed
1999
    public function ArithmeticFactor()
2000
    {
2001
        $sign = null;
guilhermeblanco's avatar
guilhermeblanco committed
2002

2003 2004
        if ($this->_lexer->lookahead['value'] == '+') {
            $this->match('+');
2005
            $sign = true;
2006 2007
        } else if ($this->_lexer->lookahead['value'] == '-') {
            $this->match('-');
2008
            $sign = false;
2009
        }
guilhermeblanco's avatar
guilhermeblanco committed
2010

2011
        return new AST\ArithmeticFactor($this->ArithmeticPrimary(), $sign);
2012 2013 2014
    }

    /**
2015 2016 2017
     * ArithmeticPrimary ::= SingleValuedPathExpression | Literal | "(" SimpleArithmeticExpression ")"
     *          | FunctionsReturningNumerics | AggregateExpression | FunctionsReturningStrings
     *          | FunctionsReturningDatetime | IdentificationVariable
2018
     */
2019
    public function ArithmeticPrimary()
2020
    {
2021 2022 2023 2024
        if ($this->_lexer->lookahead['value'] === '(') {
            $this->match('(');
            $expr = $this->SimpleArithmeticExpression();
            $this->match(')');
guilhermeblanco's avatar
guilhermeblanco committed
2025

2026
            return $expr;
2027
        }
guilhermeblanco's avatar
guilhermeblanco committed
2028

2029 2030 2031
        switch ($this->_lexer->lookahead['type']) {
            case Lexer::T_IDENTIFIER:
                $peek = $this->_lexer->glimpse();
2032

2033 2034 2035
                if ($peek['value'] == '(') {
                    return $this->FunctionDeclaration();
                }
2036

2037 2038 2039
                if ($peek['value'] == '.') {
                    return $this->SingleValuedPathExpression();
                }
guilhermeblanco's avatar
guilhermeblanco committed
2040

2041
                return $this->IdentificationVariable();
guilhermeblanco's avatar
guilhermeblanco committed
2042

2043
            case Lexer::T_INPUT_PARAMETER:
2044
                return $this->InputParameter();
2045

2046 2047
            default:
                $peek = $this->_lexer->glimpse();
guilhermeblanco's avatar
guilhermeblanco committed
2048

2049 2050 2051 2052
                if ($peek['value'] == '(') {
                    if ($this->_isAggregateFunction($this->_lexer->lookahead['type'])) {
                        return $this->AggregateExpression();
                    }
romanb's avatar
romanb committed
2053

2054
                    return $this->FunctionDeclaration();
romanb's avatar
romanb committed
2055 2056
                } else {
                    return $this->Literal();
2057 2058
                }
        }
2059
    }
2060
    
2061
    /**
2062
     * StringExpression ::= StringPrimary | "(" Subselect ")"
2063 2064 2065
     *
     * @return \Doctrine\ORM\Query\AST\StringPrimary |
     *         \Doctrine]ORM\Query\AST\Subselect
2066
     */
2067
    public function StringExpression()
2068
    {
2069 2070
        if ($this->_lexer->lookahead['value'] === '(') {
            $peek = $this->_lexer->glimpse();
2071

2072 2073 2074 2075
            if ($peek['type'] === Lexer::T_SELECT) {
                $this->match('(');
                $expr = $this->Subselect();
                $this->match(')');
2076

2077 2078 2079
                return $expr;
            }
        }
2080

2081
        return $this->StringPrimary();
2082 2083 2084
    }

    /**
2085
     * StringPrimary ::= StateFieldPathExpression | string | InputParameter | FunctionsReturningStrings | AggregateExpression
2086
     */
2087
    public function StringPrimary()
2088
    {
2089 2090
        if ($this->_lexer->lookahead['type'] === Lexer::T_IDENTIFIER) {
            $peek = $this->_lexer->glimpse();
guilhermeblanco's avatar
guilhermeblanco committed
2091

2092 2093 2094 2095 2096 2097 2098 2099 2100
            if ($peek['value'] == '.') {
                return $this->StateFieldPathExpression();
            } else if ($peek['value'] == '(') {
                return $this->FunctionsReturningStrings();
            } else {
                $this->syntaxError("'.' or '('");
            }
        } else if ($this->_lexer->lookahead['type'] === Lexer::T_STRING) {
            $this->match(Lexer::T_STRING);
guilhermeblanco's avatar
guilhermeblanco committed
2101

2102 2103
            return $this->_lexer->token['value'];
        } else if ($this->_lexer->lookahead['type'] === Lexer::T_INPUT_PARAMETER) {
2104
            return $this->InputParameter();
2105 2106 2107 2108 2109
        } else if ($this->_isAggregateFunction($this->_lexer->lookahead['type'])) {
            return $this->AggregateExpression();
        }

        $this->syntaxError('StateFieldPathExpression | string | InputParameter | FunctionsReturningStrings | AggregateExpression');
2110 2111 2112
    }

    /**
2113
     * EntityExpression ::= SingleValuedAssociationPathExpression | SimpleEntityExpression
2114 2115 2116
     *
     * @return \Doctrine\ORM\Query\AST\SingleValuedAssociationPathExpression |
     *         \Doctrine\ORM\Query\AST\SimpleEntityExpression
2117
     */
2118
    public function EntityExpression()
2119
    {
2120 2121 2122 2123
        $glimpse = $this->_lexer->glimpse();
        
        if ($this->_lexer->isNextToken(Lexer::T_IDENTIFIER) && $glimpse['value'] === '.') {
            return $this->SingleValuedAssociationPathExpression();
2124
        }
2125 2126
        
        return $this->SimpleEntityExpression();
2127
    }
2128
    
2129
    /**
2130
     * SimpleEntityExpression ::= IdentificationVariable | InputParameter
2131 2132
     *
     * @return string | \Doctrine\ORM\Query\AST\InputParameter
2133
     */
2134
    public function SimpleEntityExpression()
2135
    {
2136
        if ($this->_lexer->isNextToken(Lexer::T_INPUT_PARAMETER)) {
2137
            return $this->InputParameter();
2138
        }
2139 2140
        
        return $this->IdentificationVariable();
2141 2142
    }

2143
    
2144
    /**
2145 2146 2147
     * AggregateExpression ::=
     *  ("AVG" | "MAX" | "MIN" | "SUM") "(" ["DISTINCT"] StateFieldPathExpression ")" |
     *  "COUNT" "(" ["DISTINCT"] (IdentificationVariable | SingleValuedPathExpression) ")"
2148 2149
     *
     * @return \Doctrine\ORM\Query\AST\AggregateExpression
2150
     */
2151
    public function AggregateExpression()
2152
    {
2153 2154
        $isDistinct = false;
        $functionName = '';
guilhermeblanco's avatar
guilhermeblanco committed
2155

2156 2157 2158 2159
        if ($this->_lexer->isNextToken(Lexer::T_COUNT)) {
            $this->match(Lexer::T_COUNT);
            $functionName = $this->_lexer->token['value'];
            $this->match('(');
guilhermeblanco's avatar
guilhermeblanco committed
2160

2161 2162 2163
            if ($this->_lexer->isNextToken(Lexer::T_DISTINCT)) {
                $this->match(Lexer::T_DISTINCT);
                $isDistinct = true;
2164
            }
guilhermeblanco's avatar
guilhermeblanco committed
2165

2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178
            $pathExp = $this->SingleValuedPathExpression();
            $this->match(')');
        } else {
            if ($this->_lexer->isNextToken(Lexer::T_AVG)) {
                $this->match(Lexer::T_AVG);
            } else if ($this->_lexer->isNextToken(Lexer::T_MAX)) {
                $this->match(Lexer::T_MAX);
            } else if ($this->_lexer->isNextToken(Lexer::T_MIN)) {
                $this->match(Lexer::T_MIN);
            } else if ($this->_lexer->isNextToken(Lexer::T_SUM)) {
                $this->match(Lexer::T_SUM);
            } else {
                $this->syntaxError('One of: MAX, MIN, AVG, SUM, COUNT');
2179
            }
guilhermeblanco's avatar
guilhermeblanco committed
2180

2181 2182 2183 2184
            $functionName = $this->_lexer->token['value'];
            $this->match('(');
            $pathExp = $this->StateFieldPathExpression();
            $this->match(')');
2185
        }
2186 2187

        return new AST\AggregateExpression($functionName, $pathExp, $isDistinct);
2188 2189
    }

2190
    
2191
    /**
2192
     * QuantifiedExpression ::= ("ALL" | "ANY" | "SOME") "(" Subselect ")"
2193 2194
     *
     * @return \Doctrine\ORM\Query\AST\QuantifiedExpression
2195
     */
2196
    public function QuantifiedExpression()
2197
    {
2198
        $type = '';
guilhermeblanco's avatar
guilhermeblanco committed
2199

2200 2201
        if ($this->_lexer->isNextToken(Lexer::T_ALL)) {
            $this->match(Lexer::T_ALL);
2202
            $type = 'ALL';
2203 2204
        } else if ($this->_lexer->isNextToken(Lexer::T_ANY)) {
            $this->match(Lexer::T_ANY);
2205
             $type = 'ANY';
2206 2207
        } else if ($this->_lexer->isNextToken(Lexer::T_SOME)) {
            $this->match(Lexer::T_SOME);
2208
             $type = 'SOME';
2209 2210 2211
        } else {
            $this->syntaxError('ALL, ANY or SOME');
        }
guilhermeblanco's avatar
guilhermeblanco committed
2212

2213 2214
        $this->match('(');
        $qExpr = new AST\QuantifiedExpression($this->Subselect());
2215
        $qExpr->type = $type;
2216
        $this->match(')');
guilhermeblanco's avatar
guilhermeblanco committed
2217

2218
        return $qExpr;
2219 2220 2221 2222
    }

    /**
     * BetweenExpression ::= ArithmeticExpression ["NOT"] "BETWEEN" ArithmeticExpression "AND" ArithmeticExpression
2223 2224
     *
     * @return \Doctrine\ORM\Query\AST\BetweenExpression
2225
     */
romanb's avatar
romanb committed
2226
    public function BetweenExpression()
2227 2228
    {
        $not = false;
romanb's avatar
romanb committed
2229
        $arithExpr1 = $this->ArithmeticExpression();
guilhermeblanco's avatar
guilhermeblanco committed
2230

2231 2232 2233 2234
        if ($this->_lexer->isNextToken(Lexer::T_NOT)) {
            $this->match(Lexer::T_NOT);
            $not = true;
        }
guilhermeblanco's avatar
guilhermeblanco committed
2235

2236
        $this->match(Lexer::T_BETWEEN);
romanb's avatar
romanb committed
2237
        $arithExpr2 = $this->ArithmeticExpression();
2238
        $this->match(Lexer::T_AND);
romanb's avatar
romanb committed
2239
        $arithExpr3 = $this->ArithmeticExpression();
2240 2241

        $betweenExpr = new AST\BetweenExpression($arithExpr1, $arithExpr2, $arithExpr3);
2242
        $betweenExpr->not = $not;
2243 2244 2245 2246 2247

        return $betweenExpr;
    }

    /**
2248 2249
     * ComparisonExpression ::= ArithmeticExpression ComparisonOperator ( QuantifiedExpression | ArithmeticExpression )
     *
2250
     * @return \Doctrine\ORM\Query\AST\ComparisonExpression
2251
     */
2252
    public function ComparisonExpression()
2253
    {
2254
        $peek = $this->_lexer->glimpse();
guilhermeblanco's avatar
guilhermeblanco committed
2255

2256 2257 2258 2259 2260 2261 2262
        $leftExpr = $this->ArithmeticExpression();
        $operator = $this->ComparisonOperator();

        if ($this->_isNextAllAnySome()) {
            $rightExpr = $this->QuantifiedExpression();
        } else {
            $rightExpr = $this->ArithmeticExpression();
2263 2264
        }

2265 2266
        return new AST\ComparisonExpression($leftExpr, $operator, $rightExpr);
    }
guilhermeblanco's avatar
guilhermeblanco committed
2267

2268
    /**
2269
     * InExpression ::= StateFieldPathExpression ["NOT"] "IN" "(" (InParameter {"," InParameter}* | Subselect) ")"
2270 2271
     *
     * @return \Doctrine\ORM\Query\AST\InExpression
2272 2273 2274 2275 2276 2277 2278
     */
    public function InExpression()
    {
        $inExpression = new AST\InExpression($this->StateFieldPathExpression());

        if ($this->_lexer->isNextToken(Lexer::T_NOT)) {
            $this->match(Lexer::T_NOT);
2279
            $inExpression->not = true;
2280 2281 2282 2283 2284 2285
        }

        $this->match(Lexer::T_IN);
        $this->match('(');

        if ($this->_lexer->isNextToken(Lexer::T_SELECT)) {
2286
            $inExpression->subselect = $this->Subselect();
2287 2288
        } else {
            $literals = array();
2289
            $literals[] = $this->InParameter();
2290 2291 2292

            while ($this->_lexer->isNextToken(',')) {
                $this->match(',');
2293
                $literals[] = $this->InParameter();
2294
            }
guilhermeblanco's avatar
guilhermeblanco committed
2295

2296
            $inExpression->literals = $literals;
2297
        }
guilhermeblanco's avatar
guilhermeblanco committed
2298

2299
        $this->match(')');
guilhermeblanco's avatar
guilhermeblanco committed
2300

2301 2302
        return $inExpression;
    }
guilhermeblanco's avatar
guilhermeblanco committed
2303

2304 2305
    /**
     * LikeExpression ::= StringExpression ["NOT"] "LIKE" (string | input_parameter) ["ESCAPE" char]
2306 2307
     *
     * @return \Doctrine\ORM\Query\AST\LikeExpression
2308 2309 2310 2311
     */
    public function LikeExpression()
    {
        $stringExpr = $this->StringExpression();
2312
        $not = false;
guilhermeblanco's avatar
guilhermeblanco committed
2313

2314 2315
        if ($this->_lexer->lookahead['type'] === Lexer::T_NOT) {
            $this->match(Lexer::T_NOT);
2316
            $not = true;
2317
        }
guilhermeblanco's avatar
guilhermeblanco committed
2318

2319
        $this->match(Lexer::T_LIKE);
guilhermeblanco's avatar
guilhermeblanco committed
2320

2321 2322 2323 2324 2325 2326 2327
        if ($this->_lexer->isNextToken(Lexer::T_INPUT_PARAMETER)) {
            $this->match(Lexer::T_INPUT_PARAMETER);
            $stringPattern = new AST\InputParameter($this->_lexer->token['value']);
        } else {
            $this->match(Lexer::T_STRING);
            $stringPattern = $this->_lexer->token['value'];
        }
guilhermeblanco's avatar
guilhermeblanco committed
2328

2329
        $escapeChar = null;
guilhermeblanco's avatar
guilhermeblanco committed
2330

2331 2332 2333 2334
        if ($this->_lexer->lookahead['type'] === Lexer::T_ESCAPE) {
            $this->match(Lexer::T_ESCAPE);
            $this->match(Lexer::T_STRING);
            $escapeChar = $this->_lexer->token['value'];
2335
        }
2336

2337 2338 2339 2340
        $likeExpr = new AST\LikeExpression($stringExpr, $stringPattern, $escapeChar);
        $likeExpr->not = $not;
        
        return $likeExpr;
2341 2342 2343
    }

    /**
2344
     * NullComparisonExpression ::= (SingleValuedPathExpression | InputParameter) "IS" ["NOT"] "NULL"
2345 2346
     *
     * @return \Doctrine\ORM\Query\AST\NullComparisonExpression
2347
     */
2348
    public function NullComparisonExpression()
2349
    {
2350 2351 2352 2353 2354 2355
        if ($this->_lexer->isNextToken(Lexer::T_INPUT_PARAMETER)) {
            $this->match(Lexer::T_INPUT_PARAMETER);
            $expr = new AST\InputParameter($this->_lexer->token['value']);
        } else {
            $expr = $this->SingleValuedPathExpression();
        }
guilhermeblanco's avatar
guilhermeblanco committed
2356

2357 2358
        $nullCompExpr = new AST\NullComparisonExpression($expr);
        $this->match(Lexer::T_IS);
2359

2360 2361
        if ($this->_lexer->isNextToken(Lexer::T_NOT)) {
            $this->match(Lexer::T_NOT);
2362
            $nullCompExpr->not = true;
2363
        }
guilhermeblanco's avatar
guilhermeblanco committed
2364

2365 2366 2367
        $this->match(Lexer::T_NULL);

        return $nullCompExpr;
2368 2369 2370
    }

    /**
2371
     * ExistsExpression ::= ["NOT"] "EXISTS" "(" Subselect ")"
2372 2373
     *
     * @return \Doctrine\ORM\Query\AST\ExistsExpression
2374
     */
2375
    public function ExistsExpression()
2376
    {
2377
        $not = false;
guilhermeblanco's avatar
guilhermeblanco committed
2378

2379 2380 2381 2382 2383 2384 2385 2386
        if ($this->_lexer->isNextToken(Lexer::T_NOT)) {
            $this->match(Lexer::T_NOT);
            $not = true;
        }

        $this->match(Lexer::T_EXISTS);
        $this->match('(');
        $existsExpression = new AST\ExistsExpression($this->Subselect());
2387
        $existsExpression->not = $not;
2388 2389 2390
        $this->match(')');

        return $existsExpression;
2391 2392 2393 2394
    }

    /**
     * ComparisonOperator ::= "=" | "<" | "<=" | "<>" | ">" | ">=" | "!="
2395 2396
     *
     * @return string
2397
     */
romanb's avatar
romanb committed
2398
    public function ComparisonOperator()
2399 2400 2401 2402
    {
        switch ($this->_lexer->lookahead['value']) {
            case '=':
                $this->match('=');
guilhermeblanco's avatar
guilhermeblanco committed
2403

2404
                return '=';
guilhermeblanco's avatar
guilhermeblanco committed
2405

2406 2407 2408
            case '<':
                $this->match('<');
                $operator = '<';
guilhermeblanco's avatar
guilhermeblanco committed
2409

2410 2411 2412 2413 2414 2415 2416
                if ($this->_lexer->isNextToken('=')) {
                    $this->match('=');
                    $operator .= '=';
                } else if ($this->_lexer->isNextToken('>')) {
                    $this->match('>');
                    $operator .= '>';
                }
guilhermeblanco's avatar
guilhermeblanco committed
2417

2418
                return $operator;
guilhermeblanco's avatar
guilhermeblanco committed
2419

2420 2421 2422
            case '>':
                $this->match('>');
                $operator = '>';
guilhermeblanco's avatar
guilhermeblanco committed
2423

2424 2425 2426 2427
                if ($this->_lexer->isNextToken('=')) {
                    $this->match('=');
                    $operator .= '=';
                }
guilhermeblanco's avatar
guilhermeblanco committed
2428

2429
                return $operator;
guilhermeblanco's avatar
guilhermeblanco committed
2430

2431 2432 2433
            case '!':
                $this->match('!');
                $this->match('=');
guilhermeblanco's avatar
guilhermeblanco committed
2434

2435
                return '<>';
guilhermeblanco's avatar
guilhermeblanco committed
2436

2437 2438 2439 2440 2441
            default:
                $this->syntaxError('=, <, <=, <>, >, >=, !=');
        }
    }

2442
    
2443
    /**
2444
     * FunctionDeclaration ::= FunctionsReturningStrings | FunctionsReturningNumerics | FunctionsReturningDatetime
2445
     */
2446
    public function FunctionDeclaration()
2447
    {
2448
        $funcName = $this->_lexer->lookahead['value'];
guilhermeblanco's avatar
guilhermeblanco committed
2449

2450 2451 2452 2453 2454 2455
        if ($this->_isStringFunction($funcName)) {
            return $this->FunctionsReturningStrings();
        } else if ($this->_isNumericFunction($funcName)) {
            return $this->FunctionsReturningNumerics();
        } else if ($this->_isDatetimeFunction($funcName)) {
            return $this->FunctionsReturningDatetime();
2456
        }
2457 2458
        
        $this->syntaxError('Known function.');
2459 2460 2461
    }

    /**
2462 2463 2464 2465 2466 2467 2468
     * FunctionsReturningNumerics ::=
     *      "LENGTH" "(" StringPrimary ")" |
     *      "LOCATE" "(" StringPrimary "," StringPrimary ["," SimpleArithmeticExpression]")" |
     *      "ABS" "(" SimpleArithmeticExpression ")" |
     *      "SQRT" "(" SimpleArithmeticExpression ")" |
     *      "MOD" "(" SimpleArithmeticExpression "," SimpleArithmeticExpression ")" |
     *      "SIZE" "(" CollectionValuedPathExpression ")"
2469
     */
2470
    public function FunctionsReturningNumerics()
2471
    {
2472 2473 2474 2475
        $funcNameLower = strtolower($this->_lexer->lookahead['value']);
        $funcClass = self::$_NUMERIC_FUNCTIONS[$funcNameLower];
        $function = new $funcClass($funcNameLower);
        $function->parse($this);
guilhermeblanco's avatar
guilhermeblanco committed
2476

2477
        return $function;
2478 2479 2480
    }

    /**
2481
     * FunctionsReturningDateTime ::= "CURRENT_DATE" | "CURRENT_TIME" | "CURRENT_TIMESTAMP"
2482
     */
2483
    public function FunctionsReturningDatetime()
2484
    {
2485 2486 2487 2488
        $funcNameLower = strtolower($this->_lexer->lookahead['value']);
        $funcClass = self::$_DATETIME_FUNCTIONS[$funcNameLower];
        $function = new $funcClass($funcNameLower);
        $function->parse($this);
2489

2490
        return $function;
2491
    }
2492
    
2493
    /**
2494 2495 2496 2497 2498 2499
     * FunctionsReturningStrings ::=
     *   "CONCAT" "(" StringPrimary "," StringPrimary ")" |
     *   "SUBSTRING" "(" StringPrimary "," SimpleArithmeticExpression "," SimpleArithmeticExpression ")" |
     *   "TRIM" "(" [["LEADING" | "TRAILING" | "BOTH"] [char] "FROM"] StringPrimary ")" |
     *   "LOWER" "(" StringPrimary ")" |
     *   "UPPER" "(" StringPrimary ")"
2500
     */
2501
    public function FunctionsReturningStrings()
2502
    {
2503 2504 2505 2506
        $funcNameLower = strtolower($this->_lexer->lookahead['value']);
        $funcClass = self::$_STRING_FUNCTIONS[$funcNameLower];
        $function = new $funcClass($funcNameLower);
        $function->parse($this);
2507

2508
        return $function;
2509
    }
2510
}