Skip to content
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

Adds support for fixing missing throws doc block #7994

Merged
merged 4 commits into from Jul 12, 2022
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 19 additions & 0 deletions src/Psalm/Internal/Analyzer/FunctionLikeAnalyzer.php
Expand Up @@ -65,6 +65,8 @@
use function array_merge;
use function array_search;
use function array_values;
use function assert;
use function class_exists;
use function count;
use function end;
use function in_array;
Expand Down Expand Up @@ -706,6 +708,10 @@ public function analyze(
}
}

/**
* @var list<class-string>
*/
$missingThrowsDocblockErrors = [];
foreach ($statements_analyzer->getUncaughtThrows($context) as $possibly_thrown_exception => $codelocations) {
$is_expected = false;

Expand All @@ -719,6 +725,8 @@ public function analyze(
}

if (!$is_expected) {
assert(class_exists($possibly_thrown_exception));
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should i keep this assert or remove it, it makes sense for throws keyword to only contain classes which exist

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ideally this check would not be needed, but that means modifying the return type for the function getUncaughtThrows which would be a bigger change

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please drop it. It's risky because classes could be stubbed or inserted through a Plugin so you can't guarantee they'll exists for Psalm to autoload

$missingThrowsDocblockErrors[] = $possibly_thrown_exception;
foreach ($codelocations as $codelocation) {
// issues are suppressed in ThrowAnalyzer, CallAnalyzer, etc.
IssueBuffer::maybeAdd(
Expand All @@ -732,6 +740,17 @@ public function analyze(
}
}

if ($codebase->alter_code
&& isset($project_analyzer->getIssuesToFix()['MissingThrowsDocblock'])
) {
$manipulator = FunctionDocblockManipulator::getForFunction(
$project_analyzer,
$this->source->getFilePath(),
$this->function
);
$manipulator->addThrowsDocblock($missingThrowsDocblockErrors);
}

if ($codebase->taint_flow_graph
&& $this->function instanceof ClassMethod
&& $cased_method_id
Expand Down
1 change: 1 addition & 0 deletions src/Psalm/Internal/Analyzer/ProjectAnalyzer.php
Expand Up @@ -1322,6 +1322,7 @@ public function setIssuesToFix(array $issues): void

$supported_issues_to_fix[] = 'MissingImmutableAnnotation';
$supported_issues_to_fix[] = 'MissingPureAnnotation';
$supported_issues_to_fix[] = 'MissingThrowsDocblock';

$unsupportedIssues = array_diff(array_keys($issues), $supported_issues_to_fix);

Expand Down
Expand Up @@ -14,7 +14,9 @@
use Psalm\Internal\Analyzer\ProjectAnalyzer;
use Psalm\Internal\Scanner\ParsedDocblock;

use function array_key_exists;
use function array_merge;
use function array_reduce;
use function count;
use function is_string;
use function ltrim;
Expand Down Expand Up @@ -96,6 +98,9 @@ class FunctionDocblockManipulator
/** @var bool */
private $is_pure = false;

/** @var list<class-string> */
private $throwsExceptions = [];

/**
* @param Closure|Function_|ClassMethod|ArrowFunction $stmt
*/
Expand Down Expand Up @@ -395,6 +400,21 @@ private function getDocblock(): string
$modified_docblock = true;
$parsed_docblock->tags['psalm-pure'] = [''];
}
if (count($this->throwsExceptions) > 0) {
$modified_docblock = true;
$inferredThrowsClause = array_reduce(
$this->throwsExceptions,
function (string $throwsClause, string $exception) {
return $throwsClause === '' ? $exception : $throwsClause.'|'.$exception;
},
''
);
if (array_key_exists('throws', $parsed_docblock->tags)) {
$parsed_docblock->tags['throws'][] = $inferredThrowsClause;
} else {
$parsed_docblock->tags['throws'] = [$inferredThrowsClause];
}
}


if ($this->new_phpdoc_return_type && $this->new_phpdoc_return_type !== $old_phpdoc_return_type) {
Expand Down Expand Up @@ -528,6 +548,14 @@ public function makePure(): void
$this->is_pure = true;
}

/**
* @param list<class-string> $exceptions
*/
public function addThrowsDocblock(array $exceptions): void
{
$this->throwsExceptions = $exceptions;
}

public static function clearCache(): void
{
self::$manipulators = [];
Expand Down
1 change: 1 addition & 0 deletions tests/FileManipulation/FileManipulationTestCase.php
Expand Up @@ -86,6 +86,7 @@ public function testValidCode(
$safe_types
);
$this->project_analyzer->getCodebase()->allow_backwards_incompatible_changes = $allow_backwards_incompatible_changes;
$this->project_analyzer->getConfig()->check_for_throws_docblock = true;

if (strpos(static::class, 'Unused') || strpos(static::class, 'Unnecessary')) {
$this->project_analyzer->getCodebase()->reportUnusedCode();
Expand Down
123 changes: 123 additions & 0 deletions tests/FileManipulation/ThrowsBlockAdditionTest.php
@@ -0,0 +1,123 @@
<?php

namespace Psalm\Tests\FileManipulation;

class ThrowsBlockAdditionTest extends FileManipulationTestCase
{
/**
* @return array<string,array{string,string,string,string[],bool}>
*/
public function providerValidCodeParse(): array
{
return [
'addThrowsAnnotationToFunction' => [
'<?php
function foo(string $s): string {
if("" === $s) {
throw new \InvalidArgumentException();
}
return $s;
}',
'<?php
/**
* @throws InvalidArgumentException
*/
function foo(string $s): string {
if("" === $s) {
throw new \InvalidArgumentException();
}
return $s;
}',
'7.4',
['MissingThrowsDocblock'],
true,
],
'addMultipleThrowsAnnotationToFunction' => [
'<?php
function foo(string $s): string {
if("" === $s) {
throw new \InvalidArgumentException();
}
if("" === \trim($s)) {
throw new \DomainException();
}
return $s;
}',
'<?php
/**
* @throws InvalidArgumentException|DomainException
*/
function foo(string $s): string {
if("" === $s) {
throw new \InvalidArgumentException();
}
if("" === \trim($s)) {
throw new \DomainException();
}
return $s;
}',
'7.4',
['MissingThrowsDocblock'],
true,
],
'preservesExistingThrowsAnnotationToFunction' => [
'<?php
/**
* @throws InvalidArgumentException|DomainException
*/
function foo(string $s): string {
if("" === $s) {
throw new \Exception();
}
return $s;
}',
'<?php
/**
* @throws InvalidArgumentException|DomainException
* @throws Exception
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i preserve the existing throws annotation and add a new one based on inference

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So the fix will always add a new throws annotation which can have Exception1|Exception2 syntax, but not modify existing one

*/
function foo(string $s): string {
if("" === $s) {
throw new \Exception();
}
return $s;
}',
'7.4',
['MissingThrowsDocblock'],
true,
],
'doesNotAddDuplicateThrows' => [
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This validates that the fix only adds exceptions which are not listed in the current throws doc block

'<?php
/**
* @throws InvalidArgumentException
*/
function foo(string $s): string {
if("" === $s) {
throw new \InvalidArgumentException();
}
if("" === \trim($s)) {
throw new \DomainException();
}
return $s;
}',
'<?php
/**
* @throws InvalidArgumentException
* @throws DomainException
*/
function foo(string $s): string {
if("" === $s) {
throw new \InvalidArgumentException();
}
if("" === \trim($s)) {
throw new \DomainException();
}
return $s;
}',
'7.4',
['MissingThrowsDocblock'],
true,
],
];
}
}