Skip to content

Null-safe operator followed by a property named class results in a syntax error #1003

@shufo

Description

@shufo

Context

Problem

When property named class is exists after null safe operator, it will throws an exception.

const target = `
  $record->learner->currentEnrollment?->class->grade->code
`;
// Retrieve the AST from the specified source
const eval = parser.parseEval(target);


// then it will throws an exception
/home/shuhei/develop/php-parser/src/parser.js:357
    throw err;
    ^

SyntaxError: Parse Error : syntax error, unexpected 'class' (T_CLASS) on line 2
    at Parser.raiseError (/home/shuhei/develop/php-parser/src/parser.js:349:17)
    at Parser.error (/home/shuhei/develop/php-parser/src/parser.js:397:15)
    at Parser.read_what (/home/shuhei/develop/php-parser/src/parser/variable.js:161:14)
    at Parser.recursive_variable_chain_scan (/home/shuhei/develop/php-parser/src/parser/variable.js:235:38)
    at Parser.read_variable (/home/shuhei/develop/php-parser/src/parser/variable.js:85:17)
    at Parser.read_expr_item (/home/shuhei/develop/php-parser/src/parser/expr.js:455:19)
    at Parser.read_expr (/home/shuhei/develop/php-parser/src/parser/expr.js:18:19)
    at Parser.read_statement (/home/shuhei/develop/php-parser/src/parser/statement.js:416:27)
    at Parser.read_top_statement (/home/shuhei/develop/php-parser/src/parser/statement.js:77:21)
    at Parser.read_start (/home/shuhei/develop/php-parser/src/parser/main.js:18:19) {
  lineNumber: 2,
  fileName: 'eval',
  columnNumber: 40
}

Maybe it is recognized as reserved word.

It only happens when you put class property after null safe operator.
So class property with normal property access is ok.

// This works
$record->learner->currentEnrollment->class->grade?->code;

When I check syntax on php directly, it's ok.

$  php -v
PHP 8.1.2 (cli) (built: Aug 15 2022 12:24:10) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.1.2, Copyright (c) Zend Technologies
    with Zend OPcache v8.1.2, Copyright (c), by Zend Technologies

$ vim test.php
<?php
echo $record->learner->currentEnrollment?->class->grade->code;
$  php --syntax-check test.php
No syntax errors detected in test.php

Sorry for no PR, I tried fix this but I don't know the right solution.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions