Skip to content

feat: add options to report ignores without identifiers or comments #3976

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: 2.1.x
Choose a base branch
from
Open
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
6 changes: 6 additions & 0 deletions conf/config.neon
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,8 @@ parameters:
cache:
nodesByStringCountMax: 256
reportUnmatchedIgnoredErrors: true
reportIgnoresWithoutIdentifiers: false
reportIgnoresWithoutComments: false
typeAliases: []
universalObjectCratesClasses:
- stdClass
Expand Down Expand Up @@ -198,6 +200,8 @@ parameters:
- [parameters, errorFormat]
- [parameters, ignoreErrors]
- [parameters, reportUnmatchedIgnoredErrors]
- [parameters, reportIgnoresWithoutIdentifiers]
- [parameters, reportIgnoresWithoutComments]
- [parameters, tipsOfTheDay]
- [parameters, parallel]
- [parameters, internalErrorsCountLimit]
Expand Down Expand Up @@ -461,6 +465,8 @@ services:
class: PHPStan\Analyser\AnalyserResultFinalizer
arguments:
reportUnmatchedIgnoredErrors: %reportUnmatchedIgnoredErrors%
reportIgnoresWithoutIdentifiers: %reportIgnoresWithoutIdentifiers%
reportIgnoresWithoutComments: %reportIgnoresWithoutComments%

-
class: PHPStan\Analyser\FileAnalyser
Expand Down
2 changes: 2 additions & 0 deletions conf/parametersSchema.neon
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,8 @@ parametersSchema:
nodesByStringCountMax: int()
])
reportUnmatchedIgnoredErrors: bool()
reportIgnoresWithoutIdentifiers: bool()
reportIgnoresWithoutComments: bool()
typeAliases: arrayOf(string())
universalObjectCratesClasses: listOf(string())
stubFiles: listOf(string())
Expand Down
79 changes: 70 additions & 9 deletions src/Analyser/AnalyserResultFinalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,19 +24,18 @@ public function __construct(
private ScopeFactory $scopeFactory,
private LocalIgnoresProcessor $localIgnoresProcessor,
private bool $reportUnmatchedIgnoredErrors,
private bool $reportIgnoresWithoutIdentifiers,
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) {
return $this->addUnmatchedIgnoredErrors($this->mergeFilteredPhpErrors($analyserResult), [], []);
if (! $hasCollectedData || $hasInternalErrors) {
return $this->addUnmatchedIgnoredErrors($this->addIgnoresWithoutCommentsOrIdentifiersErrors($this->mergeFilteredPhpErrors($analyserResult)), [], []);
}

$nodeType = CollectedDataNode::class;
Expand Down Expand Up @@ -130,7 +129,7 @@ public function finalize(AnalyserResult $analyserResult, bool $onlyFiles, bool $
$allUnmatchedLineIgnores[$file] = $localIgnoresProcessorResult->getUnmatchedLineIgnores();
}

return $this->addUnmatchedIgnoredErrors(new AnalyserResult(
return $this->addUnmatchedIgnoredErrors($this->addIgnoresWithoutCommentsOrIdentifiersErrors(new AnalyserResult(
array_merge($errors, $analyserResult->getFilteredPhpErrors()),
[],
$analyserResult->getAllPhpErrors(),
Expand All @@ -143,7 +142,7 @@ public function finalize(AnalyserResult $analyserResult, bool $onlyFiles, bool $
$analyserResult->getExportedNodes(),
$analyserResult->hasReachedInternalErrorsCountLimit(),
$analyserResult->getPeakMemoryUsageBytes(),
), $collectorErrors, $locallyIgnoredCollectorErrors);
)), $collectorErrors, $locallyIgnoredCollectorErrors);
}

private function mergeFilteredPhpErrors(AnalyserResult $analyserResult): AnalyserResult
Expand Down Expand Up @@ -199,7 +198,7 @@ private function addUnmatchedIgnoredErrors(

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 Expand Up @@ -230,4 +229,66 @@ private function addUnmatchedIgnoredErrors(
);
}

private function addIgnoresWithoutCommentsOrIdentifiersErrors(AnalyserResult $analyserResult): AnalyserResult
{
if (!$this->reportIgnoresWithoutComments && !$this->reportIgnoresWithoutIdentifiers) {
return $analyserResult;
}

$errors = $analyserResult->getUnorderedErrors();
foreach ($analyserResult->getLinesToIgnore() as $file => $data) {
foreach ($data as $ignoredFile => $lines) {
if ($ignoredFile !== $file) {
continue;
}

foreach ($lines as $line => $identifiers) {
if ($identifiers === null) {
if (!$this->reportIgnoresWithoutIdentifiers) {
continue;
}
$errors[] = (new Error(
sprintf('Error is ignored with no identifiers on line %d.', $line),
$file,
$line,
false,
$file,
))->withIdentifier('ignore.noIdentifier');
continue;
}

foreach ($identifiers as $identifier) {
['name' => $name, 'comment' => $comment] = $identifier;
if ($comment !== null || !$this->reportIgnoresWithoutComments) {
continue;
}

$errors[] = (new Error(
sprintf('Ignore with identifier %s has no comment.', $name),
$file,
$line,
false,
$file,
))->withIdentifier('ignore.noComment');
}
}
}
}

return new AnalyserResult(
$errors,
$analyserResult->getFilteredPhpErrors(),
$analyserResult->getAllPhpErrors(),
$analyserResult->getLocallyIgnoredErrors(),
$analyserResult->getLinesToIgnore(),
$analyserResult->getUnmatchedLineIgnores(),
$analyserResult->getInternalErrors(),
$analyserResult->getCollectedData(),
$analyserResult->getDependencies(),
$analyserResult->getExportedNodes(),
$analyserResult->hasReachedInternalErrorsCountLimit(),
$analyserResult->getPeakMemoryUsageBytes(),
);
}

}
5 changes: 3 additions & 2 deletions src/Analyser/FileAnalyser.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
use const E_WARNING;

/**
* @phpstan-import-type Identifier from FileAnalyserResult
* @phpstan-import-type CollectorData from CollectedData
*/
final class FileAnalyser
Expand Down Expand Up @@ -306,15 +307,15 @@ public function analyseFile(

/**
* @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 @@ -47,7 +47,7 @@ public function process(
}

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

Expand All @@ -66,7 +66,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 @@ -308,7 +308,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.noIdentifier', 'ignore.noComment'], true)) {
continue;
}
$ignoreFileErrors[] = $error;
Expand Down
43 changes: 28 additions & 15 deletions src/Parser/RichParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,16 @@
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 array_values;
use function count;
use function implode;
use function in_array;
Expand All @@ -30,6 +33,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 @@ -111,7 +117,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 @@ -268,33 +274,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 @@ -303,6 +305,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 @@ -311,17 +316,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 @@ -340,7 +353,7 @@ private function parseIdentifiers(string $text, int $ignorePos): array
throw new IgnoreParseException('Missing identifier', 1);
}

return $identifiers;
return array_values($identifiers);
}

}
2 changes: 2 additions & 0 deletions src/Testing/RuleTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,8 @@ private function gatherAnalyserErrorsWithDelayedErrors(array $files): array
$this->createScopeFactory($reflectionProvider, $this->getTypeSpecifier()),
new LocalIgnoresProcessor(),
true,
false,
false,
);

return [
Expand Down
Loading
Loading