Skip to content

Commit

Permalink
Propagate possibly-null issues onto fetched properties
Browse files Browse the repository at this point in the history
  • Loading branch information
muglug committed Aug 23, 2019
1 parent f00ee74 commit fef61e9
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 4 deletions.
Expand Up @@ -297,7 +297,7 @@ public static function analyzeInstance(
$codebase->analyzer->incrementNonMixedCount($statements_analyzer->getRootFilePath());
}

if ($stmt_var_type->isNullable() && !$stmt_var_type->ignore_nullable_issues && !$context->inside_isset) {
if ($stmt_var_type->isNullable() && !$context->inside_isset && !$stmt_var_type->ignore_nullable_issues) {
if (IssueBuffer::accepts(
new PossiblyNullPropertyFetch(
'Cannot get property on possibly null variable ' . $stmt_var_id . ' of type ' . $stmt_var_type,
Expand All @@ -307,8 +307,6 @@ public static function analyzeInstance(
)) {
// fall through
}

$stmt->inferredType = Type::getNull();
}

if (!$prop_name) {
Expand Down Expand Up @@ -798,6 +796,14 @@ public static function analyzeInstance(
}
}

if ($stmt_var_type->isNullable() && !$context->inside_isset && $stmt->inferredType) {
$stmt->inferredType->addType(new TNull);

if ($stmt_var_type->ignore_nullable_issues) {
$stmt->inferredType->ignore_nullable_issues = true;
}
}

if ($codebase->store_node_types
&& !$context->collect_initializations
&& !$context->collect_mutations
Expand Down
43 changes: 42 additions & 1 deletion tests/PropertyTypeTest.php
Expand Up @@ -1702,7 +1702,28 @@ class Test {
/** @var array<int, static> */
private $t2 = [];
}'
]
],
'propagateIgnoreNullableOnPropertyFetch' => [
'<?php
class A {
public string $s = "hey";
}
/**
* @psalm-ignore-nullable-return
*/
function foo() : ?A {
return rand(0, 1) ? new A : null;
}
function takesString(string $_s) : void {}
$foo = foo();
if ($foo->s !== null) {}
echo $foo->s ?? "bar";
takesString($foo->s);',
],
];
}

Expand Down Expand Up @@ -2689,6 +2710,26 @@ public function __construct() {
$a->bar = "goodbye";',
'error_message' => 'InaccessibleProperty',
],
'addNullToMixedAfterNullablePropertyFetch' => [
'<?php
class A {
/**
* @var mixed
*/
public $foo;
}
function takesString(string $s) : void {}
function takesA(?A $a) : void {
/**
* @psalm-suppress PossiblyNullPropertyFetch
* @psalm-suppress MixedArgument
*/
takesString($a->foo);
}',
'error_message' => 'PossiblyNullArgument',
],
];
}
}

0 comments on commit fef61e9

Please sign in to comment.