feat: add rule to prevent comments after attributes
Hello!
Motivation
I've had issues with developers adding the doc comment after attributes:
#[Foo]
/** @param array<int, string> $foo */
function bad(array $foo): void {...}
// should be
/** @param array<int, string> $foo */
#[Foo]
function good(array $foo): void {...}
The former is actually a bug---the doc comment is invisible to PHP-Parser and is not used: https://phpstan.org/r/987e775c-225b-4248-a772-e97367baf952
So I decided to try and create a rule to prevent these situations.
Implementation
Given that the comment is completely invisible to PHP-Parser, this becomes more difficult than simply comparing the starting line of the comment to the ending line of the attribute group.
Basically what I'm trying to do is find "holes" by comparing the last line of the last attribute group to the starting line of the next identifier (class, property, enum, etc. name). If there's a "hole" (the identifier does not start on the same or next line) then I report the error.
I'm open to suggestions for better class name / error identifier / error message.
CC: @staabm, would you mind taking a look at this?
Thanks!
This bug has an issue: https://github.com/phpstan/phpstan/issues/4633
I don't think we should add rules about bugs, we shoud fix those bugs.
I think for a long time this one could be fixed with an AST visitor.
Similarly to the visitor which adds linesToIgnore, this one could look at lexer tokens and add comments between attributes and code to Node comments.
Even if this "bug" is fixed by being able to parse the comments I would still want a rule to enforce that comments come before attributes (but that can be more of a strict/opinionated rule at that point). To borrow an analogy from chemistry, the attribute is an actual language construct and should bind more closely with the node than a doc comment.