Skip to content

fix: comments inside the body of an attributed function crash or move - #2517

Open
mreiden wants to merge 1 commit into
prettier:mainfrom
mreiden:fix/attributed-function-comments
Open

mreiden wants to merge 1 commit into
prettier:mainfrom
mreiden:fix/attributed-function-comments

Conversation

@mreiden

@mreiden mreiden commented Sep 22, 2026

Copy link
Copy Markdown
Contributor

Problem

On main (not in 0.25.0), any comment inside the body of a function or method that carries an attribute breaks formatting:

class A
{
    #[Override]
    public function jsonSerialize(): array
    {
        // Set address details
        $vals = [];
        return $vals;
    }
}
TypeError: Cannot read properties of undefined (reading 'kind')
    at handleFunctionParameter (src/comments.mjs:596)

Without a return type it does not crash; the comments are instead hoisted out of the body and printed between the signature and {.

Cause

getCommentChildNodes() returns an explicit child list for attributed functions/methods (attrGroups, arguments, type) and omits name and body. Prettier therefore never descends into the body: a body comment gets precedingNode = type, followingNode = undefined, and handleFunctionParameter dereferences the missing following node.

Fix

Return every child in source order. Including name matters too: with only body added, a comment trailing the attribute (#[T] // comment) sees the body as its following node and handleLastFunctionArgComments pushes it into the body, changing the existing tests/attributes snapshot. With name present that comment stays on the attribute, so existing snapshots are unchanged.

Tests

tests/attributes/attributes-body-comments.php: comments at the start of, and between statements in, an attributed method with and without a return type, plus a comment trailing the attribute. Full suite passes with AST_COMPARE=1.

🤖 Generated with Claude Code

`getCommentChildNodes()` returns an explicit child list for functions
and methods that carry attributes, but it left out `name` and `body`.
Any comment inside the body of such a function was then resolved
against the return type instead of the body: with a return type it
crashed in `handleFunctionParameter` ("Cannot read properties of
undefined (reading 'kind')"), and without one the comment was hoisted
out of the body.

Return every child in source order. Including `name` keeps a comment
trailing the attribute (`#[T] // comment`) attached to the attribute
rather than being pushed into the body by
`handleLastFunctionArgComments`, so existing snapshots are unchanged.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant