Parser.php 90.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
<?php
/*
 * 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;

22
use Doctrine\ORM\Query;
23 24

/**
25
 * An LL(*) recursive-descent parser for the context-free grammar of the Doctrine Query Language.
26 27
 * Parses a DQL query, reports any errors in it, and generates an AST.
 *
28 29 30 31 32
 * @since   2.0
 * @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>
33 34 35
 */
class Parser
{
36
    /** READ-ONLY: Maps BUILT-IN string function names to AST class names. */
37
    private static $_STRING_FUNCTIONS = array(
38
        'concat'    => 'Doctrine\ORM\Query\AST\Functions\ConcatFunction',
39
        'substring' => 'Doctrine\ORM\Query\AST\Functions\SubstringFunction',
40 41 42
        'trim'      => 'Doctrine\ORM\Query\AST\Functions\TrimFunction',
        'lower'     => 'Doctrine\ORM\Query\AST\Functions\LowerFunction',
        'upper'     => 'Doctrine\ORM\Query\AST\Functions\UpperFunction'
43
    );
44

45
    /** READ-ONLY: Maps BUILT-IN numeric function names to AST class names. */
46 47 48
    private static $_NUMERIC_FUNCTIONS = array(
        'length' => 'Doctrine\ORM\Query\AST\Functions\LengthFunction',
        'locate' => 'Doctrine\ORM\Query\AST\Functions\LocateFunction',
49 50 51 52
        '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'
53 54
    );

55
    /** READ-ONLY: Maps BUILT-IN datetime function names to AST class names. */
56
    private static $_DATETIME_FUNCTIONS = array(
57 58
        'current_date'      => 'Doctrine\ORM\Query\AST\Functions\CurrentDateFunction',
        'current_time'      => 'Doctrine\ORM\Query\AST\Functions\CurrentTimeFunction',
59 60 61 62
        'current_timestamp' => 'Doctrine\ORM\Query\AST\Functions\CurrentTimestampFunction'
    );

    /**
63
     * Expressions that were encountered during parsing of identifiers and expressions
64 65
     * and still need to be validated.
     */
66 67 68 69
    private $_deferredIdentificationVariables = array();
    private $_deferredPartialObjectExpressions = array();
    private $_deferredPathExpressions = array();
    private $_deferredResultVariables = array();
70 71

    /**
romanb's avatar
romanb committed
72
     * The lexer.
73 74 75 76 77 78
     *
     * @var Doctrine\ORM\Query\Lexer
     */
    private $_lexer;

    /**
romanb's avatar
romanb committed
79
     * The parser result.
80 81 82 83
     *
     * @var Doctrine\ORM\Query\ParserResult
     */
    private $_parserResult;
romanb's avatar
romanb committed
84

85 86 87 88 89 90
    /**
     * The EntityManager.
     *
     * @var EnityManager
     */
    private $_em;
91

92 93 94 95 96 97 98 99
    /**
     * The Query to parse.
     *
     * @var Query
     */
    private $_query;

    /**
romanb's avatar
romanb committed
100
     * Map of declared query components in the parsed query.
101 102 103 104
     *
     * @var array
     */
    private $_queryComponents = array();
105

106 107 108 109 110 111
    /**
     * Keeps the nesting level of defined ResultVariables
     *
     * @var integer
     */
    private $_nestingLevel = 0;
112

113
    /**
114
     * Any additional custom tree walkers that modify the AST.
115
     *
116 117 118
     * @var array
     */
    private $_customTreeWalkers = array();
119

120 121
    /**
     * The custom last tree walker, if any, that is responsible for producing the output.
122
     *
123
     * @var TreeWalker
124
     */
125
    private $_customOutputWalker;
126 127 128 129 130 131 132 133 134 135 136

    /**
     * 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());
137
        $this->_parserResult = new ParserResult();
138 139
    }

140
    /**
141 142
     * Sets a custom tree walker that produces output.
     * This tree walker will be run last over the AST, after any other walkers.
143
     *
144
     * @param string $className
145
     */
146
    public function setCustomOutputTreeWalker($className)
147
    {
148 149
        $this->_customOutputWalker = $className;
    }
150

151 152
    /**
     * Adds a custom tree walker for modifying the AST.
153
     *
154 155 156 157 158
     * @param string $className
     */
    public function addCustomTreeWalker($className)
    {
        $this->_customTreeWalkers[] = $className;
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
    }

    /**
     * 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;
    }
180

181 182 183 184 185 186 187 188 189
    /**
     * Gets the EntityManager used by the parser.
     *
     * @return EntityManager
     */
    public function getEntityManager()
    {
        return $this->_em;
    }
190

191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
    /**
     * Parse and build AST for the given Query.
     *
     * @return \Doctrine\ORM\Query\AST\SelectStatement |
     *         \Doctrine\ORM\Query\AST\UpdateStatement |
     *         \Doctrine\ORM\Query\AST\DeleteStatement
     */
    public function getAST()
    {
        // Parse & build AST
        $AST = $this->QueryLanguage();

        // Process any deferred validations of some nodes in the AST.
        // This also allows post-processing of the AST for modification purposes.
        $this->_processDeferredIdentificationVariables();
206

207 208 209
        if ($this->_deferredPartialObjectExpressions) {
            $this->_processDeferredPartialObjectExpressions();
        }
210

211 212 213
        if ($this->_deferredPathExpressions) {
            $this->_processDeferredPathExpressions($AST);
        }
214

215 216 217 218 219 220 221
        if ($this->_deferredResultVariables) {
            $this->_processDeferredResultVariables();
        }

        return $AST;
    }

222 223 224 225 226 227 228
    /**
     * 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
229 230
     * @return void
     * @throws QueryException If the tokens dont match.
231 232 233
     */
    public function match($token)
    {
234
        if ( ! ($this->_lexer->lookahead['type'] === $token)) {
235
            $this->syntaxError($this->_lexer->getLiteral($token));
236
        }
237 238 239 240 241

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

    /**
romanb's avatar
romanb committed
242 243 244 245
     * Free this parser enabling it to be reused
     *
     * @param boolean $deep     Whether to clean peek and reset errors
     * @param integer $position Position to reset
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
     */
    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
263
     *
264 265 266 267
     * @return ParserResult
     */
    public function parse()
    {
268
        $AST = $this->getAST();
269

270
        if (($customWalkers = $this->_query->getHint(Query::HINT_CUSTOM_TREE_WALKERS)) !== false) {
271 272
            $this->_customTreeWalkers = $customWalkers;
        }
273

274
        if (($customOutputWalker = $this->_query->getHint(Query::HINT_CUSTOM_OUTPUT_WALKER)) !== false) {
275 276 277
            $this->_customOutputWalker = $customOutputWalker;
        }

278 279 280
        // Run any custom tree walkers over the AST
        if ($this->_customTreeWalkers) {
            $treeWalkerChain = new TreeWalkerChain($this->_query, $this->_parserResult, $this->_queryComponents);
281

282 283
            foreach ($this->_customTreeWalkers as $walker) {
                $treeWalkerChain->addTreeWalker($walker);
284
            }
285

286 287 288 289 290 291 292 293
            if ($AST instanceof AST\SelectStatement) {
                $treeWalkerChain->walkSelectStatement($AST);
            } else if ($AST instanceof AST\UpdateStatement) {
                $treeWalkerChain->walkUpdateStatement($AST);
            } else {
                $treeWalkerChain->walkDeleteStatement($AST);
            }
        }
294

295 296 297 298
        if ($this->_customOutputWalker) {
            $outputWalker = new $this->_customOutputWalker(
                $this->_query, $this->_parserResult, $this->_queryComponents
            );
299
        } else {
300
            $outputWalker = new SqlWalker(
301 302
                $this->_query, $this->_parserResult, $this->_queryComponents
            );
303
        }
304 305

        // Assign an SQL executor to the parser result
306
        $this->_parserResult->setSqlExecutor($outputWalker->getExecutor($AST));
307 308 309

        return $this->_parserResult;
    }
310

311 312 313
    /**
     * Generates a new syntax error.
     *
314 315
     * @param string $expected Expected string.
     * @param array $token Got token.
316 317
     *
     * @throws \Doctrine\ORM\Query\QueryException
318 319 320 321 322 323 324
     */
    public function syntaxError($expected = '', $token = null)
    {
        if ($token === null) {
            $token = $this->_lexer->lookahead;
        }

325 326
        $tokenPos = (isset($token['position'])) ? $token['position'] : '-1';
        $message  = "line 0, col {$tokenPos}: Error: ";
327 328

        if ($expected !== '') {
329
            $message .= "Expected {$expected}, got ";
330 331 332 333 334 335 336
        } else {
            $message .= 'Unexpected ';
        }

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

340
        throw QueryException::syntaxError($message);
341 342 343 344 345 346 347
    }

    /**
     * Generates a new semantical error.
     *
     * @param string $message Optional message.
     * @param array $token Optional token.
348 349
     *
     * @throws \Doctrine\ORM\Query\QueryException
350 351 352 353
     */
    public function semanticalError($message = '', $token = null)
    {
        if ($token === null) {
354
            $token = $this->_lexer->lookahead;
355
        }
356

357 358
        // Minimum exposed chars ahead of token
        $distance = 12;
359

360 361
        // Find a position of a final word to display in error string
        $dql = $this->_query->getDql();
362 363 364 365
        $length = strlen($dql);
        $pos = $token['position'] + $distance;
        $pos = strpos($dql, ' ', ($length > $pos) ? $pos : $length);
        $length = ($pos !== false) ? $pos - $token['position'] : $distance;
366

367
        // Building informative message
368 369 370
        $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
371

372
        throw \Doctrine\ORM\Query\QueryException::semanticalError($message);
373
    }
374

375
    /**
376
     * Peeks beyond the specified token and returns the first token after that one.
377 378 379
     *
     * @param array $token
     * @return array
380
     */
381 382 383 384 385 386 387 388 389 390
    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
391

392 393
        return $peek;
    }
394 395

    /**
396
     * Checks if the next-next (after lookahead) token starts a function.
397
     *
398
     * @return boolean TRUE if the next-next tokens start a function, FALSE otherwise.
399
     */
400
    private function _isFunction()
401
    {
romanb's avatar
romanb committed
402
        $peek = $this->_lexer->peek();
403 404
        $nextpeek = $this->_lexer->peek();
        $this->_lexer->resetPeek();
romanb's avatar
romanb committed
405

406 407
        // We deny the COUNT(SELECT * FROM User u) here. COUNT won't be considered a function
        return ($peek['value'] === '(' && $nextpeek['type'] !== Lexer::T_SELECT);
408
    }
409

410
    /**
411
     * Checks whether the given token type indicates an aggregate function.
412
     *
413
     * @return boolean TRUE if the token type is an aggregate function, FALSE otherwise.
414
     */
415
    private function _isAggregateFunction($tokenType)
416
    {
417 418 419
        return $tokenType == Lexer::T_AVG || $tokenType == Lexer::T_MIN ||
               $tokenType == Lexer::T_MAX || $tokenType == Lexer::T_SUM ||
               $tokenType == Lexer::T_COUNT;
420 421
    }

422 423 424 425 426 427 428 429 430 431 432 433 434
    /**
     * 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;
    }

435 436 437 438 439 440 441 442 443
    /**
     * 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
444

445 446
        return ($la['value'] === '(' && $next['type'] === Lexer::T_SELECT);
    }
447

448
    /**
449
     * Validates that the given <tt>IdentificationVariable</tt> is a semantically correct.
450 451
     * It must exist in query components list.
     *
452
     * @return void
453
     */
454
    private function _processDeferredIdentificationVariables()
455
    {
456 457 458 459 460 461
        foreach ($this->_deferredIdentificationVariables as $deferredItem) {
            $identVariable = $deferredItem['expression'];

            // Check if IdentificationVariable exists in queryComponents
            if ( ! isset($this->_queryComponents[$identVariable])) {
                $this->semanticalError(
462
                    "'$identVariable' is not defined.", $deferredItem['token']
463 464 465 466 467 468 469 470
                );
            }

            $qComp = $this->_queryComponents[$identVariable];

            // Check if queryComponent points to an AbstractSchemaName or a ResultVariable
            if ( ! isset($qComp['metadata'])) {
                $this->semanticalError(
471
                    "'$identVariable' does not point to a Class.", $deferredItem['token']
472 473 474 475 476 477
                );
            }

            // Validate if identification variable nesting level is lower or equal than the current one
            if ($qComp['nestingLevel'] > $deferredItem['nestingLevel']) {
                $this->semanticalError(
478
                    "'$identVariable' is used outside the scope of its declaration.", $deferredItem['token']
479 480 481 482 483 484 485 486 487 488 489 490 491
                );
            }
        }
    }

    private function _processDeferredPartialObjectExpressions()
    {
        foreach ($this->_deferredPartialObjectExpressions as $deferredItem) {
            $expr = $deferredItem['expression'];
            $class = $this->_queryComponents[$expr->identificationVariable]['metadata'];
            foreach ($expr->partialFieldSet as $field) {
                if ( ! isset($class->fieldMappings[$field])) {
                    $this->semanticalError(
492 493
                        "There is no mapped field named '$field' on class " . $class->name . ".",
                        $deferredItem['token']
494 495 496 497 498
                    );
                }
            }
            if (array_intersect($class->identifier, $expr->partialFieldSet) != $class->identifier) {
                $this->semanticalError(
499 500
                    "The partial field selection of class " . $class->name . " must contain the identifier.",
                    $deferredItem['token']
501 502
                );
            }
503
        }
504
    }
505

506
    /**
507
     * Validates that the given <tt>ResultVariable</tt> is a semantically correct.
508 509
     * It must exist in query components list.
     *
510
     * @return void
511
     */
512
    private function _processDeferredResultVariables()
513
    {
514 515 516 517 518 519
        foreach ($this->_deferredResultVariables as $deferredItem) {
            $resultVariable = $deferredItem['expression'];

            // Check if ResultVariable exists in queryComponents
            if ( ! isset($this->_queryComponents[$resultVariable])) {
                $this->semanticalError(
520
                    "'$resultVariable' is not defined.", $deferredItem['token']
521 522 523 524 525 526 527 528
                );
            }

            $qComp = $this->_queryComponents[$resultVariable];

            // Check if queryComponent points to an AbstractSchemaName or a ResultVariable
            if ( ! isset($qComp['resultVariable'])) {
                $this->semanticalError(
529
                    "'$identVariable' does not point to a ResultVariable.", $deferredItem['token']
530 531 532 533 534 535
                );
            }

            // Validate if identification variable nesting level is lower or equal than the current one
            if ($qComp['nestingLevel'] > $deferredItem['nestingLevel']) {
                $this->semanticalError(
536
                    "'$resultVariable' is used outside the scope of its declaration.", $deferredItem['token']
537 538
                );
            }
539
        }
540
    }
541

542 543 544 545 546 547 548 549 550
    /**
     * 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
     *
551 552
     * @param array $deferredItem
     * @param mixed $AST
553
     */
554
    private function _processDeferredPathExpressions($AST)
555
    {
556 557 558 559
        foreach ($this->_deferredPathExpressions as $deferredItem) {
            $pathExpression = $deferredItem['expression'];

            $qComp = $this->_queryComponents[$pathExpression->identificationVariable];
560
            $numParts = count($pathExpression->parts);
561

562 563 564 565 566 567
            if ($numParts == 0) {
                $pathExpression->parts = array($qComp['metadata']->identifier[0]);
                $numParts++;
            }
            
            $parts = $pathExpression->parts;
568 569 570
            $aliasIdentificationVariable = $pathExpression->identificationVariable;
            $parentField = $pathExpression->identificationVariable;
            $class = $qComp['metadata'];
571
            $fieldType = null;
572 573 574 575 576 577
            $curIndex = 0;

            foreach ($parts as $field) {
                // Check if it is not in a state field
                if ($fieldType & AST\PathExpression::TYPE_STATE_FIELD) {
                    $this->semanticalError(
578 579
                        'Cannot navigate through state field named ' . $field . ' on ' . $parentField,
                        $deferredItem['token']
580 581 582 583 584 585
                    );
                }

                // Check if it is not a collection field
                if ($fieldType & AST\PathExpression::TYPE_COLLECTION_VALUED_ASSOCIATION) {
                    $this->semanticalError(
586 587
                        'Cannot navigate through collection field named ' . $field . ' on ' . $parentField,
                        $deferredItem['token']
588 589 590 591 592 593
                    );
                }

                // Check if field or association exists
                if ( ! isset($class->associationMappings[$field]) && ! isset($class->fieldMappings[$field])) {
                    $this->semanticalError(
594 595
                        'Class ' . $class->name . ' has no field or association named ' . $field,
                        $deferredItem['token']
596 597 598 599
                    );
                }

                $parentField = $field;
600

601 602 603 604 605 606 607
                if (isset($class->fieldMappings[$field])) {
                    $fieldType = AST\PathExpression::TYPE_STATE_FIELD;
                } else {
                    $assoc = $class->associationMappings[$field];
                    $class = $this->_em->getClassMetadata($assoc->targetEntityName);

                    if (
608 609
                        ($curIndex != $numParts - 1) &&
                        ! isset($this->_queryComponents[$aliasIdentificationVariable . '.' . $field])
610 611 612
                    ) {
                        // Building queryComponent
                        $joinQueryComponent = array(
613 614 615 616 617 618
                        'metadata'     => $class,
                        'parent'       => $aliasIdentificationVariable,
                        'relation'     => $assoc,
                        'map'          => null,
                        'nestingLevel' => $this->_nestingLevel,
                        'token'        => $deferredItem['token'],
619
                        );
620

621 622
                        // Create AST node
                        $joinVariableDeclaration = new AST\JoinVariableDeclaration(
623 624 625 626 627 628 629
                            new AST\Join(
                                AST\Join::JOIN_TYPE_INNER,
                                new AST\JoinAssociationPathExpression($aliasIdentificationVariable, $field),
                                $aliasIdentificationVariable . '.' . $field,
                                false
                            ),
                            null
630
                        );
631
                        
632 633 634 635 636 637 638 639 640 641 642 643
                        $AST->fromClause->identificationVariableDeclarations[0]->joinVariableDeclarations[] = $joinVariableDeclaration;

                        $this->_queryComponents[$aliasIdentificationVariable . '.' . $field] = $joinQueryComponent;
                    }

                    $aliasIdentificationVariable .= '.' . $field;

                    if ($assoc->isOneToOne()) {
                        $fieldType = AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION;
                    } else {
                        $fieldType = AST\PathExpression::TYPE_COLLECTION_VALUED_ASSOCIATION;
                    }
644
                }
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675

                ++$curIndex;
            }

            // Validate if PathExpression is one of the expected types
            $expectedType = $pathExpression->expectedType;

            if ( ! ($expectedType & $fieldType)) {
                // We need to recognize which was expected type(s)
                $expectedStringTypes = array();

                // Validate state field type
                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] . '.';
676
                } else {
677
                    $semanticalError .= implode(' or ', $expectedStringTypes) . ' expected.';
678
                }
679 680

                $this->semanticalError($semanticalError, $deferredItem['token']);
681
            }
682 683 684

            // We need to force the type in PathExpression
            $pathExpression->type = $fieldType;
685
        }
686
    }
687

688 689
    /**
     * QueryLanguage ::= SelectStatement | UpdateStatement | DeleteStatement
690
     *
691 692
     * @return \Doctrine\ORM\Query\AST\SelectStatement |
     *         \Doctrine\ORM\Query\AST\UpdateStatement |
693
     *         \Doctrine\ORM\Query\AST\DeleteStatement
694
     */
romanb's avatar
romanb committed
695
    public function QueryLanguage()
696 697
    {
        $this->_lexer->moveNext();
698

699 700
        switch ($this->_lexer->lookahead['type']) {
            case Lexer::T_SELECT:
701 702
                $statement = $this->SelectStatement();
                break;
703
            case Lexer::T_UPDATE:
704 705
                $statement = $this->UpdateStatement();
                break;
706
            case Lexer::T_DELETE:
707 708
                $statement = $this->DeleteStatement();
                break;
709 710
            default:
                $this->syntaxError('SELECT, UPDATE or DELETE');
711
                break;
712
        }
713

714 715 716 717
        // Check for end of string
        if ($this->_lexer->lookahead !== null) {
            $this->syntaxError('end of string');
        }
718

719
        return $statement;
720 721 722 723
    }

    /**
     * SelectStatement ::= SelectClause FromClause [WhereClause] [GroupByClause] [HavingClause] [OrderByClause]
724 725
     *
     * @return \Doctrine\ORM\Query\AST\SelectStatement
726
     */
romanb's avatar
romanb committed
727
    public function SelectStatement()
728
    {
729
        $selectStatement = new AST\SelectStatement($this->SelectClause(), $this->FromClause());
730

731
        $selectStatement->whereClause = $this->_lexer->isNextToken(Lexer::T_WHERE)
guilhermeblanco's avatar
guilhermeblanco committed
732
            ? $this->WhereClause() : null;
733

734
        $selectStatement->groupByClause = $this->_lexer->isNextToken(Lexer::T_GROUP)
guilhermeblanco's avatar
guilhermeblanco committed
735
            ? $this->GroupByClause() : null;
736

737
        $selectStatement->havingClause = $this->_lexer->isNextToken(Lexer::T_HAVING)
guilhermeblanco's avatar
guilhermeblanco committed
738
            ? $this->HavingClause() : null;
739

740
        $selectStatement->orderByClause = $this->_lexer->isNextToken(Lexer::T_ORDER)
guilhermeblanco's avatar
guilhermeblanco committed
741
            ? $this->OrderByClause() : null;
742

743
        return $selectStatement;
744 745 746
    }

    /**
747
     * UpdateStatement ::= UpdateClause [WhereClause]
748 749
     *
     * @return \Doctrine\ORM\Query\AST\UpdateStatement
750
     */
751
    public function UpdateStatement()
752
    {
753
        $updateStatement = new AST\UpdateStatement($this->UpdateClause());
754
        $updateStatement->whereClause = $this->_lexer->isNextToken(Lexer::T_WHERE)
755
                ? $this->WhereClause() : null;
756 757

        return $updateStatement;
758
    }
759

760 761
    /**
     * DeleteStatement ::= DeleteClause [WhereClause]
762 763
     *
     * @return \Doctrine\ORM\Query\AST\DeleteStatement
764 765 766 767
     */
    public function DeleteStatement()
    {
        $deleteStatement = new AST\DeleteStatement($this->DeleteClause());
768
        $deleteStatement->whereClause = $this->_lexer->isNextToken(Lexer::T_WHERE)
769
                ? $this->WhereClause() : null;
770

771 772
        return $deleteStatement;
    }
773

774
    /**
775
     * IdentificationVariable ::= identifier
776 777
     *
     * @return string
778
     */
779
    public function IdentificationVariable()
780
    {
781
        $this->match(Lexer::T_IDENTIFIER);
guilhermeblanco's avatar
guilhermeblanco committed
782

783
        $identVariable = $this->_lexer->token['value'];
784 785

        $this->_deferredIdentificationVariables[] = array(
786 787 788 789 790 791
            'expression'   => $identVariable,
            'nestingLevel' => $this->_nestingLevel,
            'token'        => $this->_lexer->token,
        );

        return $identVariable;
792
    }
793

794 795
    /**
     * AliasIdentificationVariable = identifier
796 797
     *
     * @return string
798 799 800 801
     */
    public function AliasIdentificationVariable()
    {
        $this->match(Lexer::T_IDENTIFIER);
802

803
        $aliasIdentVariable = $this->_lexer->token['value'];
804
        $exists = isset($this->_queryComponents[$aliasIdentVariable]);
805

806 807 808 809 810
        if ($exists) {
            $this->semanticalError(
                "'$aliasIdentVariable' is already defined.", $this->_lexer->token
            );
        }
guilhermeblanco's avatar
guilhermeblanco committed
811

812
        return $aliasIdentVariable;
813
    }
814

815 816
    /**
     * AbstractSchemaName ::= identifier
817 818
     *
     * @return string
819 820 821 822
     */
    public function AbstractSchemaName()
    {
        $this->match(Lexer::T_IDENTIFIER);
guilhermeblanco's avatar
guilhermeblanco committed
823

824
        $schemaName = $this->_lexer->token['value'];
825 826 827 828

        if (strrpos($schemaName, ':') !== false) {
            list($namespaceAlias, $simpleClassName) = explode(':', $schemaName);
            $schemaName = $this->_em->getConfiguration()->getEntityNamespace($namespaceAlias) . '\\' . $simpleClassName;
829
        }
830

831
        $exists = class_exists($schemaName, true);
832

833 834 835
        if ( ! $exists) {
            $this->semanticalError("Class '$schemaName' is not defined.", $this->_lexer->token);
        }
836 837

        return $schemaName;
838
    }
839

840 841 842 843 844 845 846 847
    /**
     * AliasResultVariable ::= identifier
     *
     * @return string
     */
    public function AliasResultVariable()
    {
        $this->match(Lexer::T_IDENTIFIER);
848

849 850
        $resultVariable = $this->_lexer->token['value'];
        $exists = isset($this->_queryComponents[$resultVariable]);
851

852 853 854 855 856
        if ($exists) {
            $this->semanticalError(
                "'$resultVariable' is already defined.", $this->_lexer->token
            );
        }
857

858 859
        return $resultVariable;
    }
860

861 862
    /**
     * ResultVariable ::= identifier
863 864
     *
     * @return string
865 866 867 868
     */
    public function ResultVariable()
    {
        $this->match(Lexer::T_IDENTIFIER);
869

870
        $resultVariable = $this->_lexer->token['value'];
871

872
        // Defer ResultVariable validation
873 874 875 876
        $this->_deferredResultVariables[] = array(
            'expression'   => $resultVariable,
            'nestingLevel' => $this->_nestingLevel,
            'token'        => $this->_lexer->token,
877
        );
878

879
        return $resultVariable;
880
    }
guilhermeblanco's avatar
guilhermeblanco committed
881

882
    /**
883
     * JoinAssociationPathExpression ::= IdentificationVariable "." (CollectionValuedAssociationField | SingleValuedAssociationField)
884 885
     *
     * @return \Doctrine\ORM\Query\AST\JoinAssociationPathExpression
886
     */
887
    public function JoinAssociationPathExpression()
888
    {
889
        $token = $this->_lexer->lookahead;
890

891
        $identVariable = $this->IdentificationVariable();
892
        $this->match(Lexer::T_DOT);
romanb's avatar
romanb committed
893
        $this->match($this->_lexer->lookahead['type']);
894
        $field = $this->_lexer->token['value'];
romanb's avatar
romanb committed
895

896 897 898
        // Validate association field
        $qComp = $this->_queryComponents[$identVariable];
        $class = $qComp['metadata'];
899

900 901 902 903 904
        if ( ! isset($class->associationMappings[$field])) {
            $this->semanticalError('Class ' . $class->name . ' has no association named ' . $field);
        }

        return new AST\JoinAssociationPathExpression($identVariable, $field);
905
    }
906 907

    /**
908
     * Parses an arbitrary path expression and defers semantical validation
909
     * based on expected types.
910
     *
911
     * PathExpression ::= IdentificationVariable {"." identifier}* "." identifier
912
     *
913
     * @param integer $expectedTypes
914
     * @return \Doctrine\ORM\Query\AST\PathExpression
915
     */
916
    public function PathExpression($expectedTypes)
917
    {
918
        $token = $this->_lexer->lookahead;
919
        $identVariable = $this->IdentificationVariable();
920 921
        $parts = array();

922
        while ($this->_lexer->isNextToken(Lexer::T_DOT)) {
923
            $this->match(Lexer::T_DOT);
924
            $this->match(Lexer::T_IDENTIFIER);
925

926
            $parts[] = $this->_lexer->token['value'];
927
        }
928

929
        // Creating AST node
930
        $pathExpr = new AST\PathExpression($expectedTypes, $identVariable, $parts);
931

932
        // Defer PathExpression validation if requested to be defered
933 934 935 936
        $this->_deferredPathExpressions[] = array(
            'expression'   => $pathExpr,
            'nestingLevel' => $this->_nestingLevel,
            'token'        => $this->_lexer->token,
937 938
        );

939
        return $pathExpr;
940
    }
941

942 943
    /**
     * AssociationPathExpression ::= CollectionValuedPathExpression | SingleValuedAssociationPathExpression
944 945
     *
     * @return \Doctrine\ORM\Query\AST\PathExpression
946 947 948
     */
    public function AssociationPathExpression()
    {
949 950 951 952
        return $this->PathExpression(
            AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION |
            AST\PathExpression::TYPE_COLLECTION_VALUED_ASSOCIATION
        );
953
    }
954

955 956
    /**
     * SingleValuedPathExpression ::= StateFieldPathExpression | SingleValuedAssociationPathExpression
957 958
     *
     * @return \Doctrine\ORM\Query\AST\PathExpression
959 960 961
     */
    public function SingleValuedPathExpression()
    {
962 963 964 965
        return $this->PathExpression(
            AST\PathExpression::TYPE_STATE_FIELD |
            AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION
        );
966
    }
967

968 969
    /**
     * StateFieldPathExpression ::= SimpleStateFieldPathExpression | SimpleStateFieldAssociationPathExpression
970 971
     *
     * @return \Doctrine\ORM\Query\AST\PathExpression
972 973 974
     */
    public function StateFieldPathExpression()
    {
975
        return $this->PathExpression(AST\PathExpression::TYPE_STATE_FIELD);
976
    }
977

978
    /**
979
     * SingleValuedAssociationPathExpression ::= IdentificationVariable "." {SingleValuedAssociationField "."}* SingleValuedAssociationField
980 981
     *
     * @return \Doctrine\ORM\Query\AST\PathExpression
982
     */
983
    public function SingleValuedAssociationPathExpression()
984
    {
985
        return $this->PathExpression(AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION);
986
    }
987

988 989
    /**
     * CollectionValuedPathExpression ::= IdentificationVariable "." {SingleValuedAssociationField "."}* CollectionValuedAssociationField
990 991
     *
     * @return \Doctrine\ORM\Query\AST\PathExpression
992 993 994
     */
    public function CollectionValuedPathExpression()
    {
995
        return $this->PathExpression(AST\PathExpression::TYPE_COLLECTION_VALUED_ASSOCIATION);
996
    }
997

998 999
    /**
     * SimpleStateFieldPathExpression ::= IdentificationVariable "." StateField
1000 1001
     *
     * @return \Doctrine\ORM\Query\AST\PathExpression
1002 1003 1004
     */
    public function SimpleStateFieldPathExpression()
    {
1005
        $pathExpression = $this->PathExpression(AST\PathExpression::TYPE_STATE_FIELD);
1006
        $parts = $pathExpression->parts;
1007

1008 1009
        if (count($parts) > 1) {
            $this->semanticalError(
1010
                "Invalid SimpleStateFieldPathExpression. " .
1011 1012 1013
                "Expected state field, got association '{$parts[0]}'."
            );
        }
1014

1015
        return $pathExpression;
1016 1017
    }

1018 1019
    /**
     * SelectClause ::= "SELECT" ["DISTINCT"] SelectExpression {"," SelectExpression}
1020 1021
     *
     * @return \Doctrine\ORM\Query\AST\SelectClause
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
     */
    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();

1038 1039
        while ($this->_lexer->isNextToken(Lexer::T_COMMA)) {
            $this->match(Lexer::T_COMMA);
1040 1041 1042 1043 1044 1045 1046 1047
            $selectExpressions[] = $this->SelectExpression();
        }

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

    /**
     * SimpleSelectClause ::= "SELECT" ["DISTINCT"] SimpleSelectExpression
1048 1049
     *
     * @return \Doctrine\ORM\Query\AST\SimpleSelectClause
1050 1051 1052
     */
    public function SimpleSelectClause()
    {
1053
        $isDistinct = false;
1054 1055 1056 1057
        $this->match(Lexer::T_SELECT);

        if ($this->_lexer->isNextToken(Lexer::T_DISTINCT)) {
            $this->match(Lexer::T_DISTINCT);
1058
            $isDistinct = true;
1059 1060
        }

1061
        return new AST\SimpleSelectClause($this->SimpleSelectExpression(), $isDistinct);
1062 1063
    }

1064
    /**
1065
     * UpdateClause ::= "UPDATE" AbstractSchemaName ["AS"] AliasIdentificationVariable "SET" UpdateItem {"," UpdateItem}*
1066 1067
     *
     * @return \Doctrine\ORM\Query\AST\UpdateClause
1068
     */
romanb's avatar
romanb committed
1069
    public function UpdateClause()
1070 1071
    {
        $this->match(Lexer::T_UPDATE);
1072
        $token = $this->_lexer->lookahead;
romanb's avatar
romanb committed
1073
        $abstractSchemaName = $this->AbstractSchemaName();
1074

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

1079
        $aliasIdentificationVariable = $this->AliasIdentificationVariable();
1080

1081
        $class = $this->_em->getClassMetadata($abstractSchemaName);
guilhermeblanco's avatar
guilhermeblanco committed
1082

1083 1084
        // Building queryComponent
        $queryComponent = array(
1085
            'metadata'     => $class,
1086 1087 1088 1089
            'parent'       => null,
            'relation'     => null,
            'map'          => null,
            'nestingLevel' => $this->_nestingLevel,
1090
            'token'        => $token,
1091 1092 1093
        );
        $this->_queryComponents[$aliasIdentificationVariable] = $queryComponent;

1094
        $this->match(Lexer::T_SET);
1095

1096 1097 1098
        $updateItems = array();
        $updateItems[] = $this->UpdateItem();

1099 1100
        while ($this->_lexer->isNextToken(Lexer::T_COMMA)) {
            $this->match(Lexer::T_COMMA);
1101 1102 1103
            $updateItems[] = $this->UpdateItem();
        }

1104
        $updateClause = new AST\UpdateClause($abstractSchemaName, $updateItems);
1105
        $updateClause->aliasIdentificationVariable = $aliasIdentificationVariable;
1106 1107 1108 1109 1110

        return $updateClause;
    }

    /**
1111
     * DeleteClause ::= "DELETE" ["FROM"] AbstractSchemaName ["AS"] AliasIdentificationVariable
1112 1113
     *
     * @return \Doctrine\ORM\Query\AST\DeleteClause
1114
     */
romanb's avatar
romanb committed
1115
    public function DeleteClause()
1116 1117
    {
        $this->match(Lexer::T_DELETE);
guilhermeblanco's avatar
guilhermeblanco committed
1118

1119 1120 1121
        if ($this->_lexer->isNextToken(Lexer::T_FROM)) {
            $this->match(Lexer::T_FROM);
        }
guilhermeblanco's avatar
guilhermeblanco committed
1122

1123
        $token = $this->_lexer->lookahead;
romanb's avatar
romanb committed
1124
        $deleteClause = new AST\DeleteClause($this->AbstractSchemaName());
1125

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

1130
        $aliasIdentificationVariable = $this->AliasIdentificationVariable();
1131

1132 1133
        $deleteClause->aliasIdentificationVariable = $aliasIdentificationVariable;
        $class = $this->_em->getClassMetadata($deleteClause->abstractSchemaName);
1134

1135
        // Building queryComponent
1136
        $queryComponent = array(
1137
            'metadata'     => $class,
1138 1139 1140 1141
            'parent'       => null,
            'relation'     => null,
            'map'          => null,
            'nestingLevel' => $this->_nestingLevel,
1142
            'token'        => $token,
1143
        );
1144
        $this->_queryComponents[$aliasIdentificationVariable] = $queryComponent;
1145 1146 1147 1148 1149

        return $deleteClause;
    }

    /**
1150
     * FromClause ::= "FROM" IdentificationVariableDeclaration {"," IdentificationVariableDeclaration}*
1151 1152
     *
     * @return \Doctrine\ORM\Query\AST\FromClause
1153
     */
1154
    public function FromClause()
1155
    {
1156 1157 1158 1159
        $this->match(Lexer::T_FROM);
        $identificationVariableDeclarations = array();
        $identificationVariableDeclarations[] = $this->IdentificationVariableDeclaration();

1160 1161
        while ($this->_lexer->isNextToken(Lexer::T_COMMA)) {
            $this->match(Lexer::T_COMMA);
1162
            $identificationVariableDeclarations[] = $this->IdentificationVariableDeclaration();
1163 1164
        }

1165 1166 1167 1168 1169
        return new AST\FromClause($identificationVariableDeclarations);
    }

    /**
     * SubselectFromClause ::= "FROM" SubselectIdentificationVariableDeclaration {"," SubselectIdentificationVariableDeclaration}*
1170 1171
     *
     * @return \Doctrine\ORM\Query\AST\SubselectFromClause
1172 1173 1174 1175 1176 1177
     */
    public function SubselectFromClause()
    {
        $this->match(Lexer::T_FROM);
        $identificationVariables = array();
        $identificationVariables[] = $this->SubselectIdentificationVariableDeclaration();
guilhermeblanco's avatar
guilhermeblanco committed
1178

1179 1180
        while ($this->_lexer->isNextToken(Lexer::T_COMMA)) {
            $this->match(Lexer::T_COMMA);
1181
            $identificationVariables[] = $this->SubselectIdentificationVariableDeclaration();
1182 1183
        }

1184
        return new AST\SubselectFromClause($identificationVariables);
1185 1186 1187
    }

    /**
1188
     * WhereClause ::= "WHERE" ConditionalExpression
1189 1190
     *
     * @return \Doctrine\ORM\Query\AST\WhereClause
1191
     */
1192
    public function WhereClause()
1193
    {
1194 1195 1196 1197 1198 1199 1200
        $this->match(Lexer::T_WHERE);

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

    /**
     * HavingClause ::= "HAVING" ConditionalExpression
1201 1202
     *
     * @return \Doctrine\ORM\Query\AST\HavingClause
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
     */
    public function HavingClause()
    {
        $this->match(Lexer::T_HAVING);

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

    /**
     * GroupByClause ::= "GROUP" "BY" GroupByItem {"," GroupByItem}*
1213 1214
     *
     * @return \Doctrine\ORM\Query\AST\GroupByClause
1215 1216 1217 1218 1219 1220 1221
     */
    public function GroupByClause()
    {
        $this->match(Lexer::T_GROUP);
        $this->match(Lexer::T_BY);

        $groupByItems = array($this->GroupByItem());
1222

1223 1224
        while ($this->_lexer->isNextToken(Lexer::T_COMMA)) {
            $this->match(Lexer::T_COMMA);
1225
            $groupByItems[] = $this->GroupByItem();
1226 1227
        }

1228 1229
        return new AST\GroupByClause($groupByItems);
    }
1230

1231 1232
    /**
     * OrderByClause ::= "ORDER" "BY" OrderByItem {"," OrderByItem}*
1233 1234
     *
     * @return \Doctrine\ORM\Query\AST\OrderByClause
1235 1236 1237 1238 1239 1240 1241 1242 1243
     */
    public function OrderByClause()
    {
        $this->match(Lexer::T_ORDER);
        $this->match(Lexer::T_BY);

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

1244 1245
        while ($this->_lexer->isNextToken(Lexer::T_COMMA)) {
            $this->match(Lexer::T_COMMA);
1246 1247 1248 1249
            $orderByItems[] = $this->OrderByItem();
        }

        return new AST\OrderByClause($orderByItems);
1250 1251 1252
    }

    /**
1253
     * Subselect ::= SimpleSelectClause SubselectFromClause [WhereClause] [GroupByClause] [HavingClause] [OrderByClause]
1254 1255
     *
     * @return \Doctrine\ORM\Query\AST\Subselect
1256
     */
1257 1258
    public function Subselect()
    {
1259 1260
        // Increase query nesting level
        $this->_nestingLevel++;
1261

1262
        $subselect = new AST\Subselect($this->SimpleSelectClause(), $this->SubselectFromClause());
1263 1264

        $subselect->whereClause = $this->_lexer->isNextToken(Lexer::T_WHERE)
1265
            ? $this->WhereClause() : null;
1266 1267

        $subselect->groupByClause = $this->_lexer->isNextToken(Lexer::T_GROUP)
1268
            ? $this->GroupByClause() : null;
1269 1270

        $subselect->havingClause = $this->_lexer->isNextToken(Lexer::T_HAVING)
1271
            ? $this->HavingClause() : null;
1272 1273

        $subselect->orderByClause = $this->_lexer->isNextToken(Lexer::T_ORDER)
1274
            ? $this->OrderByClause() : null;
1275

1276 1277
        // Decrease query nesting level
        $this->_nestingLevel--;
1278 1279 1280 1281 1282

        return $subselect;
    }

    /**
1283
     * UpdateItem ::= IdentificationVariable "." {StateField | SingleValuedAssociationField} "=" NewValue
1284 1285
     *
     * @return \Doctrine\ORM\Query\AST\UpdateItem
1286 1287
     */
    public function UpdateItem()
1288
    {
1289
        $token = $this->_lexer->lookahead;
1290

1291
        $identVariable = $this->IdentificationVariable();
1292
        $this->match(Lexer::T_DOT);
1293 1294
        $this->match(Lexer::T_IDENTIFIER);
        $field = $this->_lexer->token['value'];
1295

1296
        // Check if field exists
1297
        $class = $this->_queryComponents[$identVariable]['metadata'];
1298

1299 1300 1301 1302 1303
        if ( ! isset($class->associationMappings[$field]) && ! isset($class->fieldMappings[$field])) {
            $this->semanticalError(
                'Class ' . $class->name . ' has no field named ' . $field, $token
            );
        }
1304

1305
        $this->match(Lexer::T_EQUALS);
1306

1307
        $newValue = $this->NewValue();
guilhermeblanco's avatar
guilhermeblanco committed
1308

1309
        $updateItem = new AST\UpdateItem($field, $newValue);
1310
        $updateItem->identificationVariable = $identVariable;
1311 1312 1313 1314 1315 1316

        return $updateItem;
    }

    /**
     * GroupByItem ::= IdentificationVariable | SingleValuedPathExpression
1317 1318
     *
     * @return string | \Doctrine\ORM\Query\AST\PathExpression
1319 1320 1321
     */
    public function GroupByItem()
    {
1322 1323
        // We need to check if we are in a IdentificationVariable or SingleValuedPathExpression
        $glimpse = $this->_lexer->glimpse();
1324

1325
        if ($glimpse['value'] != '.') {
1326
            $token = $this->_lexer->lookahead;
1327
            $identVariable = $this->IdentificationVariable();
1328

1329
            return $identVariable;
1330
        }
1331

1332 1333 1334 1335 1336 1337
        return $this->SingleValuedPathExpression();
    }

    /**
     * OrderByItem ::= (ResultVariable | StateFieldPathExpression) ["ASC" | "DESC"]
     *
1338
     * @todo Post 2.0 release. Support general SingleValuedPathExpression instead
1339
     * of only StateFieldPathExpression.
1340 1341
     *
     * @return \Doctrine\ORM\Query\AST\OrderByItem
1342 1343 1344
     */
    public function OrderByItem()
    {
1345
        $type = 'ASC';
1346

1347 1348
        // We need to check if we are in a ResultVariable or StateFieldPathExpression
        $glimpse = $this->_lexer->glimpse();
1349

1350
        if ($glimpse['value'] != '.') {
1351
            $token = $this->_lexer->lookahead;
1352
            $expr = $this->ResultVariable();
1353
        } else {
1354 1355
            $expr = $this->StateFieldPathExpression();
        }
1356

1357
        $item = new AST\OrderByItem($expr);
1358

1359 1360
        if ($this->_lexer->isNextToken(Lexer::T_ASC)) {
            $this->match(Lexer::T_ASC);
1361
        } else if ($this->_lexer->isNextToken(Lexer::T_DESC)) {
1362
            $this->match(Lexer::T_DESC);
1363
            $type = 'DESC';
1364
        }
1365

1366
        $item->type = $type;
1367 1368
        return $item;
    }
guilhermeblanco's avatar
guilhermeblanco committed
1369

1370 1371 1372 1373 1374 1375
    /**
     * 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:
1376
     *
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
     * 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']);
        }
1390

1391
        return $this->SimpleArithmeticExpression();
1392 1393 1394 1395
    }

    /**
     * IdentificationVariableDeclaration ::= RangeVariableDeclaration [IndexBy] {JoinVariableDeclaration}*
1396 1397
     *
     * @return \Doctrine\ORM\Query\AST\IdentificationVariableDeclaration
1398
     */
romanb's avatar
romanb committed
1399
    public function IdentificationVariableDeclaration()
1400
    {
romanb's avatar
romanb committed
1401 1402
        $rangeVariableDeclaration = $this->RangeVariableDeclaration();
        $indexBy = $this->_lexer->isNextToken(Lexer::T_INDEX) ? $this->IndexBy() : null;
1403
        $joinVariableDeclarations = array();
guilhermeblanco's avatar
guilhermeblanco committed
1404

1405
        while (
guilhermeblanco's avatar
guilhermeblanco committed
1406 1407 1408
            $this->_lexer->isNextToken(Lexer::T_LEFT) ||
            $this->_lexer->isNextToken(Lexer::T_INNER) ||
            $this->_lexer->isNextToken(Lexer::T_JOIN)
1409
        ) {
romanb's avatar
romanb committed
1410
            $joinVariableDeclarations[] = $this->JoinVariableDeclaration();
1411 1412 1413
        }

        return new AST\IdentificationVariableDeclaration(
guilhermeblanco's avatar
guilhermeblanco committed
1414
            $rangeVariableDeclaration, $indexBy, $joinVariableDeclarations
1415 1416 1417
        );
    }

1418 1419
    /**
     * SubselectIdentificationVariableDeclaration ::= IdentificationVariableDeclaration | (AssociationPathExpression ["AS"] AliasIdentificationVariable)
1420 1421 1422
     *
     * @return \Doctrine\ORM\Query\AST\SubselectIdentificationVariableDeclaration |
     *         \Doctrine\ORM\Query\AST\IdentificationVariableDeclaration
1423 1424 1425 1426 1427 1428
     */
    public function SubselectIdentificationVariableDeclaration()
    {
        $peek = $this->_lexer->glimpse();

        if ($peek['value'] == '.') {
1429 1430
            $subselectIdVarDecl = new AST\SubselectIdentificationVariableDeclaration();
            $subselectIdVarDecl->associationPathExpression = $this->AssociationPathExpression();
1431
            $this->match(Lexer::T_AS);
1432
            $subselectIdVarDecl->aliasIdentificationVariable = $this->AliasIdentificationVariable();
1433

1434
            return $subselectIdVarDecl;
1435 1436 1437 1438 1439 1440 1441
        }

        return $this->IdentificationVariableDeclaration();
    }

    /**
     * JoinVariableDeclaration ::= Join [IndexBy]
1442 1443
     *
     * @return \Doctrine\ORM\Query\AST\JoinVariableDeclaration
1444 1445 1446 1447 1448
     */
    public function JoinVariableDeclaration()
    {
        $join = $this->Join();
        $indexBy = $this->_lexer->isNextToken(Lexer::T_INDEX)
1449
                ? $this->IndexBy() : null;
1450 1451 1452 1453

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

1454 1455
    /**
     * RangeVariableDeclaration ::= AbstractSchemaName ["AS"] AliasIdentificationVariable
1456
     *
1457
     * @return Doctrine\ORM\Query\AST\RangeVariableDeclaration
1458
     */
romanb's avatar
romanb committed
1459
    public function RangeVariableDeclaration()
1460
    {
romanb's avatar
romanb committed
1461
        $abstractSchemaName = $this->AbstractSchemaName();
1462

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

1467
        $token = $this->_lexer->lookahead;
romanb's avatar
romanb committed
1468
        $aliasIdentificationVariable = $this->AliasIdentificationVariable();
1469 1470 1471 1472
        $classMetadata = $this->_em->getClassMetadata($abstractSchemaName);

        // Building queryComponent
        $queryComponent = array(
1473 1474 1475 1476 1477
            'metadata'     => $classMetadata,
            'parent'       => null,
            'relation'     => null,
            'map'          => null,
            'nestingLevel' => $this->_nestingLevel,
1478
            'token'        => $token
1479 1480
        );
        $this->_queryComponents[$aliasIdentificationVariable] = $queryComponent;
guilhermeblanco's avatar
guilhermeblanco committed
1481

1482
        return new AST\RangeVariableDeclaration($abstractSchemaName, $aliasIdentificationVariable);
1483 1484
    }

1485 1486 1487
    /**
     * PartialObjectExpression ::= "PARTIAL" IdentificationVariable "." PartialFieldSet
     * PartialFieldSet ::= "{" SimpleStateField {"," SimpleStateField}* "}"
1488
     *
1489 1490 1491 1492
     * @return array
     */
    public function PartialObjectExpression()
    {
1493
        $this->match(Lexer::T_PARTIAL);
1494 1495 1496 1497 1498

        $partialFieldSet = array();

        $identificationVariable = $this->IdentificationVariable();
        $this->match(Lexer::T_DOT);
1499

1500 1501 1502 1503 1504 1505 1506 1507 1508
        $this->match(Lexer::T_OPEN_CURLY_BRACE);
        $this->match(Lexer::T_IDENTIFIER);
        $partialFieldSet[] = $this->_lexer->token['value'];
        while ($this->_lexer->isNextToken(Lexer::T_COMMA)) {
            $this->match(Lexer::T_COMMA);
            $this->match(Lexer::T_IDENTIFIER);
            $partialFieldSet[] = $this->_lexer->token['value'];
        }
        $this->match(Lexer::T_CLOSE_CURLY_BRACE);
1509

1510
        $partialObjectExpression = new AST\PartialObjectExpression($identificationVariable, $partialFieldSet);
1511

1512 1513 1514 1515 1516 1517
        // Defer PartialObjectExpression validation
        $this->_deferredPartialObjectExpressions[] = array(
            'expression'   => $partialObjectExpression,
            'nestingLevel' => $this->_nestingLevel,
            'token'        => $this->_lexer->token,
        );
1518

1519 1520 1521
        return $partialObjectExpression;
    }

1522
    /**
1523
     * Join ::= ["LEFT" ["OUTER"] | "INNER"] "JOIN" JoinAssociationPathExpression
1524
     *          ["AS"] AliasIdentificationVariable ["WITH" ConditionalExpression]
1525
     *
1526
     * @return Doctrine\ORM\Query\AST\Join
1527
     */
romanb's avatar
romanb committed
1528
    public function Join()
1529 1530 1531
    {
        // Check Join type
        $joinType = AST\Join::JOIN_TYPE_INNER;
guilhermeblanco's avatar
guilhermeblanco committed
1532

1533 1534
        if ($this->_lexer->isNextToken(Lexer::T_LEFT)) {
            $this->match(Lexer::T_LEFT);
guilhermeblanco's avatar
guilhermeblanco committed
1535

1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
            // 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);
1548

1549
        $joinPathExpression = $this->JoinAssociationPathExpression();
guilhermeblanco's avatar
guilhermeblanco committed
1550

1551 1552 1553 1554
        if ($this->_lexer->isNextToken(Lexer::T_AS)) {
            $this->match(Lexer::T_AS);
        }

1555
        $token = $this->_lexer->lookahead;
romanb's avatar
romanb committed
1556
        $aliasIdentificationVariable = $this->AliasIdentificationVariable();
1557 1558

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

1562
        if ( ! $parentClass->hasAssociation($assocField)) {
guilhermeblanco's avatar
guilhermeblanco committed
1563 1564 1565
            $this->semanticalError(
                "Class " . $parentClass->name . " has no association named '$assocField'."
            );
1566
        }
guilhermeblanco's avatar
guilhermeblanco committed
1567

1568
        $targetClassName = $parentClass->getAssociationMapping($assocField)->targetEntityName;
1569 1570 1571

        // Building queryComponent
        $joinQueryComponent = array(
1572
            'metadata'     => $this->_em->getClassMetadata($targetClassName),
1573
            'parent'       => $joinPathExpression->identificationVariable,
1574 1575 1576
            'relation'     => $parentClass->getAssociationMapping($assocField),
            'map'          => null,
            'nestingLevel' => $this->_nestingLevel,
1577
            'token'        => $token
1578 1579 1580 1581 1582 1583 1584
        );
        $this->_queryComponents[$aliasIdentificationVariable] = $joinQueryComponent;

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

        // Check for ad-hoc Join conditions
1585 1586
        if ($this->_lexer->isNextToken(Lexer::T_WITH)) {
            $this->match(Lexer::T_WITH);
1587
            $join->conditionalExpression = $this->ConditionalExpression();
1588 1589 1590 1591 1592 1593 1594
        }

        return $join;
    }

    /**
     * IndexBy ::= "INDEX" "BY" SimpleStateFieldPathExpression
1595
     *
1596
     * @return Doctrine\ORM\Query\AST\IndexBy
1597
     */
romanb's avatar
romanb committed
1598
    public function IndexBy()
1599 1600 1601
    {
        $this->match(Lexer::T_INDEX);
        $this->match(Lexer::T_BY);
romanb's avatar
romanb committed
1602
        $pathExp = $this->SimpleStateFieldPathExpression();
guilhermeblanco's avatar
guilhermeblanco committed
1603

1604
        // Add the INDEX BY info to the query component
1605 1606
        $parts = $pathExp->parts;
        $this->_queryComponents[$pathExp->identificationVariable]['map'] = $parts[0];
guilhermeblanco's avatar
guilhermeblanco committed
1607

1608 1609 1610
        return $pathExp;
    }

1611 1612 1613 1614
    /**
     * ScalarExpression ::= SimpleArithmeticExpression | StringPrimary | DateTimePrimary |
     *                      StateFieldPathExpression | BooleanPrimary | CaseExpression |
     *                      EntityTypeExpression
1615
     *
1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
     * @return mixed One of the possible expressions or subexpressions.
     */
    public function ScalarExpression()
    {
        $lookahead = $this->_lexer->lookahead['type'];
        if ($lookahead === Lexer::T_IDENTIFIER) {
            $this->_lexer->peek(); // lookahead => '.'
            $this->_lexer->peek(); // lookahead => token after '.'
            $peek = $this->_lexer->peek(); // lookahead => token after the token after the '.'
            $this->_lexer->resetPeek();
1626

1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658
            if ($peek['value'] == '+' || $peek['value'] == '-' || $peek['value'] == '/' || $peek['value'] == '*') {
                return $this->SimpleArithmeticExpression();
            }

            return $this->StateFieldPathExpression();
        } else if ($lookahead == Lexer::T_INTEGER || $lookahead == Lexer::T_FLOAT) {
            return $this->SimpleArithmeticExpression();
        } else if ($this->_isFunction()) {
            return $this->FunctionDeclaration();
        } else if ($lookahead == Lexer::T_STRING) {
            return $this->StringPrimary();
        } else if ($lookahead == Lexer::T_INPUT_PARAMETER) {
            return $this->InputParameter();
        } else if ($lookahead == Lexer::T_TRUE || $lookahead == Lexer::T_FALSE) {
            $this->match($lookahead);
            return new AST\Literal(AST\Literal::BOOLEAN, $this->_lexer->token['value']);
        } else if ($lookahead == Lexer::T_CASE || $lookahead == Lexer::T_COALESCE || $lookahead == Lexer::T_NULLIF) {
            return $this->CaseExpression();
        } else {
            $this->syntaxError();
        }
    }

    public function CaseExpression()
    {
        // if "CASE" "WHEN" => GeneralCaseExpression
        // else if "CASE" => SimpleCaseExpression
        // else if "COALESCE" => CoalesceExpression
        // else if "NULLIF" => NullifExpression
        $this->semanticalError('CaseExpression not yet supported.');
    }

1659
    /**
1660 1661
     * SelectExpression ::=
     *      IdentificationVariable | StateFieldPathExpression |
1662
     *      (AggregateExpression | "(" Subselect ")" | ScalarExpression) [["AS"] AliasResultVariable]
1663
     *
1664
     * @return Doctrine\ORM\Query\AST\SelectExpression
1665
     */
1666
    public function SelectExpression()
1667
    {
1668 1669 1670
        $expression = null;
        $fieldAliasIdentificationVariable = null;
        $peek = $this->_lexer->glimpse();
guilhermeblanco's avatar
guilhermeblanco committed
1671

1672 1673 1674 1675 1676
        $supportsAlias = true;
        if ($peek['value'] != '(' && $this->_lexer->lookahead['type'] === Lexer::T_IDENTIFIER) {
            if ($peek['value'] == '.') {
                // ScalarExpression
                $expression = $this->ScalarExpression();
1677
            } else {
1678 1679 1680 1681 1682 1683
                $supportsAlias = false;
                $expression = $this->IdentificationVariable();
            }
        } else if ($this->_lexer->lookahead['value'] == '(') {
            if ($peek['type'] == Lexer::T_SELECT) {
                // Subselect
1684
                $this->match(Lexer::T_OPEN_PARENTHESIS);
1685
                $expression = $this->Subselect();
1686
                $this->match(Lexer::T_CLOSE_PARENTHESIS);
1687 1688 1689
            } else {
                // Shortcut: ScalarExpression => SimpleArithmeticExpression
                $expression = $this->SimpleArithmeticExpression();
1690
            }
1691 1692 1693 1694
        } else if ($this->_isFunction()) {
            if ($this->_isAggregateFunction($this->_lexer->lookahead['type'])) {
                $expression = $this->AggregateExpression();
            } else {
1695
                // Shortcut: ScalarExpression => Function
1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709
                $expression = $this->FunctionDeclaration();
            }
        } else if ($this->_lexer->lookahead['type'] == Lexer::T_PARTIAL) {
            $supportsAlias = false;
            $expression = $this->PartialObjectExpression();
        } else if ($this->_lexer->lookahead['type'] == Lexer::T_INTEGER ||
                $this->_lexer->lookahead['type'] == Lexer::T_FLOAT) {
            // Shortcut: ScalarExpression => SimpleArithmeticExpression
            $expression = $this->SimpleArithmeticExpression();
        } else {
            $this->syntaxError('IdentificationVariable | StateFieldPathExpression'
                    . ' | AggregateExpression | "(" Subselect ")" | ScalarExpression',
                    $this->_lexer->lookahead);
        }
1710

1711
        if ($supportsAlias) {
1712 1713 1714
            if ($this->_lexer->isNextToken(Lexer::T_AS)) {
                $this->match(Lexer::T_AS);
            }
guilhermeblanco's avatar
guilhermeblanco committed
1715

1716
            if ($this->_lexer->isNextToken(Lexer::T_IDENTIFIER)) {
1717
                $token = $this->_lexer->lookahead;
1718
                $fieldAliasIdentificationVariable = $this->AliasResultVariable();
1719

1720
                // Include AliasResultVariable in query components.
1721
                $this->_queryComponents[$fieldAliasIdentificationVariable] = array(
1722
                    'resultVariable' => $expression,
1723
                    'nestingLevel'   => $this->_nestingLevel,
1724
                    'token'          => $token,
1725
                );
1726
            }
1727
        }
guilhermeblanco's avatar
guilhermeblanco committed
1728

1729
        return new AST\SelectExpression($expression, $fieldAliasIdentificationVariable);
1730 1731 1732
    }

    /**
1733
     * SimpleSelectExpression ::= StateFieldPathExpression | IdentificationVariable | (AggregateExpression [["AS"] AliasResultVariable])
1734 1735
     *
     * @return \Doctrine\ORM\Query\AST\SimpleSelectExpression
1736
     */
1737
    public function SimpleSelectExpression()
1738
    {
1739 1740 1741 1742 1743 1744 1745 1746
        if ($this->_lexer->isNextToken(Lexer::T_IDENTIFIER)) {
            // SingleValuedPathExpression | IdentificationVariable
            $peek = $this->_lexer->glimpse();

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

1747
            $this->match(Lexer::T_IDENTIFIER);
1748 1749

            return new AST\SimpleSelectExpression($this->_lexer->token['value']);
1750
        }
1751

1752
        $expr = new AST\SimpleSelectExpression($this->AggregateExpression());
guilhermeblanco's avatar
guilhermeblanco committed
1753

1754 1755 1756
        if ($this->_lexer->isNextToken(Lexer::T_AS)) {
            $this->match(Lexer::T_AS);
        }
1757

1758
        if ($this->_lexer->isNextToken(Lexer::T_IDENTIFIER)) {
1759
            $token = $this->_lexer->lookahead;
1760
            $resultVariable = $this->AliasResultVariable();
1761
            $expr->fieldIdentificationVariable = $resultVariable;
1762

1763
            // Include AliasResultVariable in query components.
1764
            $this->_queryComponents[$resultVariable] = array(
1765 1766
                'resultvariable' => $expr,
                'nestingLevel'   => $this->_nestingLevel,
1767
                'token'          => $token,
1768
            );
1769
        }
1770 1771

        return $expr;
1772 1773 1774 1775
    }

    /**
     * ConditionalExpression ::= ConditionalTerm {"OR" ConditionalTerm}*
1776 1777
     *
     * @return \Doctrine\ORM\Query\AST\ConditionalExpression
1778
     */
romanb's avatar
romanb committed
1779
    public function ConditionalExpression()
1780 1781
    {
        $conditionalTerms = array();
romanb's avatar
romanb committed
1782
        $conditionalTerms[] = $this->ConditionalTerm();
guilhermeblanco's avatar
guilhermeblanco committed
1783

1784 1785
        while ($this->_lexer->isNextToken(Lexer::T_OR)) {
            $this->match(Lexer::T_OR);
romanb's avatar
romanb committed
1786
            $conditionalTerms[] = $this->ConditionalTerm();
1787
        }
guilhermeblanco's avatar
guilhermeblanco committed
1788

1789 1790 1791 1792 1793 1794
        // Phase 1 AST optimization: Prevent AST\ConditionalExpression
        // if only one AST\ConditionalTerm is defined
        if (count($conditionalTerms) == 1) {
            return $conditionalTerms[0];
        }

1795 1796 1797 1798 1799
        return new AST\ConditionalExpression($conditionalTerms);
    }

    /**
     * ConditionalTerm ::= ConditionalFactor {"AND" ConditionalFactor}*
1800 1801
     *
     * @return \Doctrine\ORM\Query\AST\ConditionalTerm
1802
     */
romanb's avatar
romanb committed
1803
    public function ConditionalTerm()
1804 1805
    {
        $conditionalFactors = array();
romanb's avatar
romanb committed
1806
        $conditionalFactors[] = $this->ConditionalFactor();
guilhermeblanco's avatar
guilhermeblanco committed
1807

1808 1809
        while ($this->_lexer->isNextToken(Lexer::T_AND)) {
            $this->match(Lexer::T_AND);
romanb's avatar
romanb committed
1810
            $conditionalFactors[] = $this->ConditionalFactor();
1811
        }
guilhermeblanco's avatar
guilhermeblanco committed
1812

1813 1814 1815 1816 1817 1818
        // Phase 1 AST optimization: Prevent AST\ConditionalTerm
        // if only one AST\ConditionalFactor is defined
        if (count($conditionalFactors) == 1) {
            return $conditionalFactors[0];
        }

1819 1820 1821 1822 1823
        return new AST\ConditionalTerm($conditionalFactors);
    }

    /**
     * ConditionalFactor ::= ["NOT"] ConditionalPrimary
1824 1825
     *
     * @return \Doctrine\ORM\Query\AST\ConditionalFactor
1826
     */
romanb's avatar
romanb committed
1827
    public function ConditionalFactor()
1828 1829
    {
        $not = false;
guilhermeblanco's avatar
guilhermeblanco committed
1830

1831 1832 1833 1834
        if ($this->_lexer->isNextToken(Lexer::T_NOT)) {
            $this->match(Lexer::T_NOT);
            $not = true;
        }
1835 1836
        
        $conditionalPrimary = $this->ConditionalPrimary();
guilhermeblanco's avatar
guilhermeblanco committed
1837

1838 1839 1840 1841 1842 1843 1844 1845
        // Phase 1 AST optimization: Prevent AST\ConditionalFactor
        // if only one AST\ConditionalPrimary is defined
        if ( ! $not) {
            return $conditionalPrimary;
        }

        $conditionalFactor = new AST\ConditionalFactor($conditionalPrimary);
        $conditionalFactor->not = $not;
1846

1847
        return $conditionalFactor;
1848 1849 1850 1851
    }

    /**
     * ConditionalPrimary ::= SimpleConditionalExpression | "(" ConditionalExpression ")"
1852
     *
1853
     * @return Doctrine\ORM\Query\AST\ConditionalPrimary
1854
     */
romanb's avatar
romanb committed
1855
    public function ConditionalPrimary()
1856 1857
    {
        $condPrimary = new AST\ConditionalPrimary;
1858

1859
        if ($this->_lexer->isNextToken(Lexer::T_OPEN_PARENTHESIS)) {
1860
            // Peek beyond the matching closing paranthesis ')'
romanb's avatar
romanb committed
1861
            $peek = $this->_peekBeyondClosingParenthesis();
1862

1863 1864 1865 1866 1867 1868 1869
            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) {
1870
                $condPrimary->simpleConditionalExpression = $this->SimpleConditionalExpression();
1871
            } else {
1872
                $this->match(Lexer::T_OPEN_PARENTHESIS);
romanb's avatar
romanb committed
1873
                $condPrimary->conditionalExpression = $this->ConditionalExpression();
1874
                $this->match(Lexer::T_CLOSE_PARENTHESIS);
1875 1876
            }
        } else {
1877
            $condPrimary->simpleConditionalExpression = $this->SimpleConditionalExpression();
1878
        }
1879

1880 1881 1882 1883 1884 1885 1886 1887 1888
        return $condPrimary;
    }

    /**
     * SimpleConditionalExpression ::=
     *      ComparisonExpression | BetweenExpression | LikeExpression |
     *      InExpression | NullComparisonExpression | ExistsExpression |
     *      EmptyCollectionComparisonExpression | CollectionMemberExpression
     */
romanb's avatar
romanb committed
1889
    public function SimpleConditionalExpression()
1890 1891 1892 1893 1894 1895
    {
        if ($this->_lexer->isNextToken(Lexer::T_NOT)) {
            $token = $this->_lexer->glimpse();
        } else {
            $token = $this->_lexer->lookahead;
        }
guilhermeblanco's avatar
guilhermeblanco committed
1896

1897
        if ($token['type'] === Lexer::T_EXISTS) {
romanb's avatar
romanb committed
1898
            return $this->ExistsExpression();
1899 1900
        }

romanb's avatar
romanb committed
1901
        $peek = $this->_lexer->glimpse();
1902

romanb's avatar
romanb committed
1903
        if ($token['type'] === Lexer::T_IDENTIFIER || $token['type'] === Lexer::T_INPUT_PARAMETER) {
romanb's avatar
romanb committed
1904 1905
            if ($peek['value'] == '(') {
                // Peek beyond the matching closing paranthesis ')'
1906
                $this->_lexer->peek();
romanb's avatar
romanb committed
1907 1908 1909
                $token = $this->_peekBeyondClosingParenthesis();
            } else {
                // Peek beyond the PathExpression (or InputParameter)
1910 1911
                $peek = $this->_lexer->peek();

romanb's avatar
romanb committed
1912 1913 1914 1915
                while ($peek['value'] === '.') {
                    $this->_lexer->peek();
                    $peek = $this->_lexer->peek();
                }
guilhermeblanco's avatar
guilhermeblanco committed
1916

romanb's avatar
romanb committed
1917 1918 1919 1920
                // Also peek beyond a NOT if there is one
                if ($peek['type'] === Lexer::T_NOT) {
                    $peek = $this->_lexer->peek();
                }
guilhermeblanco's avatar
guilhermeblanco committed
1921

romanb's avatar
romanb committed
1922
                $token = $peek;
guilhermeblanco's avatar
guilhermeblanco committed
1923

romanb's avatar
romanb committed
1924 1925
                // We need to go even further in case of IS (differenciate between NULL and EMPTY)
                $lookahead = $this->_lexer->peek();
guilhermeblanco's avatar
guilhermeblanco committed
1926

romanb's avatar
romanb committed
1927 1928 1929 1930
                // Also peek beyond a NOT if there is one
                if ($lookahead['type'] === Lexer::T_NOT) {
                    $lookahead = $this->_lexer->peek();
                }
guilhermeblanco's avatar
guilhermeblanco committed
1931

romanb's avatar
romanb committed
1932 1933 1934
                $this->_lexer->resetPeek();
            }
        }
guilhermeblanco's avatar
guilhermeblanco committed
1935

romanb's avatar
romanb committed
1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953
        switch ($token['type']) {
            case Lexer::T_BETWEEN:
                return $this->BetweenExpression();
            case Lexer::T_LIKE:
                return $this->LikeExpression();
            case Lexer::T_IN:
                return $this->InExpression();
            case Lexer::T_IS:
                if ($lookahead['type'] == Lexer::T_NULL) {
                    return $this->NullComparisonExpression();
                }
                return $this->EmptyCollectionComparisonExpression();
            case Lexer::T_MEMBER:
                return $this->CollectionMemberExpression();
            default:
                return $this->ComparisonExpression();
        }
    }
1954

romanb's avatar
romanb committed
1955 1956 1957 1958 1959 1960 1961 1962 1963
    private function _peekBeyondClosingParenthesis()
    {
        $numUnmatched = 1;
        $token = $this->_lexer->peek();
        while ($numUnmatched > 0 && $token !== null) {
            if ($token['value'] == ')') {
                --$numUnmatched;
            } else if ($token['value'] == '(') {
                ++$numUnmatched;
1964
            }
romanb's avatar
romanb committed
1965
            $token = $this->_lexer->peek();
1966
        }
romanb's avatar
romanb committed
1967
        $this->_lexer->resetPeek();
1968

romanb's avatar
romanb committed
1969
        return $token;
1970
    }
1971

1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985
    /**
     * 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);
1986
            $emptyColletionCompExpr->not = true;
1987 1988 1989 1990 1991 1992
        }

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

        return $emptyColletionCompExpr;
    }
1993

1994
    /**
romanb's avatar
romanb committed
1995
     * CollectionMemberExpression ::= EntityExpression ["NOT"] "MEMBER" ["OF"] CollectionValuedPathExpression
1996
     *
romanb's avatar
romanb committed
1997 1998
     * EntityExpression ::= SingleValuedAssociationPathExpression | SimpleEntityExpression
     * SimpleEntityExpression ::= IdentificationVariable | InputParameter
1999
     *
2000
     * @return \Doctrine\ORM\Query\AST\CollectionMemberExpression
2001
     */
romanb's avatar
romanb committed
2002
    public function CollectionMemberExpression()
2003
    {
2004
        $not = false;
guilhermeblanco's avatar
guilhermeblanco committed
2005

2006
        $entityExpr = $this->EntityExpression();
guilhermeblanco's avatar
guilhermeblanco committed
2007

2008
        if ($this->_lexer->isNextToken(Lexer::T_NOT)) {
2009
            $not = true;
2010 2011
            $this->match(Lexer::T_NOT);
        }
guilhermeblanco's avatar
guilhermeblanco committed
2012

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

2015 2016
        if ($this->_lexer->isNextToken(Lexer::T_OF)) {
            $this->match(Lexer::T_OF);
romanb's avatar
romanb committed
2017
        }
2018

2019 2020
        $collMemberExpr = new AST\CollectionMemberExpression(
            $entityExpr, $this->CollectionValuedPathExpression()
2021
        );
2022
        $collMemberExpr->not = $not;
2023

2024
        return $collMemberExpr;
romanb's avatar
romanb committed
2025 2026 2027
    }

    /**
2028
     * Literal ::= string | char | integer | float | boolean
romanb's avatar
romanb committed
2029
     *
2030
     * @return string
romanb's avatar
romanb committed
2031
     */
2032
    public function Literal()
romanb's avatar
romanb committed
2033
    {
2034 2035
        switch ($this->_lexer->lookahead['type']) {
            case Lexer::T_STRING:
2036
                $this->match(Lexer::T_STRING);
romanb's avatar
romanb committed
2037
                return new AST\Literal(AST\Literal::STRING, $this->_lexer->token['value']);
2038

2039 2040
            case Lexer::T_INTEGER:
            case Lexer::T_FLOAT:
2041 2042 2043
                $this->match(
                    $this->_lexer->isNextToken(Lexer::T_INTEGER) ? Lexer::T_INTEGER : Lexer::T_FLOAT
                );
romanb's avatar
romanb committed
2044
                return new AST\Literal(AST\Literal::NUMERIC, $this->_lexer->token['value']);
2045

romanb's avatar
romanb committed
2046 2047
            case Lexer::T_TRUE:
            case Lexer::T_FALSE:
2048 2049 2050
                $this->match(
                    $this->_lexer->isNextToken(Lexer::T_TRUE) ? Lexer::T_TRUE : Lexer::T_FALSE
                );
romanb's avatar
romanb committed
2051
                return new AST\Literal(AST\Literal::BOOLEAN, $this->_lexer->token['value']);
2052

2053 2054
            default:
                $this->syntaxError('Literal');
2055 2056
        }
    }
2057

2058 2059 2060 2061 2062 2063 2064 2065 2066 2067
    /**
     * 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();
        }
2068

2069 2070
        return $this->Literal();
    }
2071

2072 2073 2074 2075 2076 2077 2078
    /**
     * InputParameter ::= PositionalParameter | NamedParameter
     *
     * @return \Doctrine\ORM\Query\AST\InputParameter
     */
    public function InputParameter()
    {
2079
        $this->match(Lexer::T_INPUT_PARAMETER);
2080

2081 2082
        return new AST\InputParameter($this->_lexer->token['value']);
    }
2083

2084 2085
    /**
     * ArithmeticExpression ::= SimpleArithmeticExpression | "(" Subselect ")"
2086 2087
     *
     * @return \Doctrine\ORM\Query\AST\ArithmeticExpression
2088
     */
romanb's avatar
romanb committed
2089
    public function ArithmeticExpression()
2090 2091
    {
        $expr = new AST\ArithmeticExpression;
guilhermeblanco's avatar
guilhermeblanco committed
2092

2093
        if ($this->_lexer->isNextToken(Lexer::T_OPEN_PARENTHESIS)) {
2094
            $peek = $this->_lexer->glimpse();
guilhermeblanco's avatar
guilhermeblanco committed
2095

2096
            if ($peek['type'] === Lexer::T_SELECT) {
2097
                $this->match(Lexer::T_OPEN_PARENTHESIS);
2098
                $expr->subselect = $this->Subselect();
2099
                $this->match(Lexer::T_CLOSE_PARENTHESIS);
guilhermeblanco's avatar
guilhermeblanco committed
2100

2101 2102 2103
                return $expr;
            }
        }
guilhermeblanco's avatar
guilhermeblanco committed
2104

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

2107 2108 2109 2110 2111
        return $expr;
    }

    /**
     * SimpleArithmeticExpression ::= ArithmeticTerm {("+" | "-") ArithmeticTerm}*
2112 2113
     *
     * @return \Doctrine\ORM\Query\AST\SimpleArithmeticExpression
2114
     */
romanb's avatar
romanb committed
2115
    public function SimpleArithmeticExpression()
2116 2117
    {
        $terms = array();
romanb's avatar
romanb committed
2118
        $terms[] = $this->ArithmeticTerm();
guilhermeblanco's avatar
guilhermeblanco committed
2119

2120 2121
        while (($isPlus = $this->_lexer->isNextToken(Lexer::T_PLUS)) || $this->_lexer->isNextToken(Lexer::T_MINUS)) {
            $this->match(($isPlus) ? Lexer::T_PLUS : Lexer::T_MINUS);
guilhermeblanco's avatar
guilhermeblanco committed
2122

2123
            $terms[] = $this->_lexer->token['value'];
romanb's avatar
romanb committed
2124
            $terms[] = $this->ArithmeticTerm();
2125
        }
2126

2127 2128 2129 2130 2131 2132
        // Phase 1 AST optimization: Prevent AST\SimpleArithmeticExpression
        // if only one AST\ArithmeticTerm is defined
        if (count($terms) == 1) {
            return $terms[0];
        }

2133 2134 2135 2136 2137
        return new AST\SimpleArithmeticExpression($terms);
    }

    /**
     * ArithmeticTerm ::= ArithmeticFactor {("*" | "/") ArithmeticFactor}*
2138 2139
     *
     * @return \Doctrine\ORM\Query\AST\ArithmeticTerm
2140
     */
romanb's avatar
romanb committed
2141
    public function ArithmeticTerm()
2142 2143
    {
        $factors = array();
romanb's avatar
romanb committed
2144
        $factors[] = $this->ArithmeticFactor();
guilhermeblanco's avatar
guilhermeblanco committed
2145

2146 2147
        while (($isMult = $this->_lexer->isNextToken(Lexer::T_MULTIPLY)) || $this->_lexer->isNextToken(Lexer::T_DIVIDE)) {
            $this->match(($isMult) ? Lexer::T_MULTIPLY : Lexer::T_DIVIDE);
2148

2149
            $factors[] = $this->_lexer->token['value'];
romanb's avatar
romanb committed
2150
            $factors[] = $this->ArithmeticFactor();
2151
        }
guilhermeblanco's avatar
guilhermeblanco committed
2152

2153 2154 2155 2156 2157 2158
        // Phase 1 AST optimization: Prevent AST\ArithmeticTerm
        // if only one AST\ArithmeticFactor is defined
        if (count($factors) == 1) {
            return $factors[0];
        }

2159 2160 2161 2162 2163
        return new AST\ArithmeticTerm($factors);
    }

    /**
     * ArithmeticFactor ::= [("+" | "-")] ArithmeticPrimary
2164 2165
     *
     * @return \Doctrine\ORM\Query\AST\ArithmeticFactor
2166
     */
romanb's avatar
romanb committed
2167
    public function ArithmeticFactor()
2168
    {
2169
        $sign = null;
guilhermeblanco's avatar
guilhermeblanco committed
2170

2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182
        if (($isPlus = $this->_lexer->isNextToken(Lexer::T_PLUS)) || $this->_lexer->isNextToken(Lexer::T_MINUS)) {
            $this->match(($isPlus) ? Lexer::T_PLUS : Lexer::T_MINUS);
            $sign = $isPlus;
        }
        
        $primary = $this->ArithmeticPrimary();

        // Phase 1 AST optimization: Prevent AST\ArithmeticFactor
        // if only one AST\ArithmeticPrimary is defined
        if ($sign === null) {
            return $primary;
        }
2183

2184
        return new AST\ArithmeticFactor($primary, $sign);
2185 2186 2187
    }

    /**
2188 2189
     * ArithmeticPrimary ::= SingleValuedPathExpression | Literal | "(" SimpleArithmeticExpression ")"
     *          | FunctionsReturningNumerics | AggregateExpression | FunctionsReturningStrings
2190
     *          | FunctionsReturningDatetime | IdentificationVariable
2191
     */
2192
    public function ArithmeticPrimary()
2193
    {
2194 2195
        if ($this->_lexer->isNextToken(Lexer::T_OPEN_PARENTHESIS)) {
            $this->match(Lexer::T_OPEN_PARENTHESIS);
2196
            $expr = $this->SimpleArithmeticExpression();
2197

2198
            $this->match(Lexer::T_CLOSE_PARENTHESIS);
guilhermeblanco's avatar
guilhermeblanco committed
2199

2200
            return $expr;
2201
        }
guilhermeblanco's avatar
guilhermeblanco committed
2202

2203 2204 2205
        switch ($this->_lexer->lookahead['type']) {
            case Lexer::T_IDENTIFIER:
                $peek = $this->_lexer->glimpse();
2206

2207 2208 2209
                if ($peek['value'] == '(') {
                    return $this->FunctionDeclaration();
                }
2210

2211 2212 2213
                if ($peek['value'] == '.') {
                    return $this->SingleValuedPathExpression();
                }
guilhermeblanco's avatar
guilhermeblanco committed
2214

2215
                return $this->SimpleStateFieldPathExpression();
guilhermeblanco's avatar
guilhermeblanco committed
2216

2217
            case Lexer::T_INPUT_PARAMETER:
2218
                return $this->InputParameter();
2219

2220 2221
            default:
                $peek = $this->_lexer->glimpse();
guilhermeblanco's avatar
guilhermeblanco committed
2222

2223 2224 2225 2226
                if ($peek['value'] == '(') {
                    if ($this->_isAggregateFunction($this->_lexer->lookahead['type'])) {
                        return $this->AggregateExpression();
                    }
romanb's avatar
romanb committed
2227

2228
                    return $this->FunctionDeclaration();
romanb's avatar
romanb committed
2229 2230
                } else {
                    return $this->Literal();
2231 2232
                }
        }
2233
    }
2234

2235
    /**
2236
     * StringExpression ::= StringPrimary | "(" Subselect ")"
2237 2238 2239
     *
     * @return \Doctrine\ORM\Query\AST\StringPrimary |
     *         \Doctrine]ORM\Query\AST\Subselect
2240
     */
2241
    public function StringExpression()
2242
    {
2243
        if ($this->_lexer->isNextToken(Lexer::T_OPEN_PARENTHESIS)) {
2244
            $peek = $this->_lexer->glimpse();
2245

2246
            if ($peek['type'] === Lexer::T_SELECT) {
2247
                $this->match(Lexer::T_OPEN_PARENTHESIS);
2248
                $expr = $this->Subselect();
2249
                $this->match(Lexer::T_CLOSE_PARENTHESIS);
2250

2251 2252 2253
                return $expr;
            }
        }
2254

2255
        return $this->StringPrimary();
2256 2257 2258
    }

    /**
2259
     * StringPrimary ::= StateFieldPathExpression | string | InputParameter | FunctionsReturningStrings | AggregateExpression
2260
     */
2261
    public function StringPrimary()
2262
    {
2263
        if ($this->_lexer->isNextToken(Lexer::T_IDENTIFIER)) {
2264
            $peek = $this->_lexer->glimpse();
guilhermeblanco's avatar
guilhermeblanco committed
2265

2266 2267 2268 2269 2270 2271 2272
            if ($peek['value'] == '.') {
                return $this->StateFieldPathExpression();
            } else if ($peek['value'] == '(') {
                return $this->FunctionsReturningStrings();
            } else {
                $this->syntaxError("'.' or '('");
            }
2273
        } else if ($this->_lexer->isNextToken(Lexer::T_STRING)) {
2274
            $this->match(Lexer::T_STRING);
guilhermeblanco's avatar
guilhermeblanco committed
2275

2276
            return $this->_lexer->token['value'];
2277
        } else if ($this->_lexer->isNextToken(Lexer::T_INPUT_PARAMETER)) {
2278
            return $this->InputParameter();
2279 2280 2281 2282 2283
        } else if ($this->_isAggregateFunction($this->_lexer->lookahead['type'])) {
            return $this->AggregateExpression();
        }

        $this->syntaxError('StateFieldPathExpression | string | InputParameter | FunctionsReturningStrings | AggregateExpression');
2284 2285 2286
    }

    /**
2287
     * EntityExpression ::= SingleValuedAssociationPathExpression | SimpleEntityExpression
2288 2289 2290
     *
     * @return \Doctrine\ORM\Query\AST\SingleValuedAssociationPathExpression |
     *         \Doctrine\ORM\Query\AST\SimpleEntityExpression
2291
     */
2292
    public function EntityExpression()
2293
    {
2294
        $glimpse = $this->_lexer->glimpse();
2295

2296 2297
        if ($this->_lexer->isNextToken(Lexer::T_IDENTIFIER) && $glimpse['value'] === '.') {
            return $this->SingleValuedAssociationPathExpression();
2298
        }
2299

2300
        return $this->SimpleEntityExpression();
2301
    }
2302

2303
    /**
2304
     * SimpleEntityExpression ::= IdentificationVariable | InputParameter
2305 2306
     *
     * @return string | \Doctrine\ORM\Query\AST\InputParameter
2307
     */
2308
    public function SimpleEntityExpression()
2309
    {
2310
        if ($this->_lexer->isNextToken(Lexer::T_INPUT_PARAMETER)) {
2311
            return $this->InputParameter();
2312
        }
2313

2314
        return $this->IdentificationVariable();
2315 2316 2317
    }

    /**
2318 2319 2320
     * AggregateExpression ::=
     *  ("AVG" | "MAX" | "MIN" | "SUM") "(" ["DISTINCT"] StateFieldPathExpression ")" |
     *  "COUNT" "(" ["DISTINCT"] (IdentificationVariable | SingleValuedPathExpression) ")"
2321 2322
     *
     * @return \Doctrine\ORM\Query\AST\AggregateExpression
2323
     */
2324
    public function AggregateExpression()
2325
    {
2326 2327
        $isDistinct = false;
        $functionName = '';
guilhermeblanco's avatar
guilhermeblanco committed
2328

2329 2330 2331
        if ($this->_lexer->isNextToken(Lexer::T_COUNT)) {
            $this->match(Lexer::T_COUNT);
            $functionName = $this->_lexer->token['value'];
2332
            $this->match(Lexer::T_OPEN_PARENTHESIS);
guilhermeblanco's avatar
guilhermeblanco committed
2333

2334 2335 2336
            if ($this->_lexer->isNextToken(Lexer::T_DISTINCT)) {
                $this->match(Lexer::T_DISTINCT);
                $isDistinct = true;
2337
            }
guilhermeblanco's avatar
guilhermeblanco committed
2338

2339
            $pathExp = $this->SingleValuedPathExpression();
2340
            $this->match(Lexer::T_CLOSE_PARENTHESIS);
2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351
        } 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');
2352
            }
guilhermeblanco's avatar
guilhermeblanco committed
2353

2354
            $functionName = $this->_lexer->token['value'];
2355
            $this->match(Lexer::T_OPEN_PARENTHESIS);
2356
            $pathExp = $this->StateFieldPathExpression();
2357
            $this->match(Lexer::T_CLOSE_PARENTHESIS);
2358
        }
2359 2360

        return new AST\AggregateExpression($functionName, $pathExp, $isDistinct);
2361 2362 2363
    }

    /**
2364
     * QuantifiedExpression ::= ("ALL" | "ANY" | "SOME") "(" Subselect ")"
2365 2366
     *
     * @return \Doctrine\ORM\Query\AST\QuantifiedExpression
2367
     */
2368
    public function QuantifiedExpression()
2369
    {
2370
        $type = '';
guilhermeblanco's avatar
guilhermeblanco committed
2371

2372 2373
        if ($this->_lexer->isNextToken(Lexer::T_ALL)) {
            $this->match(Lexer::T_ALL);
2374
            $type = 'ALL';
2375 2376
        } else if ($this->_lexer->isNextToken(Lexer::T_ANY)) {
            $this->match(Lexer::T_ANY);
2377
             $type = 'ANY';
2378 2379
        } else if ($this->_lexer->isNextToken(Lexer::T_SOME)) {
            $this->match(Lexer::T_SOME);
2380
             $type = 'SOME';
2381 2382 2383
        } else {
            $this->syntaxError('ALL, ANY or SOME');
        }
guilhermeblanco's avatar
guilhermeblanco committed
2384

2385
        $this->match(Lexer::T_OPEN_PARENTHESIS);
2386
        $qExpr = new AST\QuantifiedExpression($this->Subselect());
2387
        $qExpr->type = $type;
2388
        $this->match(Lexer::T_CLOSE_PARENTHESIS);
guilhermeblanco's avatar
guilhermeblanco committed
2389

2390
        return $qExpr;
2391 2392 2393 2394
    }

    /**
     * BetweenExpression ::= ArithmeticExpression ["NOT"] "BETWEEN" ArithmeticExpression "AND" ArithmeticExpression
2395 2396
     *
     * @return \Doctrine\ORM\Query\AST\BetweenExpression
2397
     */
romanb's avatar
romanb committed
2398
    public function BetweenExpression()
2399 2400
    {
        $not = false;
romanb's avatar
romanb committed
2401
        $arithExpr1 = $this->ArithmeticExpression();
guilhermeblanco's avatar
guilhermeblanco committed
2402

2403 2404 2405 2406
        if ($this->_lexer->isNextToken(Lexer::T_NOT)) {
            $this->match(Lexer::T_NOT);
            $not = true;
        }
guilhermeblanco's avatar
guilhermeblanco committed
2407

2408
        $this->match(Lexer::T_BETWEEN);
romanb's avatar
romanb committed
2409
        $arithExpr2 = $this->ArithmeticExpression();
2410
        $this->match(Lexer::T_AND);
romanb's avatar
romanb committed
2411
        $arithExpr3 = $this->ArithmeticExpression();
2412 2413

        $betweenExpr = new AST\BetweenExpression($arithExpr1, $arithExpr2, $arithExpr3);
2414
        $betweenExpr->not = $not;
2415 2416 2417 2418 2419

        return $betweenExpr;
    }

    /**
2420 2421
     * ComparisonExpression ::= ArithmeticExpression ComparisonOperator ( QuantifiedExpression | ArithmeticExpression )
     *
2422
     * @return \Doctrine\ORM\Query\AST\ComparisonExpression
2423
     */
2424
    public function ComparisonExpression()
2425
    {
2426
        $peek = $this->_lexer->glimpse();
guilhermeblanco's avatar
guilhermeblanco committed
2427

2428 2429 2430 2431 2432 2433 2434
        $leftExpr = $this->ArithmeticExpression();
        $operator = $this->ComparisonOperator();

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

2437 2438
        return new AST\ComparisonExpression($leftExpr, $operator, $rightExpr);
    }
guilhermeblanco's avatar
guilhermeblanco committed
2439

2440
    /**
2441
     * InExpression ::= StateFieldPathExpression ["NOT"] "IN" "(" (InParameter {"," InParameter}* | Subselect) ")"
2442 2443
     *
     * @return \Doctrine\ORM\Query\AST\InExpression
2444 2445 2446 2447 2448 2449 2450
     */
    public function InExpression()
    {
        $inExpression = new AST\InExpression($this->StateFieldPathExpression());

        if ($this->_lexer->isNextToken(Lexer::T_NOT)) {
            $this->match(Lexer::T_NOT);
2451
            $inExpression->not = true;
2452 2453 2454
        }

        $this->match(Lexer::T_IN);
2455
        $this->match(Lexer::T_OPEN_PARENTHESIS);
2456 2457

        if ($this->_lexer->isNextToken(Lexer::T_SELECT)) {
2458
            $inExpression->subselect = $this->Subselect();
2459 2460
        } else {
            $literals = array();
2461
            $literals[] = $this->InParameter();
2462

2463 2464
            while ($this->_lexer->isNextToken(Lexer::T_COMMA)) {
                $this->match(Lexer::T_COMMA);
2465
                $literals[] = $this->InParameter();
2466
            }
guilhermeblanco's avatar
guilhermeblanco committed
2467

2468
            $inExpression->literals = $literals;
2469
        }
guilhermeblanco's avatar
guilhermeblanco committed
2470

2471
        $this->match(Lexer::T_CLOSE_PARENTHESIS);
guilhermeblanco's avatar
guilhermeblanco committed
2472

2473 2474
        return $inExpression;
    }
guilhermeblanco's avatar
guilhermeblanco committed
2475

2476 2477
    /**
     * LikeExpression ::= StringExpression ["NOT"] "LIKE" (string | input_parameter) ["ESCAPE" char]
2478 2479
     *
     * @return \Doctrine\ORM\Query\AST\LikeExpression
2480 2481 2482 2483
     */
    public function LikeExpression()
    {
        $stringExpr = $this->StringExpression();
2484
        $not = false;
guilhermeblanco's avatar
guilhermeblanco committed
2485

2486
        if ($this->_lexer->isNextToken(Lexer::T_NOT)) {
2487
            $this->match(Lexer::T_NOT);
2488
            $not = true;
2489
        }
guilhermeblanco's avatar
guilhermeblanco committed
2490

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

2493 2494 2495 2496 2497 2498 2499
        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
2500

2501
        $escapeChar = null;
guilhermeblanco's avatar
guilhermeblanco committed
2502

2503 2504 2505 2506
        if ($this->_lexer->lookahead['type'] === Lexer::T_ESCAPE) {
            $this->match(Lexer::T_ESCAPE);
            $this->match(Lexer::T_STRING);
            $escapeChar = $this->_lexer->token['value'];
2507
        }
2508

2509 2510
        $likeExpr = new AST\LikeExpression($stringExpr, $stringPattern, $escapeChar);
        $likeExpr->not = $not;
2511

2512
        return $likeExpr;
2513 2514 2515
    }

    /**
2516
     * NullComparisonExpression ::= (SingleValuedPathExpression | InputParameter) "IS" ["NOT"] "NULL"
2517 2518
     *
     * @return \Doctrine\ORM\Query\AST\NullComparisonExpression
2519
     */
2520
    public function NullComparisonExpression()
2521
    {
2522 2523 2524 2525 2526 2527
        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
2528

2529 2530
        $nullCompExpr = new AST\NullComparisonExpression($expr);
        $this->match(Lexer::T_IS);
2531

2532 2533
        if ($this->_lexer->isNextToken(Lexer::T_NOT)) {
            $this->match(Lexer::T_NOT);
2534
            $nullCompExpr->not = true;
2535
        }
guilhermeblanco's avatar
guilhermeblanco committed
2536

2537 2538 2539
        $this->match(Lexer::T_NULL);

        return $nullCompExpr;
2540 2541 2542
    }

    /**
2543
     * ExistsExpression ::= ["NOT"] "EXISTS" "(" Subselect ")"
2544 2545
     *
     * @return \Doctrine\ORM\Query\AST\ExistsExpression
2546
     */
2547
    public function ExistsExpression()
2548
    {
2549
        $not = false;
guilhermeblanco's avatar
guilhermeblanco committed
2550

2551 2552 2553 2554 2555 2556
        if ($this->_lexer->isNextToken(Lexer::T_NOT)) {
            $this->match(Lexer::T_NOT);
            $not = true;
        }

        $this->match(Lexer::T_EXISTS);
2557
        $this->match(Lexer::T_OPEN_PARENTHESIS);
2558
        $existsExpression = new AST\ExistsExpression($this->Subselect());
2559
        $existsExpression->not = $not;
2560
        $this->match(Lexer::T_CLOSE_PARENTHESIS);
2561 2562

        return $existsExpression;
2563 2564 2565 2566
    }

    /**
     * ComparisonOperator ::= "=" | "<" | "<=" | "<>" | ">" | ">=" | "!="
2567 2568
     *
     * @return string
2569
     */
romanb's avatar
romanb committed
2570
    public function ComparisonOperator()
2571 2572 2573
    {
        switch ($this->_lexer->lookahead['value']) {
            case '=':
2574
                $this->match(Lexer::T_EQUALS);
guilhermeblanco's avatar
guilhermeblanco committed
2575

2576
                return '=';
guilhermeblanco's avatar
guilhermeblanco committed
2577

2578
            case '<':
2579
                $this->match(Lexer::T_LOWER_THAN);
2580
                $operator = '<';
guilhermeblanco's avatar
guilhermeblanco committed
2581

2582 2583
                if ($this->_lexer->isNextToken(Lexer::T_EQUALS)) {
                    $this->match(Lexer::T_EQUALS);
2584
                    $operator .= '=';
2585 2586
                } else if ($this->_lexer->isNextToken(Lexer::T_GREATER_THAN)) {
                    $this->match(Lexer::T_GREATER_THAN);
2587 2588
                    $operator .= '>';
                }
guilhermeblanco's avatar
guilhermeblanco committed
2589

2590
                return $operator;
guilhermeblanco's avatar
guilhermeblanco committed
2591

2592
            case '>':
2593
                $this->match(Lexer::T_GREATER_THAN);
2594
                $operator = '>';
guilhermeblanco's avatar
guilhermeblanco committed
2595

2596 2597
                if ($this->_lexer->isNextToken(Lexer::T_EQUALS)) {
                    $this->match(Lexer::T_EQUALS);
2598 2599
                    $operator .= '=';
                }
guilhermeblanco's avatar
guilhermeblanco committed
2600

2601
                return $operator;
guilhermeblanco's avatar
guilhermeblanco committed
2602

2603
            case '!':
2604 2605
                $this->match(Lexer::T_NEGATE);
                $this->match(Lexer::T_EQUALS);
guilhermeblanco's avatar
guilhermeblanco committed
2606

2607
                return '<>';
guilhermeblanco's avatar
guilhermeblanco committed
2608

2609 2610 2611 2612 2613 2614
            default:
                $this->syntaxError('=, <, <=, <>, >, >=, !=');
        }
    }

    /**
2615
     * FunctionDeclaration ::= FunctionsReturningStrings | FunctionsReturningNumerics | FunctionsReturningDatetime
2616
     */
2617
    public function FunctionDeclaration()
2618
    {
2619 2620
        $token = $this->_lexer->lookahead;
        $funcName = strtolower($token['value']);
guilhermeblanco's avatar
guilhermeblanco committed
2621

2622 2623 2624 2625 2626 2627 2628 2629
        // Check for built-in functions first!
        if (isset(self::$_STRING_FUNCTIONS[$funcName])) {
            return $this->FunctionsReturningStrings();
        } else if (isset(self::$_NUMERIC_FUNCTIONS[$funcName])) {
            return $this->FunctionsReturningNumerics();
        } else if (isset(self::$_DATETIME_FUNCTIONS[$funcName])) {
            return $this->FunctionsReturningDatetime();
        }
2630

2631 2632
        // Check for custom functions afterwards
        $config = $this->_em->getConfiguration();
2633

2634 2635 2636 2637 2638 2639
        if ($config->getCustomStringFunction($funcName) !== null) {
            return $this->CustomFunctionsReturningStrings();
        } else if ($config->getCustomNumericFunction($funcName) !== null) {
            return $this->CustomFunctionsReturningNumerics();
        } else if ($config->getCustomDatetimeFunction($funcName) !== null) {
            return $this->CustomFunctionsReturningDatetime();
2640
        }
2641

2642
        $this->syntaxError('known function', $token);
2643 2644 2645
    }

    /**
2646 2647 2648 2649 2650 2651 2652
     * FunctionsReturningNumerics ::=
     *      "LENGTH" "(" StringPrimary ")" |
     *      "LOCATE" "(" StringPrimary "," StringPrimary ["," SimpleArithmeticExpression]")" |
     *      "ABS" "(" SimpleArithmeticExpression ")" |
     *      "SQRT" "(" SimpleArithmeticExpression ")" |
     *      "MOD" "(" SimpleArithmeticExpression "," SimpleArithmeticExpression ")" |
     *      "SIZE" "(" CollectionValuedPathExpression ")"
2653
     */
2654
    public function FunctionsReturningNumerics()
2655
    {
2656 2657 2658 2659
        $funcNameLower = strtolower($this->_lexer->lookahead['value']);
        $funcClass = self::$_NUMERIC_FUNCTIONS[$funcNameLower];
        $function = new $funcClass($funcNameLower);
        $function->parse($this);
guilhermeblanco's avatar
guilhermeblanco committed
2660

2661
        return $function;
2662 2663
    }

2664 2665
    public function CustomFunctionsReturningNumerics()
    {
2666 2667 2668 2669
        $funcName = strtolower($this->_lexer->lookahead['value']);
        // getCustomNumericFunction is case-insensitive
        $funcClass = $this->_em->getConfiguration()->getCustomNumericFunction($funcName);
        $function = new $funcClass($funcName);
2670 2671 2672 2673 2674
        $function->parse($this);

        return $function;
    }

2675
    /**
2676
     * FunctionsReturningDateTime ::= "CURRENT_DATE" | "CURRENT_TIME" | "CURRENT_TIMESTAMP"
2677
     */
2678
    public function FunctionsReturningDatetime()
2679
    {
2680 2681 2682 2683
        $funcNameLower = strtolower($this->_lexer->lookahead['value']);
        $funcClass = self::$_DATETIME_FUNCTIONS[$funcNameLower];
        $function = new $funcClass($funcNameLower);
        $function->parse($this);
2684

2685
        return $function;
2686
    }
2687

2688 2689
    public function CustomFunctionsReturningDatetime()
    {
2690 2691 2692 2693
        $funcName = $this->_lexer->lookahead['value'];
        // getCustomDatetimeFunction is case-insensitive
        $funcClass = $this->_em->getConfiguration()->getCustomDatetimeFunction($funcName);
        $function = new $funcClass($funcName);
2694 2695 2696 2697 2698
        $function->parse($this);

        return $function;
    }

2699
    /**
2700 2701 2702 2703 2704 2705
     * FunctionsReturningStrings ::=
     *   "CONCAT" "(" StringPrimary "," StringPrimary ")" |
     *   "SUBSTRING" "(" StringPrimary "," SimpleArithmeticExpression "," SimpleArithmeticExpression ")" |
     *   "TRIM" "(" [["LEADING" | "TRAILING" | "BOTH"] [char] "FROM"] StringPrimary ")" |
     *   "LOWER" "(" StringPrimary ")" |
     *   "UPPER" "(" StringPrimary ")"
2706
     */
2707
    public function FunctionsReturningStrings()
2708
    {
2709 2710
        $funcNameLower = strtolower($this->_lexer->lookahead['value']);
        $funcClass = self::$_STRING_FUNCTIONS[$funcNameLower];
2711 2712 2713 2714 2715 2716 2717 2718
        $function = new $funcClass($funcNameLower);
        $function->parse($this);

        return $function;
    }

    public function CustomFunctionsReturningStrings()
    {
2719 2720 2721 2722
        $funcName = $this->_lexer->lookahead['value'];
        // getCustomStringFunction is case-insensitive
        $funcClass = $this->_em->getConfiguration()->getCustomStringFunction($funcName);
        $function = new $funcClass($funcName);
2723
        $function->parse($this);
2724

2725
        return $function;
2726
    }
2727
}