Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions conf/config.neon
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ parameters:
resolvedPhpDocBlockCacheCountMax: 2048
nameScopeMapMemoryCacheCountMax: 2048
reportUnmatchedIgnoredErrors: true
reportIgnoresWithoutComments: false
typeAliases: []
universalObjectCratesClasses:
- stdClass
Expand Down
1 change: 1 addition & 0 deletions conf/parametersSchema.neon
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ parametersSchema:
nameScopeMapMemoryCacheCountMax: int()
])
reportUnmatchedIgnoredErrors: bool()
reportIgnoresWithoutComments: bool()
typeAliases: arrayOf(string())
universalObjectCratesClasses: listOf(string())
stubFiles: listOf(string())
Expand Down
2 changes: 2 additions & 0 deletions phpstan.neon.dist
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
includes: [ build/phpstan.neon ]
parameters:
reportIgnoresWithoutComments: true
11 changes: 5 additions & 6 deletions src/Analyser/AnalyserResultFinalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,20 +26,19 @@
private RuleErrorTransformer $ruleErrorTransformer,
private ScopeFactory $scopeFactory,
private LocalIgnoresProcessor $localIgnoresProcessor,
#[AutowiredParameter]

Check failure on line 29 in src/Analyser/AnalyserResultFinalizer.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.4, ubuntu-latest)

Property PHPStan\Analyser\AnalyserResultFinalizer::$reportIgnoresWithoutComments is never read, only written.

Check failure on line 29 in src/Analyser/AnalyserResultFinalizer.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.4, windows-latest)

Property PHPStan\Analyser\AnalyserResultFinalizer::$reportIgnoresWithoutComments is never read, only written.
private bool $reportUnmatchedIgnoredErrors,
#[AutowiredParameter]

Check failure on line 31 in src/Analyser/AnalyserResultFinalizer.php

View workflow job for this annotation

GitHub Actions / PHPStan with result cache (8.2)

Property PHPStan\Analyser\AnalyserResultFinalizer::$reportIgnoresWithoutComments is never read, only written.

Check failure on line 31 in src/Analyser/AnalyserResultFinalizer.php

View workflow job for this annotation

GitHub Actions / PHPStan with result cache (8.3)

Property PHPStan\Analyser\AnalyserResultFinalizer::$reportIgnoresWithoutComments is never read, only written.

Check failure on line 31 in src/Analyser/AnalyserResultFinalizer.php

View workflow job for this annotation

GitHub Actions / PHPStan with result cache (8.5)

Property PHPStan\Analyser\AnalyserResultFinalizer::$reportIgnoresWithoutComments is never read, only written.

Check failure on line 31 in src/Analyser/AnalyserResultFinalizer.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.4, ubuntu-latest)

Property PHPStan\Analyser\AnalyserResultFinalizer::$reportIgnoresWithoutComments is never read, only written.

Check failure on line 31 in src/Analyser/AnalyserResultFinalizer.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.3, ubuntu-latest)

Property PHPStan\Analyser\AnalyserResultFinalizer::$reportIgnoresWithoutComments is never read, only written.

Check failure on line 31 in src/Analyser/AnalyserResultFinalizer.php

View workflow job for this annotation

GitHub Actions / PHPStan with result cache (8.4)

Property PHPStan\Analyser\AnalyserResultFinalizer::$reportIgnoresWithoutComments is never read, only written.

Check failure on line 31 in src/Analyser/AnalyserResultFinalizer.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.5, ubuntu-latest)

Property PHPStan\Analyser\AnalyserResultFinalizer::$reportIgnoresWithoutComments is never read, only written.

Check failure on line 31 in src/Analyser/AnalyserResultFinalizer.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.2, ubuntu-latest)

Property PHPStan\Analyser\AnalyserResultFinalizer::$reportIgnoresWithoutComments is never read, only written.

Check failure on line 31 in src/Analyser/AnalyserResultFinalizer.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.0, ubuntu-latest)

Property PHPStan\Analyser\AnalyserResultFinalizer::$reportIgnoresWithoutComments is never read, only written.

Check failure on line 31 in src/Analyser/AnalyserResultFinalizer.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.1, ubuntu-latest)

Property PHPStan\Analyser\AnalyserResultFinalizer::$reportIgnoresWithoutComments is never read, only written.

Check failure on line 31 in src/Analyser/AnalyserResultFinalizer.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.5, windows-latest)

Property PHPStan\Analyser\AnalyserResultFinalizer::$reportIgnoresWithoutComments is never read, only written.

Check failure on line 31 in src/Analyser/AnalyserResultFinalizer.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.4, windows-latest)

Property PHPStan\Analyser\AnalyserResultFinalizer::$reportIgnoresWithoutComments is never read, only written.

Check failure on line 31 in src/Analyser/AnalyserResultFinalizer.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.2, windows-latest)

Property PHPStan\Analyser\AnalyserResultFinalizer::$reportIgnoresWithoutComments is never read, only written.

Check failure on line 31 in src/Analyser/AnalyserResultFinalizer.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.3, windows-latest)

Property PHPStan\Analyser\AnalyserResultFinalizer::$reportIgnoresWithoutComments is never read, only written.

Check failure on line 31 in src/Analyser/AnalyserResultFinalizer.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.1, windows-latest)

Property PHPStan\Analyser\AnalyserResultFinalizer::$reportIgnoresWithoutComments is never read, only written.

Check failure on line 31 in src/Analyser/AnalyserResultFinalizer.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.0, windows-latest)

Property PHPStan\Analyser\AnalyserResultFinalizer::$reportIgnoresWithoutComments is never read, only written.

Check failure on line 31 in src/Analyser/AnalyserResultFinalizer.php

View workflow job for this annotation

GitHub Actions / Mutation Testing (8.3, ubuntu-latest)

Proper

Check failure on line 31 in src/Analyser/AnalyserResultFinalizer.php

View workflow job for this annotation

GitHub Actions / Mutation Testing (8.4, ubuntu-latest)

Proper
private bool $reportIgnoresWithoutComments,
)
{
}

public function finalize(AnalyserResult $analyserResult, bool $onlyFiles, bool $debug): FinalizerResult
{
if (count($analyserResult->getCollectedData()) === 0) {
return $this->addUnmatchedIgnoredErrors($this->mergeFilteredPhpErrors($analyserResult), [], []);
}

$hasCollectedData = count($analyserResult->getCollectedData()) > 0;
$hasInternalErrors = count($analyserResult->getInternalErrors()) > 0 || $analyserResult->hasReachedInternalErrorsCountLimit();
if ($hasInternalErrors) {
if (! $hasCollectedData || $hasInternalErrors) {
return $this->addUnmatchedIgnoredErrors($this->mergeFilteredPhpErrors($analyserResult), [], []);
}

Expand Down Expand Up @@ -205,7 +204,7 @@

foreach ($identifiers as $identifier) {
$errors[] = (new Error(
sprintf('No error with identifier %s is reported on line %d.', $identifier, $line),
sprintf('No error with identifier %s is reported on line %d.', $identifier['name'], $line),
$file,
$line,
false,
Expand Down
26 changes: 26 additions & 0 deletions src/Analyser/FileAnalyser.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ public function __construct(
private IgnoreErrorExtensionProvider $ignoreErrorExtensionProvider,
private RuleErrorTransformer $ruleErrorTransformer,
private LocalIgnoresProcessor $localIgnoresProcessor,
#[AutowiredParameter]
private bool $reportIgnoresWithoutComments = false,
)
{
}
Expand Down Expand Up @@ -129,6 +131,30 @@ public function analyseFile(
$temporaryFileErrors = $nodeCallback->getTemporaryFileErrors();
$processedFiles = $nodeCallback->getProcessedFiles();

if ($this->reportIgnoresWithoutComments) {
foreach ($linesToIgnore[$file] ?? [] as $line => $identifiers) {
if ($identifiers === null) {
continue;
}

foreach ($identifiers as $identifier) {
if ($identifier['comment'] !== null) {
continue;
}

$fileErrors[] = (new Error(
sprintf('Ignore with identifier %s has no comment.', $identifier['name']),
$file,
$line,
false,
$file,
null,
'Explain why this ignore is necessary in parentheses after the identifier.',
))->withIdentifier('ignore.noComment');
}
}
}

$localIgnoresProcessorResult = $this->localIgnoresProcessor->process(
$temporaryFileErrors,
$linesToIgnore,
Expand Down
5 changes: 3 additions & 2 deletions src/Analyser/FileAnalyserCallback.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

/**
* @phpstan-import-type CollectorData from CollectedData
* @phpstan-import-type Identifier from FileAnalyserResult
* @phpstan-import-type LinesToIgnore from FileAnalyserResult
*/
final class FileAnalyserCallback
Expand Down Expand Up @@ -231,15 +232,15 @@ public function __invoke(Node $node, Scope $scope): void

/**
* @param Node[] $nodes
* @return array<int, non-empty-list<string>|null>
* @return array<int, non-empty-list<Identifier>|null>
*/
private function getLinesToIgnoreFromTokens(array $nodes): array
{
if (!isset($nodes[0])) {
return [];
}

/** @var array<int, non-empty-list<string>|null> */
/** @var array<int, non-empty-list<Identifier>|null> */
return $nodes[0]->getAttribute('linesToIgnore', []);
}

Expand Down
3 changes: 2 additions & 1 deletion src/Analyser/FileAnalyserResult.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
use PHPStan\Dependency\RootExportedNode;

/**
* @phpstan-type LinesToIgnore = array<string, array<int, non-empty-list<string>|null>>
* @phpstan-type Identifier = array{name: string, comment: string|null}
* @phpstan-type LinesToIgnore = array<string, array<int, non-empty-list<Identifier>|null>>
* @phpstan-import-type CollectorData from CollectedData
*/
final class FileAnalyserResult
Expand Down
4 changes: 2 additions & 2 deletions src/Analyser/LocalIgnoresProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public function process(
}

foreach ($identifiers as $i => $ignoredIdentifier) {
if ($ignoredIdentifier !== $tmpFileError->getIdentifier()) {
if ($ignoredIdentifier['name'] !== $tmpFileError->getIdentifier()) {
continue;
}

Expand All @@ -68,7 +68,7 @@ public function process(
$unmatchedIgnoredIdentifiers = $unmatchedLineIgnores[$tmpFileError->getFile()][$line];
if (is_array($unmatchedIgnoredIdentifiers)) {
foreach ($unmatchedIgnoredIdentifiers as $j => $unmatchedIgnoredIdentifier) {
if ($ignoredIdentifier !== $unmatchedIgnoredIdentifier) {
if ($ignoredIdentifier['name'] !== $unmatchedIgnoredIdentifier['name']) {
continue;
}

Expand Down
2 changes: 1 addition & 1 deletion src/Command/FixerWorkerCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ function (array $errors, array $locallyIgnoredErrors, array $analysedFiles) use
if ($error->getIdentifier() === null) {
continue;
}
if (!in_array($error->getIdentifier(), ['ignore.count', 'ignore.unmatched', 'ignore.unmatchedLine', 'ignore.unmatchedIdentifier'], true)) {
if (!in_array($error->getIdentifier(), ['ignore.count', 'ignore.unmatched', 'ignore.unmatchedLine', 'ignore.unmatchedIdentifier', 'ignore.noComment'], true)) {
continue;
}
$ignoreFileErrors[] = $error;
Expand Down
41 changes: 27 additions & 14 deletions src/Parser/RichParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@
use PhpParser\NodeTraverser;
use PhpParser\NodeVisitor\NameResolver;
use PhpParser\Token;
use PHPStan\Analyser\FileAnalyserResult;
use PHPStan\Analyser\Ignore\IgnoreLexer;
use PHPStan\Analyser\Ignore\IgnoreParseException;
use PHPStan\DependencyInjection\Container;
use PHPStan\File\FileReader;
use PHPStan\ShouldNotHappenException;
use function array_filter;
use function array_key_last;
use function array_map;
use function count;
use function implode;
Expand All @@ -30,6 +32,9 @@
use const T_DOC_COMMENT;
use const T_WHITESPACE;

/**
* @phpstan-import-type Identifier from FileAnalyserResult
*/
final class RichParser implements Parser
{

Expand Down Expand Up @@ -120,7 +125,7 @@ public function parseString(string $sourceCode): array

/**
* @param Token[] $tokens
* @return array{lines: array<int, non-empty-list<string>|null>, errors: array<int, non-empty-list<string>>}
* @return array{lines: array<int, non-empty-list<Identifier>|null>, errors: array<int, non-empty-list<string>>}
*/
private function getLinesToIgnore(array $tokens): array
{
Expand Down Expand Up @@ -277,33 +282,29 @@ private function getLinesToIgnoreForTokenByIgnoreComment(
}

/**
* @return non-empty-list<string>
* @return non-empty-list<Identifier>
* @throws IgnoreParseException
*/
private function parseIdentifiers(string $text, int $ignorePos): array
{
$text = substr($text, $ignorePos + strlen('@phpstan-ignore'));
$originalTokens = $this->ignoreLexer->tokenize($text);
$tokens = [];

foreach ($originalTokens as $originalToken) {
if ($originalToken[IgnoreLexer::TYPE_OFFSET] === IgnoreLexer::TOKEN_WHITESPACE) {
continue;
}
$tokens[] = $originalToken;
}
$tokens = $this->ignoreLexer->tokenize($text);

$c = count($tokens);

$identifiers = [];
$comment = null;
$openParenthesisCount = 0;
$expected = [IgnoreLexer::TOKEN_IDENTIFIER];
$lastTokenTypeLabel = '@phpstan-ignore';

for ($i = 0; $i < $c; $i++) {
$lastTokenTypeLabel = isset($tokenType) ? $this->ignoreLexer->getLabel($tokenType) : '@phpstan-ignore';
if (isset($tokenType) && $tokenType !== IgnoreLexer::TOKEN_WHITESPACE) {
$lastTokenTypeLabel = $this->ignoreLexer->getLabel($tokenType);
}
[IgnoreLexer::VALUE_OFFSET => $content, IgnoreLexer::TYPE_OFFSET => $tokenType, IgnoreLexer::LINE_OFFSET => $tokenLine] = $tokens[$i];

if ($expected !== null && !in_array($tokenType, $expected, true)) {
if ($expected !== null && !in_array($tokenType, [...$expected, IgnoreLexer::TOKEN_WHITESPACE], true)) {
$tokenTypeLabel = $this->ignoreLexer->getLabel($tokenType);
$otherTokenContent = $tokenType === IgnoreLexer::TOKEN_OTHER ? sprintf(" '%s'", $content) : '';
$expectedLabels = implode(' or ', array_map(fn ($token) => $this->ignoreLexer->getLabel($token), $expected));
Expand All @@ -312,6 +313,9 @@ private function parseIdentifiers(string $text, int $ignorePos): array
}

if ($tokenType === IgnoreLexer::TOKEN_OPEN_PARENTHESIS) {
if ($openParenthesisCount > 0) {
$comment .= $content;
}
$openParenthesisCount++;
$expected = null;
continue;
Expand All @@ -320,17 +324,25 @@ private function parseIdentifiers(string $text, int $ignorePos): array
if ($tokenType === IgnoreLexer::TOKEN_CLOSE_PARENTHESIS) {
$openParenthesisCount--;
if ($openParenthesisCount === 0) {
$key = array_key_last($identifiers);
if ($key !== null) {
$identifiers[$key]['comment'] = $comment;
$comment = null;
}
$expected = [IgnoreLexer::TOKEN_COMMA, IgnoreLexer::TOKEN_END];
} else {
$comment .= $content;
}
continue;
}

if ($openParenthesisCount > 0) {
$comment .= $content;
continue; // waiting for comment end
}

if ($tokenType === IgnoreLexer::TOKEN_IDENTIFIER) {
$identifiers[] = $content;
$identifiers[] = ['name' => $content, 'comment' => null];
$expected = [IgnoreLexer::TOKEN_COMMA, IgnoreLexer::TOKEN_END, IgnoreLexer::TOKEN_OPEN_PARENTHESIS];
continue;
}
Expand All @@ -349,6 +361,7 @@ private function parseIdentifiers(string $text, int $ignorePos): array
throw new IgnoreParseException('Missing identifier', 1);
}

/** @phpstan-ignore return.type (return type is correct, not sure why it's being changed from array shape to key-value shape) */
return $identifiers;
}

Expand Down
1 change: 1 addition & 0 deletions src/Testing/RuleTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,7 @@ private function gatherAnalyserErrorsWithDelayedErrors(array $files): array
self::createScopeFactory($reflectionProvider, self::getContainer()->getService('typeSpecifier')),
new LocalIgnoresProcessor(),
true,
false,
);

return [
Expand Down
5 changes: 5 additions & 0 deletions src/dumpType.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,8 @@ function dumpPhpDocType($value, ...$values) // phpcs:ignore Squiz.Functions.Glob
{
return null;
}

function test(): string
{
return 1; // @phpstan-ignore return.type
}
29 changes: 27 additions & 2 deletions tests/PHPStan/Analyser/AnalyserTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -638,6 +638,28 @@ public function testIgnoreNextLineUnmatched(): void
}
}

#[DataProvider('dataTrueAndFalse')]
public function testIgnoresWithoutCommentsReported(): void
{
$expects = [
[9, 'variable.undefined'],
[12, 'variable.undefined'],
[12, 'wrong.id'],
[13, 'wrong.id'],
[14, 'variable.undefined'],
];
$result = $this->runAnalyser([], false, [
__DIR__ . '/data/ignore-no-comments.php',
], true, true);
$this->assertCount(5, $result);
foreach ($expects as $i => $expect) {
$this->assertArrayHasKey($i, $result);
$this->assertInstanceOf(Error::class, $result[$i]);
$this->assertStringContainsString(sprintf('Ignore with identifier %s has no comment.', $expect[1]), $result[$i]->getMessage());
$this->assertSame($expect[0], $result[$i]->getLine());
}
}

#[DataProvider('dataTrueAndFalse')]
public function testIgnoreLine(bool $reportUnmatchedIgnoredErrors): void
{
Expand Down Expand Up @@ -747,9 +769,10 @@ private function runAnalyser(
bool $reportUnmatchedIgnoredErrors,
$filePaths,
bool $onlyFiles,
bool $reportIgnoresWithoutComments = false,
): array
{
$analyser = $this->createAnalyser();
$analyser = $this->createAnalyser($reportIgnoresWithoutComments);

if (is_string($filePaths)) {
$filePaths = [$filePaths];
Expand Down Expand Up @@ -779,6 +802,7 @@ private function runAnalyser(
),
new LocalIgnoresProcessor(),
$reportUnmatchedIgnoredErrors,
$reportIgnoresWithoutComments,
);
$analyserResult = $finalizer->finalize($analyserResult, $onlyFiles, false)->getAnalyserResult();

Expand All @@ -795,7 +819,7 @@ private function runAnalyser(
);
}

private function createAnalyser(): Analyser
private function createAnalyser(bool $reportIgnoresWithoutComments = false): Analyser
{
$ruleRegistry = new DirectRuleRegistry([
new AlwaysFailRule(),
Expand Down Expand Up @@ -850,6 +874,7 @@ private function createAnalyser(): Analyser
new IgnoreErrorExtensionProvider(new NetteContainer(new Container([]))),
$container->getByType(RuleErrorTransformer::class),
new LocalIgnoresProcessor(),
$reportIgnoresWithoutComments,
);

return new Analyser(
Expand Down
18 changes: 18 additions & 0 deletions tests/PHPStan/Analyser/data/ignore-no-comments.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

namespace IgnoreNoComments;

class Foo
{
public function doFoo(): void
{
echo $foo; // @phpstan-ignore variable.undefined
echo $foo; // @phpstan-ignore wrong.id (comment)

echo $foo, $bar; // @phpstan-ignore variable.undefined, wrong.id
echo $foo, $bar; // @phpstan-ignore variable.undefined (comment), wrong.id
echo $foo, $bar; // @phpstan-ignore variable.undefined, wrong.id (comment)
echo $foo, $bar; // @phpstan-ignore variable.undefined (comment), wrong.id (comment)
}

}
Loading
Loading