Disappearing comments

Author: pmjonesCreated Sep 28, 2023Updated Feb 5, 2025

BLUF: The 4.x parser appears to lose comments in some cases; while their removal has no effect on the logical operation of code rebuilt from the AST, their disappearance is surprising when using something like PHP-Styler.


Given code like the following ...

php
<?php
switch ($foo) {
    /* this comment disappears */
}

function bar(/* this comment disappears */)
{
}

... the comments noted do not appear at all in the array of parsed nodes:

array(2) {
  [0]=>
  object(PhpParser\Node\Stmt\Switch_)#641 (3) {
    ["attributes":protected]=>
    array(2) {
      ["startLine"]=>
      int(2)
      ["endLine"]=>
      int(4)
    }
    ["cond"]=>
    object(PhpParser\Node\Expr\Variable)#639 (2) {
      ["attributes":protected]=>
      array(2) {
        ["startLine"]=>
        int(2)
        ["endLine"]=>
        int(2)
      }
      ["name"]=>
      string(3) "foo"
    }
    ["cases"]=>
    array(0) {
    }
  }
  [1]=>
  object(PhpParser\Node\Stmt\Function_)#640 (8) {
    ["attributes":protected]=>
    array(2) {
      ["startLine"]=>
      int(6)
      ["endLine"]=>
      int(8)
    }
    ["byRef"]=>
    bool(false)
    ["name"]=>
    object(PhpParser\Node\Identifier)#642 (2) {
      ["attributes":protected]=>
      array(2) {
        ["startLine"]=>
        int(6)
        ["endLine"]=>
        int(6)
      }
      ["name"]=>
      string(3) "bar"
    }
    ["params"]=>
    array(0) {
    }
    ["returnType"]=>
    NULL
    ["stmts"]=>
    array(0) {
    }
    ["attrGroups"]=>
    array(0) {
    }
    ["namespacedName"]=>
    NULL
  }
}

Is it possible to retain them somehow, so that PHP-Styler can reproduce them faithfully when pretty-printing the AST?