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

22 23
namespace Doctrine\ORM\Query;

24
use Doctrine\Common\DoctrineException;
25
use Doctrine\ORM\Query;
26 27 28
use Doctrine\ORM\Query\AST;
use Doctrine\ORM\Query\Exec;

29
/**
romanb's avatar
romanb committed
30
 * An LL(*) parser for the context-free grammar of the Doctrine Query Language.
31
 * Parses a DQL query, reports any errors in it, and generates an AST.
32 33 34
 *
 * @author      Guilherme Blanco <guilhermeblanco@hotmail.com>
 * @author      Janne Vanhala <jpvanhal@cc.hut.fi>
35
 * @author      Roman Borschel <roman@code-factory.org>
36
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
37
 * @link        http://www.doctrine-project.org
38 39 40
 * @since       2.0
 * @version     $Revision$
 */
41
class Parser
42
{
romanb's avatar
romanb committed
43 44
    const SCALAR_QUERYCOMPONENT_ALIAS = 'dctrn';

45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
    /** Maps registered string function names to class names. */
    private static $_STRING_FUNCTIONS = array(
        'concat' => 'Doctrine\ORM\Query\AST\Functions\ConcatFunction',
        'substring' => 'Doctrine\ORM\Query\AST\Functions\SubstringFunction',
        'trim' => 'Doctrine\ORM\Query\AST\Functions\TrimFunction',
        'lower' => 'Doctrine\ORM\Query\AST\Functions\LowerFunction',
        'upper' => 'Doctrine\ORM\Query\AST\Functions\UpperFunction'
    );

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

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

71 72 73 74 75 76
    /**
     * The minimum number of tokens read after last detected error before
     * another error can be reported.
     *
     * @var int
     */
77
    //const MIN_ERROR_DISTANCE = 2;
78 79

    /**
80 81
     * Path expressions that were encountered during parsing of SelectExpressions
     * and still need to be validated.
82
     *
83
     * @var array
84
     */
85
    private $_deferredPathExpressionStacks = array();
86 87 88 89 90 91

    /**
     * A scanner object.
     *
     * @var Doctrine_ORM_Query_Scanner
     */
92
    private $_lexer;
93 94 95 96 97 98

    /**
     * The Parser Result object.
     *
     * @var Doctrine_ORM_Query_ParserResult
     */
99
    private $_parserResult;
100 101 102 103 104 105
    
    /**
     * The EntityManager.
     *
     * @var EnityManager
     */
106
    private $_em;
107

108 109 110 111 112 113 114
    /**
     * The Query to parse.
     *
     * @var Query
     */
    private $_query;

115 116 117 118 119 120 121
    /**
     * Map of declared classes in the parsed query.
     * Maps the declared DQL alias (key) to the class name (value).
     *
     * @var array
     */
    private $_queryComponents = array();
122

123 124 125
    /**
     * Creates a new query parser object.
     *
126
     * @param Query $query The Query to parse.
127
     */
128
    public function __construct(Query $query)
129
    {
130
        $this->_query = $query;
131
        $this->_em = $query->getEntityManager();
132
        $this->_lexer = new Lexer($query->getDql());
133
        $this->_parserResult = new ParserResult;
134
        $this->_parserResult->setEntityManager($this->_em);
135
        //$this->free(true);
136 137 138 139 140 141 142 143 144 145 146 147 148 149
    }

    /**
     * Attempts to match the given token with the current lookahead token.
     *
     * If they match, updates the lookahead token; otherwise raises a syntax
     * error.
     *
     * @param int|string token type or value
     * @return bool True, if tokens match; false otherwise.
     */
    public function match($token)
    {
        if (is_string($token)) {
150
            $isMatch = ($this->_lexer->lookahead['value'] === $token);
151
        } else {
152
            $isMatch = ($this->_lexer->lookahead['type'] === $token);
153 154 155
        }

        if ( ! $isMatch) {
romanb's avatar
romanb committed
156
            $this->syntaxError($this->_lexer->getLiteral($token));
157 158
        }

159
        $this->_lexer->moveNext();
160 161 162 163 164 165 166 167 168 169 170
    }

    /**
     * Free this parser enabling it to be reused 
     * 
     * @param boolean $deep     Whether to clean peek and reset errors 
     * @param integer $position Position to reset 
     */
    public function free($deep = false, $position = 0)
    {
        // WARNING! Use this method with care. It resets the scanner!
171
        $this->_lexer->resetPosition($position);
172 173 174

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

179 180 181
        $this->_lexer->token = null;
        $this->_lexer->lookahead = null;
        //$this->_errorDistance = self::MIN_ERROR_DISTANCE;
182 183 184 185 186 187 188
    }

    /**
     * Parses a query string.
     */
    public function parse()
    {
189 190
        // Parse & build AST
        $AST = $this->_QueryLanguage();
191
        
192
        // Check for end of string
193
        if ($this->_lexer->lookahead !== null) {
romanb's avatar
romanb committed
194
            //var_dump($this->_lexer->lookahead);
195 196 197
            $this->syntaxError('end of string');
        }

198
        // Create SqlWalker who creates the SQL from the AST
199
        $sqlWalker = new SqlWalker($this->_query, $this->_parserResult, $this->_queryComponents);
200

romanb's avatar
romanb committed
201
        // Assign an SQL executor to the parser result
202
        $this->_parserResult->setSqlExecutor(Exec\AbstractExecutor::create($AST, $sqlWalker));
203 204 205 206 207

        return $this->_parserResult;
    }

    /**
208
     * Gets the lexer used by the parser.
209
     *
210
     * @return Doctrine\ORM\Query\Lexer
211
     */
212
    public function getLexer()
213
    {
214
        return $this->_lexer;
215 216 217
    }

    /**
218
     * Gets the ParserResult that is being filled with information during parsing.
219
     *
220
     * @return Doctrine\ORM\Query\ParserResult
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
     */
    public function getParserResult()
    {
        return $this->_parserResult;
    }

    /**
     * Generates a new syntax error.
     *
     * @param string $expected Optional expected string.
     * @param array $token Optional token.
     */
    public function syntaxError($expected = '', $token = null)
    {
        if ($token === null) {
236
            $token = $this->_lexer->lookahead;
237 238 239 240 241 242 243 244 245 246
        }

        $message = 'line 0, col ' . (isset($token['position']) ? $token['position'] : '-1') . ': Error: ';

        if ($expected !== '') {
            $message .= "Expected '$expected', got ";
        } else {
            $message .= 'Unexpected ';
        }

247
        if ($this->_lexer->lookahead === null) {
248 249
            $message .= 'end of string.';
        } else {
250
            $message .= "'{$this->_lexer->lookahead['value']}'";
251 252
        }

253
        throw DoctrineException::updateMe($message);
254 255 256 257 258 259 260 261 262 263 264
    }

    /**
     * Generates a new semantical error.
     *
     * @param string $message Optional message.
     * @param array $token Optional token.
     */
    public function semanticalError($message = '', $token = null)
    {
        if ($token === null) {
265
            $token = $this->_lexer->token;
266
        }
267
        //TODO: Include $token in $message
268
        throw DoctrineException::updateMe($message);
269 270 271 272 273 274 275 276
    }

    /**
     * Logs new error entry.
     *
     * @param string $message Message to log.
     * @param array $token Token that it was processing.
     */
277
    /*protected function _logError($message = '', $token)
278 279 280 281 282 283 284
    {
        if ($this->_errorDistance >= self::MIN_ERROR_DISTANCE) {
            $message = 'line 0, col ' . $token['position'] . ': ' . $message;
            $this->_errors[] = $message;
        }

        $this->_errorDistance = 0;
285
    }*/
286 287 288 289 290 291 292 293 294
    
    /**
     * Gets the EntityManager used by the parser.
     *
     * @return EntityManager
     */
    public function getEntityManager()
    {
        return $this->_em;
romanb's avatar
romanb committed
295
    }
296 297

    /**
romanb's avatar
romanb committed
298
     * Checks if the next-next (after lookahead) token starts a function.
299 300 301 302 303
     *
     * @return boolean
     */
    private function _isFunction()
    {
304
        $next = $this->_lexer->glimpse();
romanb's avatar
romanb committed
305
        return $next['value'] === '(';
306 307 308 309 310 311 312 313 314
    }

    /**
     * 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()
    {
315 316
        $la = $this->_lexer->lookahead;
        $next = $this->_lexer->glimpse();
romanb's avatar
romanb committed
317
        return ($la['value'] === '(' && $next['type'] === Lexer::T_SELECT);
318 319 320 321 322
    }

    /**
     * QueryLanguage ::= SelectStatement | UpdateStatement | DeleteStatement
     */
323
    public function _QueryLanguage()
324
    {
325
        $this->_lexer->moveNext();
326
        switch ($this->_lexer->lookahead['type']) {
romanb's avatar
romanb committed
327
            case Lexer::T_SELECT:
328
                return $this->_SelectStatement();
romanb's avatar
romanb committed
329
            case Lexer::T_UPDATE:
330
                return $this->_UpdateStatement();
romanb's avatar
romanb committed
331
            case Lexer::T_DELETE:
332 333 334 335 336 337 338 339 340 341
                return $this->_DeleteStatement();
            default:
                $this->syntaxError('SELECT, UPDATE or DELETE');
                break;
        }
    }

    /**
     * SelectStatement ::= SelectClause FromClause [WhereClause] [GroupByClause] [HavingClause] [OrderByClause]
     */
romanb's avatar
romanb committed
342
    public function _SelectStatement()
343
    {
344
        $this->_beginDeferredPathExpressionStack();
345 346
        $selectClause = $this->_SelectClause();
        $fromClause = $this->_FromClause();
347
        $this->_processDeferredPathExpressionStack();
348

romanb's avatar
romanb committed
349
        $whereClause = $this->_lexer->isNextToken(Lexer::T_WHERE) ?
350 351
                $this->_WhereClause() : null;

romanb's avatar
romanb committed
352
        $groupByClause = $this->_lexer->isNextToken(Lexer::T_GROUP) ?
353 354
                $this->_GroupByClause() : null;

romanb's avatar
romanb committed
355
        $havingClause = $this->_lexer->isNextToken(Lexer::T_HAVING) ?
356 357
                $this->_HavingClause() : null;

romanb's avatar
romanb committed
358
        $orderByClause = $this->_lexer->isNextToken(Lexer::T_ORDER) ?
359 360
                $this->_OrderByClause() : null;

361
        return new AST\SelectStatement(
362 363 364 365
            $selectClause, $fromClause, $whereClause, $groupByClause, $havingClause, $orderByClause
        );
    }

366
    /**
romanb's avatar
romanb committed
367
     * Begins a new stack of deferred path expressions.
368 369 370 371 372 373
     */
    private function _beginDeferredPathExpressionStack()
    {
        $this->_deferredPathExpressionStacks[] = array();
    }

374
    /**
romanb's avatar
romanb committed
375 376
     * Processes the topmost stack of deferred path expressions.
     * These will be validated to make sure they are indeed
377 378 379
     * valid <tt>StateFieldPathExpression</tt>s and additional information
     * is attached to their AST nodes.
     */
380
    private function _processDeferredPathExpressionStack()
381
    {
382
        $exprStack = array_pop($this->_deferredPathExpressionStacks);
383
        $qComps = $this->_queryComponents;
384
        foreach ($exprStack as $expr) {
385 386 387 388 389 390
            $parts = $expr->getParts();
            $numParts = count($parts);
            $dqlAlias = $parts[0];
            if (count($parts) == 2) {
                $expr->setIsSimpleStateFieldPathExpression(true);
                if ( ! $qComps[$dqlAlias]['metadata']->hasField($parts[1])) {
391
                    $this->semanticalError('The class ' . $qComps[$dqlAlias]['metadata']->name
romanb's avatar
romanb committed
392
                            . ' has no simple state field named ' . $parts[1]);
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
                }
            } else {
                $embeddedClassFieldSeen = false;
                $assocSeen = false;
                for ($i = 1; $i < $numParts - 1; ++$i) {
                    if ($qComps[$dqlAlias]['metadata']->hasAssociation($parts[$i])) {
                        if ($embeddedClassFieldSeen) {
                            $this->semanticalError('Invalid navigation path.');
                        }
                        // Indirect join
                        $assoc = $qComps[$dqlAlias]['metadata']->getAssociationMapping($parts[$i]);
                        if ( ! $assoc->isOneToOne()) {
                            $this->semanticalError('Single-valued association expected.');
                        }
                        $expr->setIsSingleValuedAssociationPart($parts[$i]);
                        //TODO...
                        $assocSeen = true;
                    } else if ($qComps[$dqlAlias]['metadata']->hasEmbeddedClassField($parts[$i])) {
                        //TODO...
                        $expr->setIsEmbeddedClassPart($parts[$i]);
                        $this->syntaxError();
                    } else {
                        $this->syntaxError();
                    }
                }
                if ( ! $assocSeen) {
                    $expr->setIsSimpleStateFieldPathExpression(true);
                } else {
                    $expr->setIsSimpleStateFieldAssociationPathExpression(true);
                }
                // Last part MUST be a simple state field
                if ( ! $qComps[$dqlAlias]['metadata']->hasField($parts[$numParts-1])) {
425
                    $this->semanticalError('The class ' . $qComps[$dqlAlias]['metadata']->name
romanb's avatar
romanb committed
426
                            . ' has no simple state field named ' . $parts[$numParts-1]);
427 428 429 430 431
                }
            }
        }
    }

romanb's avatar
romanb committed
432 433 434
    /**
     * UpdateStatement ::= UpdateClause [WhereClause]
     */
romanb's avatar
romanb committed
435
    public function _UpdateStatement()
436
    {
romanb's avatar
romanb committed
437 438 439 440 441 442 443 444 445 446
        $updateStatement = new AST\UpdateStatement($this->_UpdateClause());
        $updateStatement->setWhereClause(
                $this->_lexer->isNextToken(Lexer::T_WHERE) ? $this->_WhereClause() : null
                );
        return $updateStatement;
    }

    /**
     * UpdateClause ::= "UPDATE" AbstractSchemaName [["AS"] AliasIdentificationVariable] "SET" UpdateItem {"," UpdateItem}*
     */
romanb's avatar
romanb committed
447
    public function _UpdateClause()
romanb's avatar
romanb committed
448 449 450 451 452 453 454 455 456 457
    {
        $this->match(Lexer::T_UPDATE);
        $abstractSchemaName = $this->_AbstractSchemaName();
        $aliasIdentificationVariable = null;
        if ($this->_lexer->isNextToken(Lexer::T_AS)) {
            $this->match(Lexer::T_AS);
        }
        if ($this->_lexer->isNextToken(Lexer::T_IDENTIFIER)) {
            $this->match(Lexer::T_IDENTIFIER);
            $aliasIdentificationVariable = $this->_lexer->token['value'];
romanb's avatar
romanb committed
458 459
        } else {
            $aliasIdentificationVariable = $abstractSchemaName;
romanb's avatar
romanb committed
460 461 462 463 464 465 466 467 468
        }
        $this->match(Lexer::T_SET);
        $updateItems = array();
        $updateItems[] = $this->_UpdateItem();
        while ($this->_lexer->isNextToken(',')) {
            $this->match(',');
            $updateItems[] = $this->_UpdateItem();
        }

romanb's avatar
romanb committed
469 470 471 472 473 474 475 476 477
        $classMetadata = $this->_em->getClassMetadata($abstractSchemaName);
        // Building queryComponent
        $queryComponent = array(
            'metadata' => $classMetadata,
            'parent'   => null,
            'relation' => null,
            'map'      => null,
            'scalar'   => null,
        );
478
        $this->_queryComponents[$aliasIdentificationVariable] = $queryComponent;
romanb's avatar
romanb committed
479 480 481 482 483 484 485 486 487 488

        $updateClause = new AST\UpdateClause($abstractSchemaName, $updateItems);
        $updateClause->setAliasIdentificationVariable($aliasIdentificationVariable);

        return $updateClause;
    }

    /**
     * UpdateItem ::= [IdentificationVariable "."] {StateField | SingleValuedAssociationField} "=" NewValue
     */
romanb's avatar
romanb committed
489
    public function _UpdateItem()
romanb's avatar
romanb committed
490 491 492 493 494 495 496
    {
        $peek = $this->_lexer->glimpse();
        $identVariable = null;
        if ($peek['value'] == '.') {
            $this->match(Lexer::T_IDENTIFIER);
            $identVariable = $this->_lexer->token['value'];
            $this->match('.');
romanb's avatar
romanb committed
497
        } else {
498 499
            //$identVariable = $this->_parserResult->getDefaultQueryComponentAlias();
            throw new DoctrineException("Missing alias qualifier.");
romanb's avatar
romanb committed
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
        }
        $this->match(Lexer::T_IDENTIFIER);
        $field = $this->_lexer->token['value'];
        $this->match('=');
        $newValue = $this->_NewValue();

        $updateItem = new AST\UpdateItem($field, $newValue);
        $updateItem->setIdentificationVariable($identVariable);

        return $updateItem;
    }

    /**
     * NewValue ::= SimpleArithmeticExpression | StringPrimary | DatetimePrimary | BooleanPrimary |
     *      EnumPrimary | SimpleEntityExpression | "NULL"
     */
romanb's avatar
romanb committed
516
    public function _NewValue()
romanb's avatar
romanb committed
517 518 519 520 521 522 523 524 525 526 527
    {
        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']);
        } else if ($this->_lexer->isNextToken(Lexer::T_STRING)) {
            //TODO: Can be StringPrimary or EnumPrimary
            return $this->_StringPrimary();
        } else {
528
            $this->syntaxError('Not yet implemented-1.');
romanb's avatar
romanb committed
529 530
            //echo "UH OH ...";
        }
531 532
    }

romanb's avatar
romanb committed
533 534 535
    /**
     * DeleteStatement ::= DeleteClause [WhereClause]
     */
romanb's avatar
romanb committed
536
    public function _DeleteStatement()
537
    {
romanb's avatar
romanb committed
538 539 540 541 542 543 544 545 546 547
        $deleteStatement = new AST\DeleteStatement($this->_DeleteClause());
        $deleteStatement->setWhereClause(
                $this->_lexer->isNextToken(Lexer::T_WHERE) ? $this->_WhereClause() : null
                );
        return $deleteStatement;
    }

    /**
     * DeleteClause ::= "DELETE" ["FROM"] AbstractSchemaName [["AS"] AliasIdentificationVariable]
     */
romanb's avatar
romanb committed
548
    public function _DeleteClause()
romanb's avatar
romanb committed
549 550 551 552 553 554 555 556 557 558 559 560
    {
        $this->match(Lexer::T_DELETE);
        if ($this->_lexer->isNextToken(Lexer::T_FROM)) {
            $this->match(Lexer::T_FROM);
        }
        $deleteClause = new AST\DeleteClause($this->_AbstractSchemaName());
        if ($this->_lexer->isNextToken(Lexer::T_AS)) {
            $this->match(Lexer::T_AS);
        }
        if ($this->_lexer->isNextToken(Lexer::T_IDENTIFIER)) {
            $this->match(Lexer::T_IDENTIFIER);
            $deleteClause->setAliasIdentificationVariable($this->_lexer->token['value']);
romanb's avatar
romanb committed
561 562
        } else {
            $deleteClause->setAliasIdentificationVariable($deleteClause->getAbstractSchemaName());
romanb's avatar
romanb committed
563
        }
romanb's avatar
romanb committed
564 565 566 567 568 569 570 571 572

        $classMetadata = $this->_em->getClassMetadata($deleteClause->getAbstractSchemaName());
        $queryComponent = array(
            'metadata' => $classMetadata,
            'parent'   => null,
            'relation' => null,
            'map'      => null,
            'scalar'   => null,
        );
573 574 575
        $this->_queryComponents[$deleteClause->getAliasIdentificationVariable()] = $queryComponent;
        //$this->_parserResult->setDefaultQueryComponentAlias($deleteClause->getAliasIdentificationVariable());
        //$this->_declaredClasses[$deleteClause->getAliasIdentificationVariable()] = $classMetadata;
romanb's avatar
romanb committed
576
        return $deleteClause;
577 578 579 580 581
    }

    /**
     * SelectClause ::= "SELECT" ["DISTINCT"] SelectExpression {"," SelectExpression}
     */
romanb's avatar
romanb committed
582
    public function _SelectClause()
583 584
    {
        $isDistinct = false;
romanb's avatar
romanb committed
585
        $this->match(Lexer::T_SELECT);
586 587

        // Inspecting if we are in a DISTINCT query
romanb's avatar
romanb committed
588 589
        if ($this->_lexer->isNextToken(Lexer::T_DISTINCT)) {
            $this->match(Lexer::T_DISTINCT);
590 591 592 593 594 595
            $isDistinct = true;
        }

        // Process SelectExpressions (1..N)
        $selectExpressions = array();
        $selectExpressions[] = $this->_SelectExpression();
596
        while ($this->_lexer->isNextToken(',')) {
597 598 599 600
            $this->match(',');
            $selectExpressions[] = $this->_SelectExpression();
        }

601
        return new AST\SelectClause($selectExpressions, $isDistinct);
602 603 604 605 606
    }

    /**
     * FromClause ::= "FROM" IdentificationVariableDeclaration {"," IdentificationVariableDeclaration}
     */
romanb's avatar
romanb committed
607
    public function _FromClause()
608
    {
romanb's avatar
romanb committed
609
        $this->match(Lexer::T_FROM);
610 611
        $identificationVariableDeclarations = array();
        $identificationVariableDeclarations[] = $this->_IdentificationVariableDeclaration();
612 613

        $firstRangeDecl = $identificationVariableDeclarations[0]->getRangeVariableDeclaration();
614
        /*if ($firstRangeDecl->getAliasIdentificationVariable()) {
615 616 617
            $this->_parserResult->setDefaultQueryComponentAlias($firstRangeDecl->getAliasIdentificationVariable());
        } else {
            $this->_parserResult->setDefaultQueryComponentAlias($firstRangeDecl->getAbstractSchemaName());
618
        }*/
619

620
        while ($this->_lexer->isNextToken(',')) {
621 622 623 624
            $this->match(',');
            $identificationVariableDeclarations[] = $this->_IdentificationVariableDeclaration();
        }

625
        return new AST\FromClause($identificationVariableDeclarations);
626 627 628 629 630
    }

    /**
     * SelectExpression ::=
     *      IdentificationVariable | StateFieldPathExpression |
631 632
     *      (AggregateExpression | "(" Subselect ")") [["AS"] FieldAliasIdentificationVariable] |
     *      Function
633
     */
romanb's avatar
romanb committed
634
    public function _SelectExpression()
635 636 637
    {
        $expression = null;
        $fieldIdentificationVariable = null;
638
        $peek = $this->_lexer->glimpse();
639
        // First we recognize for an IdentificationVariable (DQL class alias)
640
        if ($peek['value'] != '.' && $peek['value'] != '(' && $this->_lexer->lookahead['type'] === Lexer::T_IDENTIFIER) {
641 642
            $expression = $this->_IdentificationVariable();
        } else if (($isFunction = $this->_isFunction()) !== false || $this->_isSubselect()) {
romanb's avatar
romanb committed
643
            if ($isFunction) {
644 645 646 647 648
                if ($this->_isAggregateFunction($this->_lexer->lookahead['type'])) {
                    $expression = $this->_AggregateExpression();
                } else {
                    $expression = $this->_Function();
                }
romanb's avatar
romanb committed
649 650 651 652 653
            } else {
                $this->match('(');
                $expression = $this->_Subselect();
                $this->match(')');
            }
romanb's avatar
romanb committed
654 655
            if ($this->_lexer->isNextToken(Lexer::T_AS)) {
                $this->match(Lexer::T_AS);
romanb's avatar
romanb committed
656 657 658 659
            }
            if ($this->_lexer->isNextToken(Lexer::T_IDENTIFIER)) {
                $this->match(Lexer::T_IDENTIFIER);
                $fieldIdentificationVariable = $this->_lexer->token['value'];
660 661
            }
        } else {
662 663
            //TODO: If hydration mode is OBJECT throw an exception ("partial object dangerous...")
            // unless the doctrine.forcePartialLoad query hint is set
664
            $expression = $this->_StateFieldPathExpression();
665
        }
666
        return new AST\SelectExpression($expression, $fieldIdentificationVariable);
667 668 669 670 671
    }

    /**
     * IdentificationVariable ::= identifier
     */
romanb's avatar
romanb committed
672
    public function _IdentificationVariable()
673
    {
romanb's avatar
romanb committed
674
        $this->match(Lexer::T_IDENTIFIER);
675
        return $this->_lexer->token['value'];
676 677 678 679 680
    }

    /**
     * IdentificationVariableDeclaration ::= RangeVariableDeclaration [IndexBy] {JoinVariableDeclaration}*
     */
romanb's avatar
romanb committed
681
    public function _IdentificationVariableDeclaration()
682 683
    {
        $rangeVariableDeclaration = $this->_RangeVariableDeclaration();
romanb's avatar
romanb committed
684
        $indexBy = $this->_lexer->isNextToken(Lexer::T_INDEX) ?
685 686 687
                $this->_IndexBy() : null;
        $joinVariableDeclarations = array();
        while (
romanb's avatar
romanb committed
688 689 690
            $this->_lexer->isNextToken(Lexer::T_LEFT) ||
            $this->_lexer->isNextToken(Lexer::T_INNER) ||
            $this->_lexer->isNextToken(Lexer::T_JOIN)
691 692 693 694
        ) {
            $joinVariableDeclarations[] = $this->_JoinVariableDeclaration();
        }

695
        return new AST\IdentificationVariableDeclaration(
696 697 698 699 700 701 702
            $rangeVariableDeclaration, $indexBy, $joinVariableDeclarations
        );
    }

    /**
     * RangeVariableDeclaration ::= AbstractSchemaName ["AS"] AliasIdentificationVariable
     */
romanb's avatar
romanb committed
703
    public function _RangeVariableDeclaration()
704 705 706
    {
        $abstractSchemaName = $this->_AbstractSchemaName();

romanb's avatar
romanb committed
707 708
        if ($this->_lexer->isNextToken(Lexer::T_AS)) {
            $this->match(Lexer::T_AS);
709 710 711 712 713 714 715 716 717 718 719 720
        }
        $aliasIdentificationVariable = $this->_AliasIdentificationVariable();
        $classMetadata = $this->_em->getClassMetadata($abstractSchemaName);

        // Building queryComponent
        $queryComponent = array(
            'metadata' => $classMetadata,
            'parent'   => null,
            'relation' => null,
            'map'      => null,
            'scalar'   => null,
        );
721 722
        $this->_queryComponents[$aliasIdentificationVariable] = $queryComponent;
        //$this->_declaredClasses[$aliasIdentificationVariable] = $classMetadata;
723

724
        return new AST\RangeVariableDeclaration(
725 726 727 728 729 730 731
            $classMetadata, $aliasIdentificationVariable
        );
    }

    /**
     * AbstractSchemaName ::= identifier
     */
romanb's avatar
romanb committed
732
    public function _AbstractSchemaName()
733
    {
romanb's avatar
romanb committed
734
        $this->match(Lexer::T_IDENTIFIER);
735
        return $this->_lexer->token['value'];
736 737 738 739 740
    }

    /**
     * AliasIdentificationVariable = identifier
     */
romanb's avatar
romanb committed
741
    public function _AliasIdentificationVariable()
742
    {
romanb's avatar
romanb committed
743
        $this->match(Lexer::T_IDENTIFIER);
744
        return $this->_lexer->token['value'];
745 746 747 748 749
    }

    /**
     * JoinVariableDeclaration ::= Join [IndexBy]
     */
romanb's avatar
romanb committed
750
    public function _JoinVariableDeclaration()
751 752
    {
        $join = $this->_Join();
romanb's avatar
romanb committed
753
        $indexBy = $this->_lexer->isNextToken(Lexer::T_INDEX) ?
754
                $this->_IndexBy() : null;
755
        return new AST\JoinVariableDeclaration($join, $indexBy);
756 757 758 759 760 761
    }

    /**
     * Join ::= ["LEFT" ["OUTER"] | "INNER"] "JOIN" JoinAssociationPathExpression
     *          ["AS"] AliasIdentificationVariable [("ON" | "WITH") ConditionalExpression]
     */
romanb's avatar
romanb committed
762
    public function _Join()
763 764
    {
        // Check Join type
765
        $joinType = AST\Join::JOIN_TYPE_INNER;
romanb's avatar
romanb committed
766 767
        if ($this->_lexer->isNextToken(Lexer::T_LEFT)) {
            $this->match(Lexer::T_LEFT);
768
            // Possible LEFT OUTER join
romanb's avatar
romanb committed
769 770
            if ($this->_lexer->isNextToken(Lexer::T_OUTER)) {
                $this->match(Lexer::T_OUTER);
771
                $joinType = AST\Join::JOIN_TYPE_LEFTOUTER;
772
            } else {
773
                $joinType = AST\Join::JOIN_TYPE_LEFT;
774
            }
romanb's avatar
romanb committed
775 776
        } else if ($this->_lexer->isNextToken(Lexer::T_INNER)) {
            $this->match(Lexer::T_INNER);
777 778
        }

romanb's avatar
romanb committed
779
        $this->match(Lexer::T_JOIN);
780 781

        $joinPathExpression = $this->_JoinPathExpression();
romanb's avatar
romanb committed
782 783
        if ($this->_lexer->isNextToken(Lexer::T_AS)) {
            $this->match(Lexer::T_AS);
784 785 786 787 788 789
        }

        $aliasIdentificationVariable = $this->_AliasIdentificationVariable();

        // Verify that the association exists, if yes update the ParserResult
        // with the new component.
790 791
        //$parentComp = $this->_parserResult->getQueryComponent($joinPathExpression->getIdentificationVariable());
        $parentClass = $this->_queryComponents[$joinPathExpression->getIdentificationVariable()]['metadata'];
792 793
        $assocField = $joinPathExpression->getAssociationField();
        if ( ! $parentClass->hasAssociation($assocField)) {
794
            $this->semanticalError("Class " . $parentClass->name .
795 796 797 798 799 800 801 802 803 804 805 806
                    " has no association named '$assocField'.");
        }
        $targetClassName = $parentClass->getAssociationMapping($assocField)->getTargetEntityName();

        // Building queryComponent
        $joinQueryComponent = array(
            'metadata' => $this->_em->getClassMetadata($targetClassName),
            'parent'   => $joinPathExpression->getIdentificationVariable(),
            'relation' => $parentClass->getAssociationMapping($assocField),
            'map'      => null,
            'scalar'   => null,
        );
807 808
        $this->_queryComponents[$aliasIdentificationVariable] = $joinQueryComponent;
        //$this->_declaredClasses[$aliasIdentificationVariable] = $this->_em->getClassMetadata($targetClassName);
809 810

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

        // Check Join where type
romanb's avatar
romanb committed
814
        if ($this->_lexer->isNextToken(Lexer::T_ON) || $this->_lexer->isNextToken(Lexer::T_WITH)) {
romanb's avatar
romanb committed
815 816
            if ($this->_lexer->isNextToken(Lexer::T_ON)) {
                $this->match(Lexer::T_ON);
817
                $join->setWhereType(AST\Join::JOIN_WHERE_ON);
818
            } else {
romanb's avatar
romanb committed
819
                $this->match(Lexer::T_WITH);
820 821 822 823 824 825 826 827 828 829
            }
            $join->setConditionalExpression($this->_ConditionalExpression());
        }

        return $join;
    }

    /**
     * JoinPathExpression ::= IdentificationVariable "." (CollectionValuedAssociationField | SingleValuedAssociationField)
     */
romanb's avatar
romanb committed
830
    public function _JoinPathExpression()
831 832 833
    {
        $identificationVariable = $this->_IdentificationVariable();
        $this->match('.');
romanb's avatar
romanb committed
834
        $this->match(Lexer::T_IDENTIFIER);
835 836
        $assocField = $this->_lexer->token['value'];
        return new AST\JoinPathExpression(
837 838 839 840 841 842 843
            $identificationVariable, $assocField
        );
    }

    /**
     * IndexBy ::= "INDEX" "BY" SimpleStateFieldPathExpression
     */
romanb's avatar
romanb committed
844
    public function _IndexBy()
845
    {
romanb's avatar
romanb committed
846 847
        $this->match(Lexer::T_INDEX);
        $this->match(Lexer::T_BY);
848 849
        $pathExp = $this->_SimpleStateFieldPathExpression();
        // Add the INDEX BY info to the query component
850
        $this->_queryComponents[$pathExp->getIdentificationVariable()]['map'] = $pathExp->getSimpleStateField();
851 852 853 854 855 856
        return $pathExp;
    }

    /**
     * SimpleStateFieldPathExpression ::= IdentificationVariable "." StateField
     */
romanb's avatar
romanb committed
857
    public function _SimpleStateFieldPathExpression()
858 859 860
    {
        $identificationVariable = $this->_IdentificationVariable();
        $this->match('.');
romanb's avatar
romanb committed
861
        $this->match(Lexer::T_IDENTIFIER);
862 863
        $simpleStateField = $this->_lexer->token['value'];
        return new AST\SimpleStateFieldPathExpression($identificationVariable, $simpleStateField);
864 865
    }

866 867 868
    /**
     * StateFieldPathExpression ::= SimpleStateFieldPathExpression | SimpleStateFieldAssociationPathExpression
     */
romanb's avatar
romanb committed
869
    public function _StateFieldPathExpression()
870
    {
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885
        if ( ! empty($this->_deferredPathExpressionStacks)) {
            $exprStack = array_pop($this->_deferredPathExpressionStacks);
            $this->match(Lexer::T_IDENTIFIER);
            $parts = array($this->_lexer->token['value']);
            while ($this->_lexer->isNextToken('.')) {
                $this->match('.');
                $this->match(Lexer::T_IDENTIFIER);
                $parts[] = $this->_lexer->token['value'];
            }
            $expr = new AST\StateFieldPathExpression($parts);
            $exprStack[] = $expr;
            array_push($this->_deferredPathExpressionStacks, $exprStack);
            return $expr; // EARLY EXIT!
        }

886 887 888 889 890
        $parts = array();
        $stateFieldSeen = false;
        $assocSeen = false;

        $identificationVariable = $this->_IdentificationVariable();
891
        if ( ! isset($this->_queryComponents[$identificationVariable])) {
892
            $this->syntaxError("Identification variable '$identificationVariable' was not declared.");
893
        }
894

895
        $qComp = $this->_queryComponents[$identificationVariable];
896 897 898 899
        $parts[] = $identificationVariable;

        $class = $qComp['metadata'];

900
        if ( ! $this->_lexer->isNextToken('.')) {
901 902 903 904
            if ($class->isIdentifierComposite) {
                $this->syntaxError();
            }
            $parts[] = $class->identifier[0];
905 906
        }
        
907
        while ($this->_lexer->isNextToken('.')) {
908 909 910 911 912 913 914 915 916 917
            if ($stateFieldSeen) $this->syntaxError();
            $this->match('.');
            $part = $this->_IdentificationVariable();
            if ($class->hasField($part)) {
                $stateFieldSeen = true;
            } else if ($class->hasAssociation($part)) {
                $assoc = $class->getAssociationMapping($part);
                $class = $this->_em->getClassMetadata($assoc->getTargetEntityName());
                $assocSeen = true;
            } else {
918
                $this->semanticalError('The class ' . $class->name .
romanb's avatar
romanb committed
919
                        ' has no field or association named ' . $part);
920 921 922 923
            }
            $parts[] = $part;
        }

924 925 926 927 928
        /*$lastPart = $parts[count($parts) - 1];
        if ($class->hasAssociation($lastPart)) {
            
        }*/

929
        $pathExpr = new AST\StateFieldPathExpression($parts);
930 931 932 933 934 935 936 937 938 939

        if ($assocSeen) {
            $pathExpr->setIsSimpleStateFieldAssociationPathExpression(true);
        } else {
            $pathExpr->setIsSimpleStateFieldPathExpression(true);
        }

        return $pathExpr;
    }

940 941 942
    /**
     * NullComparisonExpression ::= (SingleValuedPathExpression | InputParameter) "IS" ["NOT"] "NULL"
     */
romanb's avatar
romanb committed
943
    public function _NullComparisonExpression()
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
    {
        if ($this->_lexer->isNextToken(Lexer::T_INPUT_PARAMETER)) {
            $this->match(Lexer::T_INPUT_PARAMETER);
            $expr = new AST\InputParameter($this->_lexer->token['value']);
        } else {
            //TODO: Support SingleValuedAssociationPathExpression
            $expr = $this->_StateFieldPathExpression();
        }
        $nullCompExpr = new AST\NullComparisonExpression($expr);
        $this->match(Lexer::T_IS);
        if ($this->_lexer->isNextToken(Lexer::T_NOT)) {
            $this->match(Lexer::T_NOT);
            $nullCompExpr->setNot(true);
        }
        $this->match(Lexer::T_NULL);
        return $nullCompExpr;
    }

962 963 964 965 966
    /**
     * AggregateExpression ::=
     *  ("AVG" | "MAX" | "MIN" | "SUM") "(" ["DISTINCT"] StateFieldPathExpression ")" |
     *  "COUNT" "(" ["DISTINCT"] (IdentificationVariable | SingleValuedAssociationPathExpression | StateFieldPathExpression) ")"
     */
romanb's avatar
romanb committed
967
    public function _AggregateExpression()
968 969 970
    {
        $isDistinct = false;
        $functionName = '';
romanb's avatar
romanb committed
971 972
        if ($this->_lexer->isNextToken(Lexer::T_COUNT)) {
            $this->match(Lexer::T_COUNT);
973
            $functionName = $this->_lexer->token['value'];
974
            $this->match('(');
romanb's avatar
romanb committed
975 976
            if ($this->_lexer->isNextToken(Lexer::T_DISTINCT)) {
                $this->match(Lexer::T_DISTINCT);
977 978 979
                $isDistinct = true;
            }
            // For now we only support a PathExpression here...
980
            $pathExp = $this->_StateFieldPathExpression();
981
            $this->match(')');
romanb's avatar
romanb committed
982 983 984 985 986 987 988 989 990 991 992 993
        } 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');
            }
994
            $functionName = $this->_lexer->token['value'];
995
            $this->match('(');
romanb's avatar
romanb committed
996 997
            $pathExp = $this->_StateFieldPathExpression();
            $this->match(')');
998
        }
999
        return new AST\AggregateExpression($functionName, $pathExp, $isDistinct);
1000 1001 1002 1003 1004 1005
    }

    /**
     * GroupByClause ::= "GROUP" "BY" GroupByItem {"," GroupByItem}*
     * GroupByItem ::= SingleValuedPathExpression
     */
romanb's avatar
romanb committed
1006
    public function _GroupByClause()
1007
    {
romanb's avatar
romanb committed
1008 1009
        $this->match(Lexer::T_GROUP);
        $this->match(Lexer::T_BY);
1010
        $groupByItems = array();
1011
        $groupByItems[] = $this->_StateFieldPathExpression();
1012
        while ($this->_lexer->isNextToken(',')) {
1013
            $this->match(',');
1014
            $groupByItems[] = $this->_StateFieldPathExpression();
1015
        }
1016
        return new AST\GroupByClause($groupByItems);
1017 1018
    }

romanb's avatar
romanb committed
1019 1020 1021
    /**
     * HavingClause ::= "HAVING" ConditionalExpression
     */
romanb's avatar
romanb committed
1022
    public function _HavingClause()
romanb's avatar
romanb committed
1023 1024 1025 1026 1027 1028 1029 1030
    {
        $this->match(Lexer::T_HAVING);
        return new AST\HavingClause($this->_ConditionalExpression());
    }

    /**
     * OrderByClause ::= "ORDER" "BY" OrderByItem {"," OrderByItem}*
     */
romanb's avatar
romanb committed
1031
    public function _OrderByClause()
romanb's avatar
romanb committed
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
    {
        $this->match(Lexer::T_ORDER);
        $this->match(Lexer::T_BY);
        $orderByItems = array();
        $orderByItems[] = $this->_OrderByItem();
        while ($this->_lexer->isNextToken(',')) {
            $this->match(',');
            $orderByItems[] = $this->_OrderByItem();
        }
        return new AST\OrderByClause($orderByItems);
    }

    /**
     * OrderByItem ::= StateFieldPathExpression ["ASC" | "DESC"]
     */
romanb's avatar
romanb committed
1047
    public function _OrderByItem()
romanb's avatar
romanb committed
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
    {
        $item = new AST\OrderByItem($this->_StateFieldPathExpression());
        if ($this->_lexer->isNextToken(Lexer::T_ASC)) {
            $this->match(Lexer::T_ASC);
            $item->setAsc(true);
        } else if ($this->_lexer->isNextToken(Lexer::T_DESC)) {
            $this->match(Lexer::T_DESC);
            $item->setDesc(true);
        } else {
            $item->setDesc(true);
        }
        return $item;
    }

1062 1063 1064
    /**
     * WhereClause ::= "WHERE" ConditionalExpression
     */
romanb's avatar
romanb committed
1065
    public function _WhereClause()
1066
    {
romanb's avatar
romanb committed
1067
        $this->match(Lexer::T_WHERE);
1068
        return new AST\WhereClause($this->_ConditionalExpression());
1069 1070 1071 1072 1073
    }

    /**
     * ConditionalExpression ::= ConditionalTerm {"OR" ConditionalTerm}*
     */
romanb's avatar
romanb committed
1074
    public function _ConditionalExpression()
1075 1076 1077
    {
        $conditionalTerms = array();
        $conditionalTerms[] = $this->_ConditionalTerm();
romanb's avatar
romanb committed
1078 1079
        while ($this->_lexer->isNextToken(Lexer::T_OR)) {
            $this->match(Lexer::T_OR);
1080 1081
            $conditionalTerms[] = $this->_ConditionalTerm();
        }
1082
        return new AST\ConditionalExpression($conditionalTerms);
1083 1084 1085 1086 1087
    }

    /**
     * ConditionalTerm ::= ConditionalFactor {"AND" ConditionalFactor}*
     */
romanb's avatar
romanb committed
1088
    public function _ConditionalTerm()
1089 1090 1091
    {
        $conditionalFactors = array();
        $conditionalFactors[] = $this->_ConditionalFactor();
romanb's avatar
romanb committed
1092 1093
        while ($this->_lexer->isNextToken(Lexer::T_AND)) {
            $this->match(Lexer::T_AND);
1094 1095
            $conditionalFactors[] = $this->_ConditionalFactor();
        }
1096
        return new AST\ConditionalTerm($conditionalFactors);
1097 1098 1099 1100 1101
    }

    /**
     * ConditionalFactor ::= ["NOT"] ConditionalPrimary
     */
romanb's avatar
romanb committed
1102
    public function _ConditionalFactor()
1103 1104
    {
        $not = false;
romanb's avatar
romanb committed
1105 1106
        if ($this->_lexer->isNextToken(Lexer::T_NOT)) {
            $this->match(Lexer::T_NOT);
1107 1108
            $not = true;
        }
1109
        return new AST\ConditionalFactor($this->_ConditionalPrimary(), $not);
1110 1111 1112 1113 1114
    }

    /**
     * ConditionalPrimary ::= SimpleConditionalExpression | "(" ConditionalExpression ")"
     */
romanb's avatar
romanb committed
1115
    public function _ConditionalPrimary()
1116
    {
1117 1118
        $condPrimary = new AST\ConditionalPrimary;
        if ($this->_lexer->isNextToken('(')) {
1119
            $numUnmatched = 1;
1120
            $peek = $this->_lexer->peek();
1121 1122 1123 1124 1125 1126
            while ($numUnmatched > 0) {
                if ($peek['value'] == ')') {
                    --$numUnmatched;
                } else if ($peek['value'] == '(') {
                    ++$numUnmatched;
                }
1127
                $peek = $this->_lexer->peek();
1128
            }
1129
            $this->_lexer->resetPeek();
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141

            //TODO: This is not complete, what about LIKE/BETWEEN/...etc?
            $comparisonOps = array("=",  "<", "<=", "<>", ">", ">=", "!=");

            if (in_array($peek['value'], $comparisonOps)) {
                $condPrimary->setSimpleConditionalExpression($this->_SimpleConditionalExpression());
            } else {
                $this->match('(');
                $conditionalExpression = $this->_ConditionalExpression();
                $this->match(')');
                $condPrimary->setConditionalExpression($conditionalExpression);
            }
1142 1143 1144 1145 1146 1147 1148
        } else {
            $condPrimary->setSimpleConditionalExpression($this->_SimpleConditionalExpression());
        }
        return $condPrimary;
    }

    /**
romanb's avatar
romanb committed
1149 1150 1151 1152
     * SimpleConditionalExpression ::=
     *      ComparisonExpression | BetweenExpression | LikeExpression |
     *      InExpression | NullComparisonExpression | ExistsExpression |
     *      EmptyCollectionComparisonExpression | CollectionMemberExpression
1153
     */
romanb's avatar
romanb committed
1154
    public function _SimpleConditionalExpression()
1155
    {
romanb's avatar
romanb committed
1156
        if ($this->_lexer->isNextToken(Lexer::T_NOT)) {
1157
            $token = $this->_lexer->glimpse();
1158
        } else {
1159
            $token = $this->_lexer->lookahead;
1160
        }
romanb's avatar
romanb committed
1161
        if ($token['type'] === Lexer::T_EXISTS) {
1162 1163 1164
            return $this->_ExistsExpression();
        }

1165
        $stateFieldPathExpr = false;
romanb's avatar
romanb committed
1166
        if ($token['type'] === Lexer::T_IDENTIFIER) {
1167 1168
            // Peek beyond the PathExpression
            $stateFieldPathExpr = true;
1169
            $peek = $this->_lexer->peek();
1170
            while ($peek['value'] === '.') {
1171 1172
                $this->_lexer->peek();
                $peek = $this->_lexer->peek();
1173
            }
romanb's avatar
romanb committed
1174 1175 1176 1177 1178 1179

            // Also peek beyond a NOT if there is one
            if ($peek['type'] === Lexer::T_NOT) {
                $peek = $this->_lexer->peek();
            }

1180
            $this->_lexer->resetPeek();
1181 1182
            $token = $peek;
        }
1183

1184 1185
        if ($stateFieldPathExpr) {
            switch ($token['type']) {
romanb's avatar
romanb committed
1186
                case Lexer::T_BETWEEN:
1187
                    return $this->_BetweenExpression();
romanb's avatar
romanb committed
1188
                case Lexer::T_LIKE:
1189
                    return $this->_LikeExpression();
romanb's avatar
romanb committed
1190
                case Lexer::T_IN:
1191
                    return $this->_InExpression();
romanb's avatar
romanb committed
1192
                case Lexer::T_IS:
1193
                    return $this->_NullComparisonExpression();
romanb's avatar
romanb committed
1194
                case Lexer::T_NONE:
1195 1196 1197 1198 1199
                    return $this->_ComparisonExpression();
                default:
                    $this->syntaxError();
            }
        } else {
romanb's avatar
romanb committed
1200 1201
            return $this->_ComparisonExpression();
        /*} else {
1202
            switch ($token['type']) {
romanb's avatar
romanb committed
1203
                case Lexer::T_INTEGER:
1204 1205
                    // IF it turns out its a ComparisonExpression, then it MUST be ArithmeticExpression
                    break;
romanb's avatar
romanb committed
1206
                case Lexer::T_STRING:
1207 1208 1209 1210
                    // IF it turns out its a ComparisonExpression, then it MUST be StringExpression
                    break;
                default:
                    $this->syntaxError();
romanb's avatar
romanb committed
1211
            }*/
1212 1213
        }
    }
1214

1215
    /**
1216 1217 1218 1219 1220 1221 1222
     * ComparisonExpression ::=
     *          ArithmeticExpression ComparisonOperator (QuantifiedExpression | ArithmeticExpression) |
     *          StringExpression ComparisonOperator (StringExpression | QuantifiedExpression) |
     *          BooleanExpression ("=" | "<>" | "!=") (BooleanExpression | QuantifiedExpression) |
     *          EnumExpression ("=" | "<>" | "!=") (EnumExpression | QuantifiedExpression) |
     *          DatetimeExpression ComparisonOperator (DatetimeExpression | QuantifiedExpression) |
     *          EntityExpression ("=" | "<>") (EntityExpression | QuantifiedExpression)
1223
     */
romanb's avatar
romanb committed
1224
    public function _ComparisonExpression()
1225
    {
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
        $peek = $this->_lexer->glimpse();

        if ($this->_lexer->isNextToken(Lexer::T_INPUT_PARAMETER)) {
            if ($this->_isComparisonOperator($peek)) {
                $this->match(Lexer::T_INPUT_PARAMETER);
                $leftExpr = new AST\InputParameter($this->_lexer->token['value']);
            } else {
                $leftExpr = $this->_ArithmeticExpression();
            }
            $operator = $this->_ComparisonOperator();
1236
            $rightExpr = $this->_ArithmeticExpression();
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
            //...
        }
        else if ($this->_lexer->isNextToken('(') && $peek['type'] == Lexer::T_SELECT) {
            $leftExpr = $this->_Subselect();
            //...
        }
        else if ($this->_lexer->isNextToken(Lexer::T_IDENTIFIER) && $peek['value'] == '(') {
            $peek2 = $this->_peekBeyond(')');
            if ($this->_isComparisonOperator($peek2)) {
                if ($this->_isStringFunction($this->_lexer->lookahead['value'])) {
                    $leftExpr = $this->_FunctionsReturningStrings();
                    $operator = $this->_ComparisonOperator();
                    if ($this->_lexer->lookahead['type'] === Lexer::T_ALL ||
                            $this->_lexer->lookahead['type'] === Lexer::T_ANY ||
                            $this->_lexer->lookahead['type'] === Lexer::T_SOME) {
                        $rightExpr = $this->_QuantifiedExpression();
                    } else {
                        $rightExpr = $this->_StringPrimary();
                    }
                } else if ($this->_isNumericFunction($this->_lexer->lookahead['value'])) {
                    $leftExpr = $this->_FunctionsReturningNumerics();
                    $operator = $this->_ComparisonOperator();
                    if ($this->_lexer->lookahead['type'] === Lexer::T_ALL ||
                            $this->_lexer->lookahead['type'] === Lexer::T_ANY ||
                            $this->_lexer->lookahead['type'] === Lexer::T_SOME) {
                        $rightExpr = $this->_QuantifiedExpression();
                    } else {
                        $rightExpr = $this->_ArithmeticExpression();
                    }
                } else {
                    $leftExpr = $this->_FunctionsReturningDatetime();
                    $operator = $this->_ComparisonOperator();
                    if ($this->_lexer->lookahead['type'] === Lexer::T_ALL ||
                            $this->_lexer->lookahead['type'] === Lexer::T_ANY ||
                            $this->_lexer->lookahead['type'] === Lexer::T_SOME) {
                        $rightExpr = $this->_QuantifiedExpression();
                    } else {
                        $rightExpr = $this->_DatetimePrimary();
                    }
                }
            } else {
                $leftExpr = $this->_ArithmeticExpression();
                $operator = $this->_ComparisonOperator();
                if ($this->_lexer->lookahead['type'] === Lexer::T_ALL ||
                        $this->_lexer->lookahead['type'] === Lexer::T_ANY ||
                        $this->_lexer->lookahead['type'] === Lexer::T_SOME) {
                    $rightExpr = $this->_QuantifiedExpression();
                } else {
                    $rightExpr = $this->_StringExpression();
                }
            }
1288
        } else {
1289 1290 1291 1292 1293 1294 1295 1296 1297
            $leftExpr = $this->_ArithmeticExpression();
            $operator = $this->_ComparisonOperator();
            if ($this->_lexer->lookahead['type'] === Lexer::T_ALL ||
                    $this->_lexer->lookahead['type'] === Lexer::T_ANY ||
                    $this->_lexer->lookahead['type'] === Lexer::T_SOME) {
                $rightExpr = $this->_QuantifiedExpression();
            } else {
                $rightExpr = $this->_ArithmeticExpression();
            }
1298
        }
1299

1300
        return new AST\ComparisonExpression($leftExpr, $operator, $rightExpr);
1301
    }
1302

1303 1304 1305
    /**
     * Function ::= FunctionsReturningStrings | FunctionsReturningNumerics | FunctionsReturningDatetime
     */
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
    public function _Function()
    {
        $funcName = $this->_lexer->lookahead['value'];
        if ($this->_isStringFunction($funcName)) {
            return $this->_FunctionsReturningStrings();
        } else if ($this->_isNumericFunction($funcName)) {
            return $this->_FunctionsReturningNumerics();
        } else if ($this->_isDatetimeFunction($funcName)) {
            return $this->_FunctionsReturningDatetime();
        } else {
            $this->syntaxError('Known function.');
        }
    }

1320 1321 1322 1323
    /**
     * Checks whether the function with the given name is a string function
     * (a function that returns strings).
     */
romanb's avatar
romanb committed
1324
    public function _isStringFunction($funcName)
1325 1326 1327 1328
    {
        return isset(self::$_STRING_FUNCTIONS[strtolower($funcName)]);
    }

1329 1330 1331 1332
    /**
     * Checks whether the function with the given name is a numeric function
     * (a function that returns numerics).
     */
romanb's avatar
romanb committed
1333
    public function _isNumericFunction($funcName)
1334 1335 1336 1337
    {
        return isset(self::$_NUMERIC_FUNCTIONS[strtolower($funcName)]);
    }

1338 1339 1340 1341
    /**
     * Checks whether the function with the given name is a datetime function
     * (a function that returns date/time values).
     */
romanb's avatar
romanb committed
1342
    public function _isDatetimeFunction($funcName)
1343 1344 1345 1346
    {
        return isset(self::$_DATETIME_FUNCTIONS[strtolower($funcName)]);
    }

1347 1348 1349
    /**
     * Peeks beyond the specified token and returns the first token after that one.
     */
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
    private function _peekBeyond($token)
    {
        $peek = $this->_lexer->peek();
        while ($peek['value'] != $token) {
            $peek = $this->_lexer->peek();
        }
        $peek = $this->_lexer->peek();
        $this->_lexer->resetPeek();
        return $peek;
    }

1361 1362 1363
    /**
     * Checks whether the given token is a comparison operator.
     */
romanb's avatar
romanb committed
1364
    public function _isComparisonOperator($token)
1365 1366 1367 1368 1369 1370
    {
        $value = $token['value'];
        return $value == '=' || $value == '<' || $value == '<=' || $value == '<>' ||
                $value == '>' || $value == '>=' || $value == '!=';
    }

1371 1372 1373
    /**
     * ArithmeticExpression ::= SimpleArithmeticExpression | "(" Subselect ")"
     */
romanb's avatar
romanb committed
1374
    public function _ArithmeticExpression()
1375
    {
1376 1377 1378
        $expr = new AST\ArithmeticExpression;
        if ($this->_lexer->lookahead['value'] === '(') {
            $peek = $this->_lexer->glimpse();
romanb's avatar
romanb committed
1379
            if ($peek['type'] === Lexer::T_SELECT) {
1380
                $this->match('(');
1381
                $expr->setSubselect($this->_Subselect());
1382
                $this->match(')');
1383 1384 1385 1386 1387 1388
                return $expr;
            }
        }
        $expr->setSimpleArithmeticExpression($this->_SimpleArithmeticExpression());
        return $expr;
    }
1389

1390 1391 1392
    /**
     * SimpleArithmeticExpression ::= ArithmeticTerm {("+" | "-") ArithmeticTerm}*
     */
romanb's avatar
romanb committed
1393
    public function _SimpleArithmeticExpression()
1394 1395 1396
    {
        $terms = array();
        $terms[] = $this->_ArithmeticTerm();
1397 1398
        while ($this->_lexer->lookahead['value'] == '+' || $this->_lexer->lookahead['value'] == '-') {
            if ($this->_lexer->lookahead['value'] == '+') {
1399 1400 1401 1402
                $this->match('+');
            } else {
                $this->match('-');
            }
1403
            $terms[] = $this->_lexer->token['value'];
1404 1405
            $terms[] = $this->_ArithmeticTerm();
        }
1406
        return new AST\SimpleArithmeticExpression($terms);
1407
    }
1408

1409 1410 1411
    /**
     * ArithmeticTerm ::= ArithmeticFactor {("*" | "/") ArithmeticFactor}*
     */
romanb's avatar
romanb committed
1412
    public function _ArithmeticTerm()
1413 1414 1415
    {
        $factors = array();
        $factors[] = $this->_ArithmeticFactor();
1416 1417
        while ($this->_lexer->lookahead['value'] == '*' || $this->_lexer->lookahead['value'] == '/') {
            if ($this->_lexer->lookahead['value'] == '*') {
1418 1419 1420 1421
                $this->match('*');
            } else {
                $this->match('/');
            }
1422
            $factors[] = $this->_lexer->token['value'];
1423
            $factors[] = $this->_ArithmeticFactor();
1424
        }
1425
        return new AST\ArithmeticTerm($factors);
1426
    }
1427

1428 1429 1430
    /**
     * ArithmeticFactor ::= [("+" | "-")] ArithmeticPrimary
     */
romanb's avatar
romanb committed
1431
    public function _ArithmeticFactor()
1432 1433
    {
        $pSign = $nSign = false;
1434
        if ($this->_lexer->lookahead['value'] == '+') {
1435 1436
            $this->match('+');
            $pSign = true;
1437
        } else if ($this->_lexer->lookahead['value'] == '-') {
1438 1439 1440
            $this->match('-');
            $nSign = true;
        }
1441
        return new AST\ArithmeticFactor($this->_ArithmeticPrimary(), $pSign, $nSign);
1442 1443
    }

romanb's avatar
romanb committed
1444 1445 1446
    /**
     * InExpression ::= StateFieldPathExpression ["NOT"] "IN" "(" (Literal {"," Literal}* | Subselect) ")"
     */
romanb's avatar
romanb committed
1447
    public function _InExpression()
romanb's avatar
romanb committed
1448
    {
1449
        $inExpression = new AST\InExpression($this->_StateFieldPathExpression());
romanb's avatar
romanb committed
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464
        if ($this->_lexer->isNextToken(Lexer::T_NOT)) {
            $this->match(Lexer::T_NOT);
            $inExpression->setNot(true);
        }
        $this->match(Lexer::T_IN);
        $this->match('(');
        if ($this->_lexer->isNextToken(Lexer::T_SELECT)) {
            $inExpression->setSubselect($this->_Subselect());
        } else {
            $literals = array();
            $literals[] = $this->_Literal();
            while ($this->_lexer->isNextToken(',')) {
                $this->match(',');
                $literals[] = $this->_Literal();
            }
romanb's avatar
romanb committed
1465
            $inExpression->setLiterals($literals);
romanb's avatar
romanb committed
1466 1467 1468 1469 1470 1471
        }
        $this->match(')');

        return $inExpression;
    }

romanb's avatar
romanb committed
1472 1473 1474
    /**
     * ExistsExpression ::= ["NOT"] "EXISTS" "(" Subselect ")"
     */
romanb's avatar
romanb committed
1475
    public function _ExistsExpression()
romanb's avatar
romanb committed
1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
    {
        $not = false;
        if ($this->_lexer->isNextToken(Lexer::T_NOT)) {
            $this->match(Lexer::T_NOT);
            $not = true;
        }
        $this->match(Lexer::T_EXISTS);
        $this->match('(');
        $existsExpression = new AST\ExistsExpression($this->_Subselect());
        $this->match(')');
        $existsExpression->setNot($not);
        return $existsExpression;
    }

1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516
    /**
     * QuantifiedExpression ::= ("ALL" | "ANY" | "SOME") "(" Subselect ")"
     */
    public function _QuantifiedExpression()
    {
        $all = $any = $some = false;
        if ($this->_lexer->isNextToken(Lexer::T_ALL)) {
            $this->match(Lexer::T_ALL);
            $all = true;
        } else if ($this->_lexer->isNextToken(Lexer::T_ANY)) {
            $this->match(Lexer::T_ANY);
            $any = true;
        } else if ($this->_lexer->isNextToken(Lexer::T_SOME)) {
            $this->match(Lexer::T_SOME);
            $some = true;
        } else {
            $this->syntaxError('ALL, ANY or SOME');
        }
        $this->match('(');
        $qExpr = new AST\QuantifiedExpression($this->_Subselect());
        $this->match(')');
        $qExpr->setAll($all);
        $qExpr->setAny($any);
        $qExpr->setSome($some);
        return $qExpr;
    }

romanb's avatar
romanb committed
1517 1518 1519
    /**
     * 	Subselect ::= SimpleSelectClause SubselectFromClause [WhereClause] [GroupByClause] [HavingClause] [OrderByClause]
     */
romanb's avatar
romanb committed
1520
    public function _Subselect()
romanb's avatar
romanb committed
1521
    {
1522
        $this->_beginDeferredPathExpressionStack();
romanb's avatar
romanb committed
1523
        $subselect = new AST\Subselect($this->_SimpleSelectClause(), $this->_SubselectFromClause());
1524
        $this->_processDeferredPathExpressionStack();
romanb's avatar
romanb committed
1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547

        $subselect->setWhereClause(
                $this->_lexer->isNextToken(Lexer::T_WHERE) ? $this->_WhereClause() : null
                );

        $subselect->setGroupByClause(
                $this->_lexer->isNextToken(Lexer::T_GROUP) ? $this->_GroupByClause() : null
                );

        $subselect->setHavingClause(
                $this->_lexer->isNextToken(Lexer::T_HAVING) ? $this->_HavingClause() : null
                );

        $subselect->setOrderByClause(
                $this->_lexer->isNextToken(Lexer::T_ORDER) ? $this->_OrderByClause() : null
                );

        return $subselect;
    }

    /**
     * SimpleSelectClause ::= "SELECT" ["DISTINCT"] SimpleSelectExpression
     */
romanb's avatar
romanb committed
1548
    public function _SimpleSelectClause()
romanb's avatar
romanb committed
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563
    {
        $distinct = false;
        $this->match(Lexer::T_SELECT);
        if ($this->_lexer->isNextToken(Lexer::T_DISTINCT)) {
            $this->match(Lexer::T_DISTINCT);
            $distinct = true;
        }
        $simpleSelectClause = new AST\SimpleSelectClause($this->_SimpleSelectExpression());
        $simpleSelectClause->setDistinct($distinct);
        return $simpleSelectClause;
    }

    /**
     * SubselectFromClause ::= "FROM" SubselectIdentificationVariableDeclaration {"," SubselectIdentificationVariableDeclaration}*
     */
romanb's avatar
romanb committed
1564
    public function _SubselectFromClause()
romanb's avatar
romanb committed
1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578
    {
        $this->match(Lexer::T_FROM);
        $identificationVariables = array();
        $identificationVariables[] = $this->_SubselectIdentificationVariableDeclaration();
        while ($this->_lexer->isNextToken(',')) {
            $this->match(',');
            $identificationVariables[] = $this->_SubselectIdentificationVariableDeclaration();
        }
        return new AST\SubselectFromClause($identificationVariables);
    }

    /**
     * SubselectIdentificationVariableDeclaration ::= IdentificationVariableDeclaration | (AssociationPathExpression ["AS"] AliasIdentificationVariable)
     */
romanb's avatar
romanb committed
1579
    public function _SubselectIdentificationVariableDeclaration()
romanb's avatar
romanb committed
1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594
    {
        $peek = $this->_lexer->glimpse();
        if ($peek['value'] == '.') {
            $subselectIdentificationVarDecl = new AST\SubselectIdentificationVariableDeclaration;
            $subselectIdentificationVarDecl->setAssociationPathExpression($this->_AssociationPathExpression());
            $this->match(Lexer::T_AS);
            $this->match(Lexer::T_IDENTIFIER);
            $subselectIdentificationVarDecl->setAliasIdentificationVariable($this->_lexer->token['value']);
            return $subselectIdentificationVarDecl;
        } else {
            return $this->_IdentificationVariableDeclaration();
        }
    }

    /**
romanb's avatar
romanb committed
1595
     * SimpleSelectExpression ::= StateFieldPathExpression | IdentificationVariable | (AggregateExpression [["AS"] FieldAliasIdentificationVariable])
romanb's avatar
romanb committed
1596
     */
romanb's avatar
romanb committed
1597
    public function _SimpleSelectExpression()
romanb's avatar
romanb committed
1598 1599 1600 1601 1602
    {
        if ($this->_lexer->isNextToken(Lexer::T_IDENTIFIER)) {
            // SingleValuedPathExpression | IdentificationVariable
            $peek = $this->_lexer->glimpse();
            if ($peek['value'] == '.') {
1603
                return new AST\SimpleSelectExpression($this->_StateFieldPathExpression());
romanb's avatar
romanb committed
1604 1605
            } else {
                $this->match($this->_lexer->lookahead['value']);
romanb's avatar
romanb committed
1606
                return new AST\SimpleSelectExpression($this->_lexer->token['value']);
romanb's avatar
romanb committed
1607 1608
            }
        } else {
romanb's avatar
romanb committed
1609 1610 1611 1612 1613 1614 1615 1616 1617
            $expr = new AST\SimpleSelectExpression($this->_AggregateExpression());
            if ($this->_lexer->isNextToken(Lexer::T_AS)) {
                $this->match(Lexer::T_AS);
            }
            if ($this->_lexer->isNextToken(Lexer::T_IDENTIFIER)) {
                $this->match(Lexer::T_IDENTIFIER);
                $expr->setFieldIdentificationVariable($this->_lexer->token['value']);
            }
            return $expr;
romanb's avatar
romanb committed
1618 1619 1620
        }
    }

romanb's avatar
romanb committed
1621 1622 1623
    /**
     * Literal ::= string | char | integer | float | boolean | InputParameter
     */
romanb's avatar
romanb committed
1624
    public function _Literal()
romanb's avatar
romanb committed
1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
    {
        switch ($this->_lexer->lookahead['type']) {
            case Lexer::T_INPUT_PARAMETER:
                $this->match($this->_lexer->lookahead['value']);
                return new AST\InputParameter($this->_lexer->token['value']);
            case Lexer::T_STRING:
            case Lexer::T_INTEGER:
            case Lexer::T_FLOAT:
                $this->match($this->_lexer->lookahead['value']);
                return $this->_lexer->token['value'];
            default:
                $this->syntaxError();
        }
    }

romanb's avatar
romanb committed
1640 1641 1642
    /**
     * BetweenExpression ::= ArithmeticExpression ["NOT"] "BETWEEN" ArithmeticExpression "AND" ArithmeticExpression
     */
romanb's avatar
romanb committed
1643
    public function _BetweenExpression()
romanb's avatar
romanb committed
1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661
    {
        $not = false;
        $arithExpr1 = $this->_ArithmeticExpression();
        if ($this->_lexer->isNextToken(Lexer::T_NOT)) {
            $this->match(Lexer::T_NOT);
            $not = true;
        }
        $this->match(Lexer::T_BETWEEN);
        $arithExpr2 = $this->_ArithmeticExpression();
        $this->match(Lexer::T_AND);
        $arithExpr3 = $this->_ArithmeticExpression();

        $betweenExpr = new AST\BetweenExpression($arithExpr1, $arithExpr2, $arithExpr3);
        $betweenExpr->setNot($not);

        return $betweenExpr;
    }

1662 1663 1664
    /**
     * ArithmeticPrimary ::= StateFieldPathExpression | Literal | "(" SimpleArithmeticExpression ")" | Function | AggregateExpression
     */
romanb's avatar
romanb committed
1665
    public function _ArithmeticPrimary()
1666
    {
1667
        if ($this->_lexer->lookahead['value'] === '(') {
1668 1669 1670 1671
            $this->match('(');
            $expr = $this->_SimpleArithmeticExpression();
            $this->match(')');
            return $expr;
1672
        }
romanb's avatar
romanb committed
1673

1674
        switch ($this->_lexer->lookahead['type']) {
romanb's avatar
romanb committed
1675
            case Lexer::T_IDENTIFIER:
1676 1677
                $peek = $this->_lexer->glimpse();
                if ($peek['value'] == '(') {
1678
                    return $this->_FunctionsReturningNumerics();
1679
                }
1680
                return $this->_StateFieldPathExpression();
romanb's avatar
romanb committed
1681
            case Lexer::T_INPUT_PARAMETER:
1682 1683
                $this->match($this->_lexer->lookahead['value']);
                return new AST\InputParameter($this->_lexer->token['value']);
romanb's avatar
romanb committed
1684 1685 1686
            case Lexer::T_STRING:
            case Lexer::T_INTEGER:
            case Lexer::T_FLOAT:
1687 1688
                $this->match($this->_lexer->lookahead['value']);
                return $this->_lexer->token['value'];
1689
            default:
romanb's avatar
romanb committed
1690 1691 1692 1693 1694 1695 1696 1697 1698
                $peek = $this->_lexer->glimpse();
                if ($peek['value'] == '(') {
                    if ($this->_isAggregateFunction($this->_lexer->lookahead['type'])) {
                        return $this->_AggregateExpression();
                    }
                    return $this->_FunctionsReturningStrings();
                } else {
                    $this->syntaxError();
                }
1699
        }
1700
        throw DoctrineException::updateMe("Not yet implemented2.");
1701
        //TODO...
1702 1703
    }

1704 1705 1706 1707 1708 1709 1710 1711
    /**
     * PortableFunctionsReturningStrings ::=
     *   "CONCAT" "(" StringPrimary "," StringPrimary ")" |
     *   "SUBSTRING" "(" StringPrimary "," SimpleArithmeticExpression "," SimpleArithmeticExpression ")" |
     *   "TRIM" "(" [["LEADING" | "TRAILING" | "BOTH"] [char] "FROM"] StringPrimary ")" |
     *   "LOWER" "(" StringPrimary ")" |
     *   "UPPER" "(" StringPrimary ")"
     */
romanb's avatar
romanb committed
1712
    public function _FunctionsReturningStrings()
1713
    {
1714 1715 1716 1717 1718 1719
        $funcNameLower = strtolower($this->_lexer->lookahead['value']);
        $funcClass = self::$_STRING_FUNCTIONS[$funcNameLower];
        $function = new $funcClass($funcNameLower);
        $function->parse($this);
        return $function;
    }
1720

1721 1722 1723 1724 1725 1726 1727 1728 1729
    /**
     * PortableFunctionsReturningNumerics ::=
     *      "LENGTH" "(" StringPrimary ")" |
     *      "LOCATE" "(" StringPrimary "," StringPrimary ["," SimpleArithmeticExpression]")" |
     *      "ABS" "(" SimpleArithmeticExpression ")" |
     *      "SQRT" "(" SimpleArithmeticExpression ")" |
     *      "MOD" "(" SimpleArithmeticExpression "," SimpleArithmeticExpression ")" |
     *      "SIZE" "(" CollectionValuedPathExpression ")"
     */
romanb's avatar
romanb committed
1730
    public function _FunctionsReturningNumerics()
1731 1732 1733 1734 1735 1736 1737
    {
        $funcNameLower = strtolower($this->_lexer->lookahead['value']);
        $funcClass = self::$_NUMERIC_FUNCTIONS[$funcNameLower];
        $function = new $funcClass($funcNameLower);
        $function->parse($this);
        return $function;
    }
1738

1739 1740 1741 1742 1743 1744 1745 1746 1747 1748
    /**
     * PortableFunctionsReturningDateTime ::= "CURRENT_DATE" | "CURRENT_TIME" | "CURRENT_TIMESTAMP"
     */
    public function _FunctionsReturningDatetime()
    {
        $funcNameLower = strtolower($this->_lexer->lookahead['value']);
        $funcClass = self::$_DATETIME_FUNCTIONS[$funcNameLower];
        $function = new $funcClass($funcNameLower);
        $function->parse($this);
        return $function;
1749 1750
    }

1751 1752 1753
    /**
     * Checks whether the given token type indicates an aggregate function.
     */
romanb's avatar
romanb committed
1754
    public function _isAggregateFunction($tokenType)
1755
    {
1756 1757 1758
        return $tokenType == Lexer::T_AVG || $tokenType == Lexer::T_MIN ||
                $tokenType == Lexer::T_MAX || $tokenType == Lexer::T_SUM ||
                $tokenType == Lexer::T_COUNT;
1759 1760
    }

1761 1762 1763
    /**
     * ComparisonOperator ::= "=" | "<" | "<=" | "<>" | ">" | ">=" | "!="
     */
romanb's avatar
romanb committed
1764
    public function _ComparisonOperator()
1765
    {
1766
        switch ($this->_lexer->lookahead['value']) {
1767 1768 1769 1770 1771 1772
            case '=':
                $this->match('=');
                return '=';
            case '<':
                $this->match('<');
                $operator = '<';
1773
                if ($this->_lexer->isNextToken('=')) {
1774 1775
                    $this->match('=');
                    $operator .= '=';
1776
                } else if ($this->_lexer->isNextToken('>')) {
1777 1778 1779 1780 1781 1782 1783
                    $this->match('>');
                    $operator .= '>';
                }
                return $operator;
            case '>':
                $this->match('>');
                $operator = '>';
1784
                if ($this->_lexer->isNextToken('=')) {
1785 1786 1787 1788 1789 1790 1791 1792 1793
                    $this->match('=');
                    $operator .= '=';
                }
                return $operator;
            case '!':
                $this->match('!');
                $this->match('=');
                return '<>';
            default:
1794
                $this->syntaxError('=, <, <=, <>, >, >=, !=');
1795 1796
                break;
        }
1797
    }
1798 1799

    /**
1800
     * LikeExpression ::= StringExpression ["NOT"] "LIKE" (string | input_parameter) ["ESCAPE" char]
1801
     */
romanb's avatar
romanb committed
1802
    public function _LikeExpression()
1803 1804 1805
    {
        $stringExpr = $this->_StringExpression();
        $isNot = false;
romanb's avatar
romanb committed
1806 1807
        if ($this->_lexer->lookahead['type'] === Lexer::T_NOT) {
            $this->match(Lexer::T_NOT);
1808 1809
            $isNot = true;
        }
romanb's avatar
romanb committed
1810
        $this->match(Lexer::T_LIKE);
1811 1812 1813 1814 1815 1816 1817
        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'];
        }
1818
        $escapeChar = null;
romanb's avatar
romanb committed
1819 1820
        if ($this->_lexer->lookahead['type'] === Lexer::T_ESCAPE) {
            $this->match(Lexer::T_ESCAPE);
romanb's avatar
romanb committed
1821 1822
            $this->match(Lexer::T_STRING);
            $escapeChar = $this->_lexer->token['value'];
1823
        }
1824
        return new AST\LikeExpression($stringExpr, $stringPattern, $isNot, $escapeChar);
1825 1826 1827 1828 1829
    }

    /**
     * StringExpression ::= StringPrimary | "(" Subselect ")"
     */
romanb's avatar
romanb committed
1830
    public function _StringExpression()
1831
    {
1832 1833
        if ($this->_lexer->lookahead['value'] === '(') {
            $peek = $this->_lexer->glimpse();
romanb's avatar
romanb committed
1834
            if ($peek['type'] === Lexer::T_SELECT) {
1835 1836 1837 1838
                $this->match('(');
                $expr = $this->_Subselect();
                $this->match(')');
                return $expr;
1839 1840 1841 1842 1843 1844 1845 1846
            }
        }
        return $this->_StringPrimary();
    }

    /**
     * StringPrimary ::= StateFieldPathExpression | string | InputParameter | FunctionsReturningStrings | AggregateExpression
     */
1847
    public function _StringPrimary()
1848
    {
romanb's avatar
romanb committed
1849
        if ($this->_lexer->lookahead['type'] === Lexer::T_IDENTIFIER) {
1850
            $peek = $this->_lexer->glimpse();
1851 1852 1853
            if ($peek['value'] == '.') {
                return $this->_StateFieldPathExpression();
            } else if ($peek['value'] == '(') {
1854
                return $this->_FunctionsReturningStrings();
1855 1856 1857
            } else {
                $this->syntaxError("'.' or '('");
            }
romanb's avatar
romanb committed
1858
        } else if ($this->_lexer->lookahead['type'] === Lexer::T_STRING) {
romanb's avatar
romanb committed
1859 1860
            $this->match(Lexer::T_STRING);
            return $this->_lexer->token['value'];
romanb's avatar
romanb committed
1861
        } else if ($this->_lexer->lookahead['type'] === Lexer::T_INPUT_PARAMETER) {
romanb's avatar
romanb committed
1862 1863
            $this->match(Lexer::T_INPUT_PARAMETER);
            return new AST\InputParameter($this->_lexer->token['value']);
1864 1865
        } else if ($this->_isAggregateFunction($this->_lexer->lookahead['type'])) {
            return $this->_AggregateExpression();
1866 1867 1868 1869
        } else {
            $this->syntaxError('StateFieldPathExpression | string | InputParameter | FunctionsReturningStrings | AggregateExpression');
        }
    }
1870

romanb's avatar
romanb committed
1871 1872 1873 1874 1875 1876
    /**
     * Registers a custom function that returns strings.
     *
     * @param string $name The function name.
     * @param string $class The class name of the function implementation.
     */
1877 1878 1879 1880 1881
    public static function registerStringFunction($name, $class)
    {
        self::$_STRING_FUNCTIONS[$name] = $class;
    }

romanb's avatar
romanb committed
1882 1883 1884 1885 1886 1887
    /**
     * Registers a custom function that returns numerics.
     *
     * @param string $name The function name.
     * @param string $class The class name of the function implementation.
     */
1888 1889 1890 1891 1892
    public static function registerNumericFunction($name, $class)
    {
        self::$_NUMERIC_FUNCTIONS[$name] = $class;
    }

romanb's avatar
romanb committed
1893 1894 1895 1896 1897 1898
    /**
     * Registers a custom function that returns date/time values.
     *
     * @param string $name The function name.
     * @param string $class The class name of the function implementation.
     */
1899 1900 1901 1902
    public static function registerDatetimeFunction($name, $class)
    {
        self::$_DATETIME_FUNCTIONS[$name] = $class;
    }
1903
}