nikic / nikic/PHP-Parser

Inline comment before semicolon not in AST

Open
#802 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
PHP
Stars
17.5k
Forks
1.1k
PR merge metrics
No merged PRs in 30d

Description

Steps to reproduce:

Create a simple PHP file like this:

<?php
echo 'foo' /* bar */ ;

The comment between the end of the function and the ; is crucial. It's also reproducible with code like $x = str_contains('abcde', 'a') /* test */; or $x = 7 /* seven */;.

Parse it:

$parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7);
$ast = $parser->parse(file_get_contents('sample.php');
print_r($ast);

Actual Result

array(1) {
  [0]=>
  object(PhpParser\Node\Stmt\Echo_)#9202 (2) {
    ["exprs"]=>
    array(1) {
      [0]=>
      object(PhpParser\Node\Scalar\String_)#9206 (2) {
        ["value"]=>
        string(3) "foo"
        ["attributes":protected]=>
        array(3) {
          ["startLine"]=>
          int(2)
          ["endLine"]=>
          int(2)
          ["kind"]=>
          int(1)
        }
      }
    }
    ["attributes":protected]=>
    array(2) {
      ["startLine"]=>
      int(2)
      ["endLine"]=>
      int(2)
    }
  }
}

Expected Result

I'd like to see to "bar" comment to show up somewhere in the AST. As an attribute of the Stmt\Echo_ most likely.

Use Case

We use this in our internal translation system to annotate calls to our translation engine.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the issue with sample.php using the ParserFactory and parse() example from the report, then inspect the resulting AST for the comment between the expression and semicolon. The change is complete when that comment is represented in the AST, such as on the Echo_ statement, for all shown examples.

Written by the indexing model from the issue text.

Assessment

Tech stack
php
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.