Skip to content
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
2 changes: 2 additions & 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 Expand Up @@ -226,6 +227,7 @@ parameters:
- [parameters, errorFormat]
- [parameters, ignoreErrors]
- [parameters, reportUnmatchedIgnoredErrors]
- [parameters, reportIgnoresWithoutComments]
- [parameters, tipsOfTheDay]
- [parameters, parallel]
- [parameters, internalErrorsCountLimit]
Expand Down
1 change: 1 addition & 0 deletions conf/parametersSchema.neon
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ parametersSchema:
nameScopeMapMemoryCacheCountMax: int()
])
reportUnmatchedIgnoredErrors: bool()
reportIgnoresWithoutComments: bool()
typeAliases: arrayOf(string())
universalObjectCratesClasses: listOf(string())
stubFiles: listOf(string())
Expand Down
70 changes: 61 additions & 9 deletions src/Analyser/AnalyserResultFinalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,19 +28,18 @@ public function __construct(
private LocalIgnoresProcessor $localIgnoresProcessor,
#[AutowiredParameter]
private bool $reportUnmatchedIgnoredErrors,
#[AutowiredParameter]
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->addIgnoresWithoutCommentErrors($this->mergeFilteredPhpErrors($analyserResult)), [], []);
}

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

return $this->addUnmatchedIgnoredErrors(new AnalyserResult(
return $this->addUnmatchedIgnoredErrors($this->addIgnoresWithoutCommentErrors(new AnalyserResult(
unorderedErrors: array_merge($errors, $analyserResult->getFilteredPhpErrors()),
filteredPhpErrors: [],
allPhpErrors: $analyserResult->getAllPhpErrors(),
Expand All @@ -148,7 +147,7 @@ public function finalize(AnalyserResult $analyserResult, bool $onlyFiles, bool $
exportedNodes: $analyserResult->getExportedNodes(),
reachedInternalErrorsCountLimit: $analyserResult->hasReachedInternalErrorsCountLimit(),
peakMemoryUsageBytes: $analyserResult->getPeakMemoryUsageBytes(),
), $collectorErrors, $locallyIgnoredCollectorErrors);
)), $collectorErrors, $locallyIgnoredCollectorErrors);
}

private function mergeFilteredPhpErrors(AnalyserResult $analyserResult): AnalyserResult
Expand Down Expand Up @@ -205,7 +204,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 @@ -237,4 +236,57 @@ private function addUnmatchedIgnoredErrors(
);
}

private function addIgnoresWithoutCommentErrors(AnalyserResult $analyserResult): AnalyserResult
{
if (!$this->reportIgnoresWithoutComments) {
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) {
continue;
}

foreach ($identifiers as $identifier) {
['name' => $name, 'comment' => $comment] = $identifier;
if ($comment !== null) {
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->getUsedTraitDependencies(),
$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 @@ -42,6 +42,7 @@
use const E_WARNING;

/**
* @phpstan-import-type Identifier from FileAnalyserResult
* @phpstan-import-type CollectorData from CollectedData
*/
#[AutowiredService]
Expand Down Expand Up @@ -347,15 +348,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 @@ -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
24 changes: 24 additions & 0 deletions tests/PHPStan/Analyser/AnalyserTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -632,6 +632,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 @@ -741,6 +763,7 @@ private function runAnalyser(
bool $reportUnmatchedIgnoredErrors,
$filePaths,
bool $onlyFiles,
bool $reportIgnoresWithoutComments = false,
): array
{
$analyser = $this->createAnalyser();
Expand Down Expand Up @@ -773,6 +796,7 @@ private function runAnalyser(
),
new LocalIgnoresProcessor(),
$reportUnmatchedIgnoredErrors,
$reportIgnoresWithoutComments,
);
$analyserResult = $finalizer->finalize($analyserResult, $onlyFiles, false)->getAnalyserResult();

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