php-parser icon indicating copy to clipboard operation
php-parser copied to clipboard

Fails to parse classes with typed constants

Open davidrans opened this issue 1 year ago • 2 comments

It looks like files that have typed constants are not parseable by the latest version (3.1.5).

Input file:

<?php

class Test {
   private const int MY_CONST = 3;
}

Error:

SyntaxError: Parse Error : syntax error, unexpected 'MY_CONST' (T_STRING), expecting '=' on line 4
    at Parser.raiseError (/home/user/Code/node_modules/.pnpm/[email protected]/node_modules/php-parser/src/parser.js:349:17)
    at Parser.error (/home/user/Code/node_modules/.pnpm/[email protected]/node_modules/php-parser/src/parser.js:397:15)
    at Parser.expect (/home/user/Code/node_modules/.pnpm/[email protected]/node_modules/php-parser/src/parser.js:577:10)
    at Parser.read_constant_declaration (/home/user/Code/node_modules/.pnpm/[email protected]/node_modules/php-parser/src/parser/class.js:261:18)
    at Parser.read_list (/home/user/Code/node_modules/.pnpm/[email protected]/node_modules/php-parser/src/parser/utils.js:76:33)
    at Parser.read_constant_list (/home/user/Code/node_modules/.pnpm/[email protected]/node_modules/php-parser/src/parser/class.js:237:24)
    at Parser.read_class_body (/home/user/Code/node_modules/.pnpm/[email protected]/node_modules/php-parser/src/parser/class.js:117:32)
    at Parser.read_class_declaration_statement (/home/user/Code/node_modules/.pnpm/[email protected]/node_modules/php-parser/src/parser/class.js:32:30)
    at Parser.read_top_statement (/home/user/Code/node_modules/.pnpm/[email protected]/node_modules/php-parser/src/parser/statement.js:52:21)
    at Parser.read_start (/home/user/Code/node_modules/.pnpm/[email protected]/node_modules/php-parser/src/parser/main.js:18:19) {
  lineNumber: 4,
  fileName: 'eval',
  columnNumber: 21
}

davidrans avatar May 09 '24 19:05 davidrans

At a glance, this conditional needs to be updated to support type hint tokens proceeded by a constant list, then read_constant_declaration needs to be updated to use read_optional_type.[^1] Finally, we'll need to throw that information into the ClassConstant constructor.

Traits, interfaces, and enums go through this path, so should be supported implicitly. So as long as there's no complications, that should be all that's necessary.

@czosel Are y'all currently accepting PRs? It's been a bit since an update, so want to confirm before embarking on any work.

[^1]: I'm not too familiar with this library and what it would consider a parser error vs runtime error, but it's worth noting that there are limitations on allowed types.

Kenneth-Sills avatar Jun 24 '24 01:06 Kenneth-Sills

PR would be great

cseufert avatar Jun 24 '24 03:06 cseufert