glayzzle / php-parser

:herb: NodeJS PHP Parser - extract AST or tokens
https://php-parser.glayzzle.com/
BSD 3-Clause "New" or "Revised" License
528 stars 70 forks source link

Fails to parse classes with typed constants #1133

Open davidrans opened 4 months ago

davidrans commented 4 months ago

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/php-parser@3.1.5/node_modules/php-parser/src/parser.js:349:17)
    at Parser.error (/home/user/Code/node_modules/.pnpm/php-parser@3.1.5/node_modules/php-parser/src/parser.js:397:15)
    at Parser.expect (/home/user/Code/node_modules/.pnpm/php-parser@3.1.5/node_modules/php-parser/src/parser.js:577:10)
    at Parser.read_constant_declaration (/home/user/Code/node_modules/.pnpm/php-parser@3.1.5/node_modules/php-parser/src/parser/class.js:261:18)
    at Parser.read_list (/home/user/Code/node_modules/.pnpm/php-parser@3.1.5/node_modules/php-parser/src/parser/utils.js:76:33)
    at Parser.read_constant_list (/home/user/Code/node_modules/.pnpm/php-parser@3.1.5/node_modules/php-parser/src/parser/class.js:237:24)
    at Parser.read_class_body (/home/user/Code/node_modules/.pnpm/php-parser@3.1.5/node_modules/php-parser/src/parser/class.js:117:32)
    at Parser.read_class_declaration_statement (/home/user/Code/node_modules/.pnpm/php-parser@3.1.5/node_modules/php-parser/src/parser/class.js:32:30)
    at Parser.read_top_statement (/home/user/Code/node_modules/.pnpm/php-parser@3.1.5/node_modules/php-parser/src/parser/statement.js:52:21)
    at Parser.read_start (/home/user/Code/node_modules/.pnpm/php-parser@3.1.5/node_modules/php-parser/src/parser/main.js:18:19) {
  lineNumber: 4,
  fileName: 'eval',
  columnNumber: 21
}
Kenneth-Sills commented 2 months ago

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.

cseufert commented 2 months ago

PR would be great