1
0
mirror of https://github.com/danog/psalm.git synced 2024-12-15 10:57:08 +01:00
psalm/src/Psalm/Checker/FunctionLikeChecker.php

1309 lines
46 KiB
PHP
Raw Normal View History

2016-08-14 05:26:45 +02:00
<?php
namespace Psalm\Checker;
use PhpParser;
2016-10-15 06:12:57 +02:00
use PhpParser\Node\Expr\Closure;
use PhpParser\Node\Stmt\ClassMethod;
2016-11-02 07:29:00 +01:00
use PhpParser\Node\Stmt\Function_;
Refactor scanning and analysis, introducing multithreading (#191) * Add failing test * Add visitor to soup up classlike references * Move a whole bunch of code into the visitor * Move some methods back, move onto analysis stage * Use the getAliases method everywhere * Fix refs * Fix more refs * Fix some tests * Fix more tests * Fix include tests * Shift config class finding to project checker and fix bugs * Fix a few more tests * transition test to new syntax * Remove var_dump * Delete a bunch of code and fix mutation test * Remove unnecessary visitation * Transition to better mocked out file provider, breaking some cached statement loading * Use different scheme for naming anonymous classes * Fix anonymous class issues * Refactor file/statement loading * Add specific property types * Fix mapped property assignment * Improve how we deal with traits * Fix trait checking * Pass Psalm checks * Add multi-process support * Delay console output until the end * Remove PHP 7 syntax * Update file storage with classes * Fix scanning individual files and add reflection return types * Always turn XDebug off * Add quicker method of getting method mutations * Queue return types for crawling * Interpret all strings as possible classes once we see a `get_class` call * Check invalid return types again * Fix template namespacing issues * Default to class-insensitive file names for includes * Don’t overwrite existing issues data * Add var docblocks for scanning * Add null check * Fix loading of external classes in templates * Only try to populate class when we haven’t yet seen it’s not a class * Fix trait property accessibility * Only ever improve docblock param type * Make param replacement more robust * Fix static const missing inferred type * Fix a few more tests * Register constant definitions * Fix trait aliasing * Skip constant type tests for now * Fix linting issues * Make sure caching is off for tests * Remove unnecessary return * Use emulative parser if on PHP 5.6 * Cache parser for faster first-time parse * Fix constant resolution when scanning classes * Remove test that’s beyond a practical scope * Add back --diff support * Add --help for --threads * Remove unused vars
2017-07-25 22:11:02 +02:00
use Psalm\Aliases;
2016-10-22 19:23:18 +02:00
use Psalm\Checker\Statements\ExpressionChecker;
use Psalm\CodeLocation;
use Psalm\Config;
2016-11-02 07:29:00 +01:00
use Psalm\Context;
use Psalm\EffectsAnalyser;
use Psalm\FunctionLikeParameter;
2016-08-14 05:26:45 +02:00
use Psalm\Issue\InvalidDocblock;
use Psalm\Issue\InvalidParamDefault;
2016-08-14 05:26:45 +02:00
use Psalm\Issue\InvalidReturnType;
use Psalm\Issue\InvalidToString;
use Psalm\Issue\LessSpecificReturnType;
use Psalm\Issue\MethodSignatureMismatch;
use Psalm\Issue\MissingClosureReturnType;
2016-11-07 23:07:59 +01:00
use Psalm\Issue\MissingReturnType;
use Psalm\Issue\MixedInferredReturnType;
use Psalm\Issue\MoreSpecificReturnType;
use Psalm\Issue\OverriddenMethodAccess;
use Psalm\Issue\PossiblyUnusedVariable;
use Psalm\Issue\UntypedParam;
use Psalm\Issue\UnusedVariable;
2016-11-02 07:29:00 +01:00
use Psalm\IssueBuffer;
use Psalm\Mutator\FileMutator;
2016-08-14 05:26:45 +02:00
use Psalm\StatementsSource;
use Psalm\Storage\MethodStorage;
2016-08-14 05:26:45 +02:00
use Psalm\Type;
use Psalm\Type\Atomic\TNamedObject;
2016-08-14 05:26:45 +02:00
2016-11-21 03:49:06 +01:00
abstract class FunctionLikeChecker extends SourceChecker implements StatementsSource
2016-08-14 05:26:45 +02:00
{
const RETURN_TYPE_REGEX = '/\\:\s+(\\??[A-Za-z0-9_\\\\\[\]]+)/';
const PARAM_TYPE_REGEX = '/^(\\??[A-Za-z0-9_\\\\\[\]]+)\s/';
2016-10-14 06:53:43 +02:00
/**
2016-10-15 06:12:57 +02:00
* @var Closure|Function_|ClassMethod
2016-10-14 06:53:43 +02:00
*/
2016-08-14 05:26:45 +02:00
protected $function;
2016-10-14 06:53:43 +02:00
/**
2017-01-07 20:35:07 +01:00
* @var array<string>
2016-10-14 06:53:43 +02:00
*/
2017-01-07 20:35:07 +01:00
protected $suppressed_issues;
2016-10-14 06:53:43 +02:00
/**
* @var bool
*/
2016-08-14 05:26:45 +02:00
protected $is_static = false;
2016-10-14 06:53:43 +02:00
/**
* @var StatementsChecker|null
*/
2016-08-14 05:26:45 +02:00
protected $statements_checker;
2016-10-14 06:53:43 +02:00
/**
* @var StatementsSource
*/
2016-08-14 05:26:45 +02:00
protected $source;
2016-10-14 06:53:43 +02:00
/** @var FileChecker */
public $file_checker;
2016-10-15 06:12:57 +02:00
/**
* @var array<string, array<string, Type\Union>>
2016-10-15 06:12:57 +02:00
*/
2016-08-14 05:26:45 +02:00
protected $return_vars_in_scope = [];
2016-10-15 06:12:57 +02:00
/**
* @var array<string, array<string, bool|string>>
2016-10-15 06:12:57 +02:00
*/
2016-08-14 05:26:45 +02:00
protected $return_vars_possibly_in_scope = [];
2016-11-01 05:39:41 +01:00
/**
* @var array<string, array>
*/
2016-08-14 05:26:45 +02:00
protected static $no_effects_hashes = [];
2016-10-15 06:12:57 +02:00
/**
* @param Closure|Function_|ClassMethod $function
* @param StatementsSource $source
*/
public function __construct($function, StatementsSource $source)
2016-08-14 05:26:45 +02:00
{
$this->function = $function;
$this->source = $source;
$this->file_checker = $source->getFileChecker();
2016-08-14 05:26:45 +02:00
$this->suppressed_issues = $source->getSuppressedIssues();
}
2016-11-02 07:29:00 +01:00
/**
* @param Context $context
* @param Context|null $global_context
2017-01-12 03:37:53 +01:00
* @param bool $add_mutations whether or not to add mutations to this method
2017-05-27 02:16:18 +02:00
*
2016-11-02 07:29:00 +01:00
* @return false|null
*/
2017-01-12 03:37:53 +01:00
public function analyze(Context $context, Context $global_context = null, $add_mutations = false)
2016-08-14 05:26:45 +02:00
{
2017-01-07 20:35:07 +01:00
/** @var array<PhpParser\Node\Expr|PhpParser\Node\Stmt> */
2016-12-07 20:13:39 +01:00
$function_stmts = $this->function->getStmts() ?: [];
2016-09-02 00:02:09 +02:00
2016-12-07 20:13:39 +01:00
$hash = null;
2016-08-14 05:26:45 +02:00
$cased_method_id = null;
2016-11-02 07:29:00 +01:00
2017-02-10 02:35:17 +01:00
$class_storage = null;
if ($global_context) {
foreach ($global_context->constants as $const_name => $var_type) {
if (!$context->hasVariable($const_name)) {
$context->vars_in_scope[$const_name] = clone $var_type;
}
}
}
$project_checker = $this->file_checker->project_checker;
$file_storage_provider = $project_checker->file_storage_provider;
if ($this->function instanceof ClassMethod) {
2017-01-12 06:54:41 +01:00
$real_method_id = (string)$this->getMethodId();
$method_id = (string)$this->getMethodId($context->self);
2017-01-12 03:37:53 +01:00
if ($add_mutations) {
$hash = $real_method_id . json_encode([
2016-12-07 20:13:39 +01:00
$context->vars_in_scope,
2017-05-27 02:05:57 +02:00
$context->vars_possibly_in_scope,
2016-12-07 20:13:39 +01:00
]);
2016-08-14 05:26:45 +02:00
2016-12-07 20:13:39 +01:00
// if we know that the function has no effects on vars, we don't bother rechecking
if (isset(self::$no_effects_hashes[$hash])) {
list(
$context->vars_in_scope,
$context->vars_possibly_in_scope
) = self::$no_effects_hashes[$hash];
2016-12-07 20:13:39 +01:00
return null;
2016-11-07 05:29:54 +01:00
}
2016-12-07 20:13:39 +01:00
} elseif ($context->self) {
$context->vars_in_scope['$this'] = new Type\Union([new TNamedObject($context->self)]);
2017-02-08 08:23:17 +01:00
$context->vars_possibly_in_scope['$this'] = true;
2016-12-07 20:13:39 +01:00
}
2016-11-07 05:29:54 +01:00
$declaring_method_id = MethodChecker::getDeclaringMethodId($project_checker, $method_id);
if (!is_string($declaring_method_id)) {
throw new \UnexpectedValueException('$declaring_method_id should be a string');
}
2017-01-07 20:35:07 +01:00
$fq_class_name = (string)$context->self;
2016-11-05 03:04:55 +01:00
$project_checker = $this->file_checker->project_checker;
2017-02-10 02:35:17 +01:00
$classlike_storage_provider = $project_checker->classlike_storage_provider;
$class_storage = $classlike_storage_provider->get($fq_class_name);
$storage = MethodChecker::getStorage($project_checker, $declaring_method_id);
$cased_method_id = $fq_class_name . '::' . $storage->cased_name;
$implemented_method_ids = MethodChecker::getOverriddenMethodIds($project_checker, $method_id);
if ($this->function->name === '__construct') {
$context->inside_constructor = true;
}
$implemented_docblock_param_types = [];
2016-12-07 20:13:39 +01:00
if ($implemented_method_ids) {
$have_emitted = false;
2016-12-07 20:13:39 +01:00
foreach ($implemented_method_ids as $implemented_method_id) {
if ($this->function->name === '__construct') {
2016-12-07 20:13:39 +01:00
continue;
}
2016-11-07 05:29:54 +01:00
list($implemented_fq_class_name) = explode('::', $implemented_method_id);
$class_storage = $classlike_storage_provider->get($implemented_fq_class_name);
$implemented_storage = MethodChecker::getStorage($project_checker, $implemented_method_id);
if ($implemented_storage->visibility < $storage->visibility) {
$parent_method_id = MethodChecker::getCasedMethodId(
$project_checker,
$implemented_method_id
);
if (IssueBuffer::accepts(
new OverriddenMethodAccess(
2017-05-25 04:07:49 +02:00
'Method ' . $cased_method_id . ' has different access level than ' . $parent_method_id,
new CodeLocation($this, $this->function, $context->include_location, true)
)
)) {
return false;
}
2016-12-07 20:13:39 +01:00
continue;
}
$implemented_params = $implemented_storage->params;
2016-12-07 20:13:39 +01:00
foreach ($implemented_params as $i => $implemented_param) {
if (!isset($storage->params[$i])) {
$parent_method_id = MethodChecker::getCasedMethodId(
$project_checker,
$implemented_method_id
);
2016-12-07 20:13:39 +01:00
if (IssueBuffer::accepts(
new MethodSignatureMismatch(
2017-05-25 04:07:49 +02:00
'Method ' . $cased_method_id . ' has fewer arguments than parent method ' .
2016-12-07 20:13:39 +01:00
$parent_method_id,
new CodeLocation($this, $this->function, $context->include_location, true)
2016-12-07 20:13:39 +01:00
)
)) {
return false;
}
2016-12-07 20:13:39 +01:00
$have_emitted = true;
break 2;
2016-12-07 20:13:39 +01:00
}
if ($class_storage->user_defined &&
(string)$storage->params[$i]->signature_type !== (string)$implemented_param->signature_type
2016-12-07 20:13:39 +01:00
) {
$cased_method_id = MethodChecker::getCasedMethodId(
$project_checker,
(string)$this->getMethodId()
);
$parent_method_id = MethodChecker::getCasedMethodId(
$project_checker,
$implemented_method_id
);
2016-12-07 20:13:39 +01:00
if (IssueBuffer::accepts(
new MethodSignatureMismatch(
2017-05-25 04:07:49 +02:00
'Argument ' . ($i + 1) . ' of ' . $cased_method_id . ' has wrong type \'' .
$storage->params[$i]->signature_type . '\', expecting \'' .
2016-12-07 20:13:39 +01:00
$implemented_param->signature_type . '\' as defined by ' .
$parent_method_id,
$storage->params[$i]->location
?: new CodeLocation(
$this,
$this->function,
$context->include_location,
true
)
2016-12-07 20:13:39 +01:00
)
)) {
return false;
}
2016-12-07 20:13:39 +01:00
$have_emitted = true;
break 2;
}
if ($implemented_param->type
&& (!$implemented_param->signature_type || !$class_storage->user_defined)
) {
$implemented_docblock_param_types[$i] = true;
}
if (!$class_storage->user_defined &&
$implemented_param->type &&
!$implemented_param->type->isMixed() &&
(string)$storage->params[$i]->type !== (string)$implemented_param->type
) {
$cased_method_id = MethodChecker::getCasedMethodId(
$project_checker,
(string)$this->getMethodId()
);
$parent_method_id = MethodChecker::getCasedMethodId(
$project_checker,
$implemented_method_id
);
if (IssueBuffer::accepts(
new MethodSignatureMismatch(
2017-05-25 04:07:49 +02:00
'Argument ' . ($i + 1) . ' of ' . $cased_method_id . ' has wrong type \'' .
$storage->params[$i]->type . '\', expecting \'' .
$implemented_param->type . '\' as defined by ' .
$parent_method_id,
$storage->params[$i]->location
?: new CodeLocation(
$this,
$this->function,
$context->include_location,
true
)
)
)) {
return false;
}
$have_emitted = true;
break 2;
}
}
if ($storage->cased_name !== '__construct' &&
$storage->required_param_count > $implemented_storage->required_param_count
) {
$parent_method_id = MethodChecker::getCasedMethodId($project_checker, $implemented_method_id);
if (IssueBuffer::accepts(
new MethodSignatureMismatch(
2017-05-25 04:07:49 +02:00
'Method ' . $cased_method_id . ' has more arguments than parent method ' .
$parent_method_id,
new CodeLocation($this, $this->function, $context->include_location, true)
)
)) {
return false;
}
$have_emitted = true;
break;
}
}
2016-12-07 20:13:39 +01:00
}
} elseif ($this->function instanceof Function_) {
$file_storage = $file_storage_provider->get($this->source->getFilePath());
Refactor scanning and analysis, introducing multithreading (#191) * Add failing test * Add visitor to soup up classlike references * Move a whole bunch of code into the visitor * Move some methods back, move onto analysis stage * Use the getAliases method everywhere * Fix refs * Fix more refs * Fix some tests * Fix more tests * Fix include tests * Shift config class finding to project checker and fix bugs * Fix a few more tests * transition test to new syntax * Remove var_dump * Delete a bunch of code and fix mutation test * Remove unnecessary visitation * Transition to better mocked out file provider, breaking some cached statement loading * Use different scheme for naming anonymous classes * Fix anonymous class issues * Refactor file/statement loading * Add specific property types * Fix mapped property assignment * Improve how we deal with traits * Fix trait checking * Pass Psalm checks * Add multi-process support * Delay console output until the end * Remove PHP 7 syntax * Update file storage with classes * Fix scanning individual files and add reflection return types * Always turn XDebug off * Add quicker method of getting method mutations * Queue return types for crawling * Interpret all strings as possible classes once we see a `get_class` call * Check invalid return types again * Fix template namespacing issues * Default to class-insensitive file names for includes * Don’t overwrite existing issues data * Add var docblocks for scanning * Add null check * Fix loading of external classes in templates * Only try to populate class when we haven’t yet seen it’s not a class * Fix trait property accessibility * Only ever improve docblock param type * Make param replacement more robust * Fix static const missing inferred type * Fix a few more tests * Register constant definitions * Fix trait aliasing * Skip constant type tests for now * Fix linting issues * Make sure caching is off for tests * Remove unnecessary return * Use emulative parser if on PHP 5.6 * Cache parser for faster first-time parse * Fix constant resolution when scanning classes * Remove test that’s beyond a practical scope * Add back --diff support * Add --help for --threads * Remove unused vars
2017-07-25 22:11:02 +02:00
$storage = $file_storage->functions[(string)$this->getMethodId()];
2016-12-07 20:13:39 +01:00
$cased_method_id = $this->function->name;
} else { // Closure
$file_storage = $file_storage_provider->get($this->source->getFilePath());
Refactor scanning and analysis, introducing multithreading (#191) * Add failing test * Add visitor to soup up classlike references * Move a whole bunch of code into the visitor * Move some methods back, move onto analysis stage * Use the getAliases method everywhere * Fix refs * Fix more refs * Fix some tests * Fix more tests * Fix include tests * Shift config class finding to project checker and fix bugs * Fix a few more tests * transition test to new syntax * Remove var_dump * Delete a bunch of code and fix mutation test * Remove unnecessary visitation * Transition to better mocked out file provider, breaking some cached statement loading * Use different scheme for naming anonymous classes * Fix anonymous class issues * Refactor file/statement loading * Add specific property types * Fix mapped property assignment * Improve how we deal with traits * Fix trait checking * Pass Psalm checks * Add multi-process support * Delay console output until the end * Remove PHP 7 syntax * Update file storage with classes * Fix scanning individual files and add reflection return types * Always turn XDebug off * Add quicker method of getting method mutations * Queue return types for crawling * Interpret all strings as possible classes once we see a `get_class` call * Check invalid return types again * Fix template namespacing issues * Default to class-insensitive file names for includes * Don’t overwrite existing issues data * Add var docblocks for scanning * Add null check * Fix loading of external classes in templates * Only try to populate class when we haven’t yet seen it’s not a class * Fix trait property accessibility * Only ever improve docblock param type * Make param replacement more robust * Fix static const missing inferred type * Fix a few more tests * Register constant definitions * Fix trait aliasing * Skip constant type tests for now * Fix linting issues * Make sure caching is off for tests * Remove unnecessary return * Use emulative parser if on PHP 5.6 * Cache parser for faster first-time parse * Fix constant resolution when scanning classes * Remove test that’s beyond a practical scope * Add back --diff support * Add --help for --threads * Remove unused vars
2017-07-25 22:11:02 +02:00
$function_id = $cased_function_id = $this->getMethodId();
Refactor scanning and analysis, introducing multithreading (#191) * Add failing test * Add visitor to soup up classlike references * Move a whole bunch of code into the visitor * Move some methods back, move onto analysis stage * Use the getAliases method everywhere * Fix refs * Fix more refs * Fix some tests * Fix more tests * Fix include tests * Shift config class finding to project checker and fix bugs * Fix a few more tests * transition test to new syntax * Remove var_dump * Delete a bunch of code and fix mutation test * Remove unnecessary visitation * Transition to better mocked out file provider, breaking some cached statement loading * Use different scheme for naming anonymous classes * Fix anonymous class issues * Refactor file/statement loading * Add specific property types * Fix mapped property assignment * Improve how we deal with traits * Fix trait checking * Pass Psalm checks * Add multi-process support * Delay console output until the end * Remove PHP 7 syntax * Update file storage with classes * Fix scanning individual files and add reflection return types * Always turn XDebug off * Add quicker method of getting method mutations * Queue return types for crawling * Interpret all strings as possible classes once we see a `get_class` call * Check invalid return types again * Fix template namespacing issues * Default to class-insensitive file names for includes * Don’t overwrite existing issues data * Add var docblocks for scanning * Add null check * Fix loading of external classes in templates * Only try to populate class when we haven’t yet seen it’s not a class * Fix trait property accessibility * Only ever improve docblock param type * Make param replacement more robust * Fix static const missing inferred type * Fix a few more tests * Register constant definitions * Fix trait aliasing * Skip constant type tests for now * Fix linting issues * Make sure caching is off for tests * Remove unnecessary return * Use emulative parser if on PHP 5.6 * Cache parser for faster first-time parse * Fix constant resolution when scanning classes * Remove test that’s beyond a practical scope * Add back --diff support * Add --help for --threads * Remove unused vars
2017-07-25 22:11:02 +02:00
if (!isset($file_storage->functions[$function_id])) {
throw new \UnexpectedValueException('Closure function ' . $function_id . ' should exist');
}
Refactor scanning and analysis, introducing multithreading (#191) * Add failing test * Add visitor to soup up classlike references * Move a whole bunch of code into the visitor * Move some methods back, move onto analysis stage * Use the getAliases method everywhere * Fix refs * Fix more refs * Fix some tests * Fix more tests * Fix include tests * Shift config class finding to project checker and fix bugs * Fix a few more tests * transition test to new syntax * Remove var_dump * Delete a bunch of code and fix mutation test * Remove unnecessary visitation * Transition to better mocked out file provider, breaking some cached statement loading * Use different scheme for naming anonymous classes * Fix anonymous class issues * Refactor file/statement loading * Add specific property types * Fix mapped property assignment * Improve how we deal with traits * Fix trait checking * Pass Psalm checks * Add multi-process support * Delay console output until the end * Remove PHP 7 syntax * Update file storage with classes * Fix scanning individual files and add reflection return types * Always turn XDebug off * Add quicker method of getting method mutations * Queue return types for crawling * Interpret all strings as possible classes once we see a `get_class` call * Check invalid return types again * Fix template namespacing issues * Default to class-insensitive file names for includes * Don’t overwrite existing issues data * Add var docblocks for scanning * Add null check * Fix loading of external classes in templates * Only try to populate class when we haven’t yet seen it’s not a class * Fix trait property accessibility * Only ever improve docblock param type * Make param replacement more robust * Fix static const missing inferred type * Fix a few more tests * Register constant definitions * Fix trait aliasing * Skip constant type tests for now * Fix linting issues * Make sure caching is off for tests * Remove unnecessary return * Use emulative parser if on PHP 5.6 * Cache parser for faster first-time parse * Fix constant resolution when scanning classes * Remove test that’s beyond a practical scope * Add back --diff support * Add --help for --threads * Remove unused vars
2017-07-25 22:11:02 +02:00
$storage = $file_storage->functions[$function_id];
2016-09-02 00:02:09 +02:00
2016-12-15 01:19:25 +01:00
/** @var PhpParser\Node\Expr\Closure $this->function */
2016-12-07 20:13:39 +01:00
$this->function->inferredType = new Type\Union([
new Type\Atomic\Fn(
2016-12-07 20:13:39 +01:00
'Closure',
$storage->params,
$storage->return_type ?: Type::getMixed()
2017-05-27 02:05:57 +02:00
),
2016-12-07 20:13:39 +01:00
]);
}
2016-09-02 00:02:09 +02:00
$this->suppressed_issues = array_merge(
$this->getSource()->getSuppressedIssues(),
$storage->suppressed_issues
);
if ($storage instanceof MethodStorage && $storage->is_static) {
$this->is_static = true;
}
$statements_checker = new StatementsChecker($this);
2017-02-10 02:35:17 +01:00
$template_types = $storage->template_types;
if ($class_storage && $class_storage->template_types) {
$template_types = array_merge($template_types ?: [], $class_storage->template_types);
}
foreach ($storage->params as $offset => $function_param) {
Refactor scanning and analysis, introducing multithreading (#191) * Add failing test * Add visitor to soup up classlike references * Move a whole bunch of code into the visitor * Move some methods back, move onto analysis stage * Use the getAliases method everywhere * Fix refs * Fix more refs * Fix some tests * Fix more tests * Fix include tests * Shift config class finding to project checker and fix bugs * Fix a few more tests * transition test to new syntax * Remove var_dump * Delete a bunch of code and fix mutation test * Remove unnecessary visitation * Transition to better mocked out file provider, breaking some cached statement loading * Use different scheme for naming anonymous classes * Fix anonymous class issues * Refactor file/statement loading * Add specific property types * Fix mapped property assignment * Improve how we deal with traits * Fix trait checking * Pass Psalm checks * Add multi-process support * Delay console output until the end * Remove PHP 7 syntax * Update file storage with classes * Fix scanning individual files and add reflection return types * Always turn XDebug off * Add quicker method of getting method mutations * Queue return types for crawling * Interpret all strings as possible classes once we see a `get_class` call * Check invalid return types again * Fix template namespacing issues * Default to class-insensitive file names for includes * Don’t overwrite existing issues data * Add var docblocks for scanning * Add null check * Fix loading of external classes in templates * Only try to populate class when we haven’t yet seen it’s not a class * Fix trait property accessibility * Only ever improve docblock param type * Make param replacement more robust * Fix static const missing inferred type * Fix a few more tests * Register constant definitions * Fix trait aliasing * Skip constant type tests for now * Fix linting issues * Make sure caching is off for tests * Remove unnecessary return * Use emulative parser if on PHP 5.6 * Cache parser for faster first-time parse * Fix constant resolution when scanning classes * Remove test that’s beyond a practical scope * Add back --diff support * Add --help for --threads * Remove unused vars
2017-07-25 22:11:02 +02:00
$signature_type = $function_param->signature_type;
2017-02-10 06:14:44 +01:00
if ($function_param->type) {
$param_type = clone $function_param->type;
$param_type = ExpressionChecker::fleshOutType(
$project_checker,
$param_type,
$context->self,
$this->getMethodId()
);
} else {
$param_type = Type::getMixed();
}
2017-07-09 03:19:16 +02:00
$context->vars_in_scope['$' . $function_param->name] = $param_type;
$context->vars_possibly_in_scope['$' . $function_param->name] = true;
2017-03-02 00:36:04 +01:00
if (!$function_param->location) {
2017-07-09 03:19:16 +02:00
continue;
2016-12-07 20:13:39 +01:00
}
$parser_param = $this->function->getParams()[$offset];
Refactor scanning and analysis, introducing multithreading (#191) * Add failing test * Add visitor to soup up classlike references * Move a whole bunch of code into the visitor * Move some methods back, move onto analysis stage * Use the getAliases method everywhere * Fix refs * Fix more refs * Fix some tests * Fix more tests * Fix include tests * Shift config class finding to project checker and fix bugs * Fix a few more tests * transition test to new syntax * Remove var_dump * Delete a bunch of code and fix mutation test * Remove unnecessary visitation * Transition to better mocked out file provider, breaking some cached statement loading * Use different scheme for naming anonymous classes * Fix anonymous class issues * Refactor file/statement loading * Add specific property types * Fix mapped property assignment * Improve how we deal with traits * Fix trait checking * Pass Psalm checks * Add multi-process support * Delay console output until the end * Remove PHP 7 syntax * Update file storage with classes * Fix scanning individual files and add reflection return types * Always turn XDebug off * Add quicker method of getting method mutations * Queue return types for crawling * Interpret all strings as possible classes once we see a `get_class` call * Check invalid return types again * Fix template namespacing issues * Default to class-insensitive file names for includes * Don’t overwrite existing issues data * Add var docblocks for scanning * Add null check * Fix loading of external classes in templates * Only try to populate class when we haven’t yet seen it’s not a class * Fix trait property accessibility * Only ever improve docblock param type * Make param replacement more robust * Fix static const missing inferred type * Fix a few more tests * Register constant definitions * Fix trait aliasing * Skip constant type tests for now * Fix linting issues * Make sure caching is off for tests * Remove unnecessary return * Use emulative parser if on PHP 5.6 * Cache parser for faster first-time parse * Fix constant resolution when scanning classes * Remove test that’s beyond a practical scope * Add back --diff support * Add --help for --threads * Remove unused vars
2017-07-25 22:11:02 +02:00
if ($signature_type) {
if (!TypeChecker::isContainedBy(
$project_checker,
Refactor scanning and analysis, introducing multithreading (#191) * Add failing test * Add visitor to soup up classlike references * Move a whole bunch of code into the visitor * Move some methods back, move onto analysis stage * Use the getAliases method everywhere * Fix refs * Fix more refs * Fix some tests * Fix more tests * Fix include tests * Shift config class finding to project checker and fix bugs * Fix a few more tests * transition test to new syntax * Remove var_dump * Delete a bunch of code and fix mutation test * Remove unnecessary visitation * Transition to better mocked out file provider, breaking some cached statement loading * Use different scheme for naming anonymous classes * Fix anonymous class issues * Refactor file/statement loading * Add specific property types * Fix mapped property assignment * Improve how we deal with traits * Fix trait checking * Pass Psalm checks * Add multi-process support * Delay console output until the end * Remove PHP 7 syntax * Update file storage with classes * Fix scanning individual files and add reflection return types * Always turn XDebug off * Add quicker method of getting method mutations * Queue return types for crawling * Interpret all strings as possible classes once we see a `get_class` call * Check invalid return types again * Fix template namespacing issues * Default to class-insensitive file names for includes * Don’t overwrite existing issues data * Add var docblocks for scanning * Add null check * Fix loading of external classes in templates * Only try to populate class when we haven’t yet seen it’s not a class * Fix trait property accessibility * Only ever improve docblock param type * Make param replacement more robust * Fix static const missing inferred type * Fix a few more tests * Register constant definitions * Fix trait aliasing * Skip constant type tests for now * Fix linting issues * Make sure caching is off for tests * Remove unnecessary return * Use emulative parser if on PHP 5.6 * Cache parser for faster first-time parse * Fix constant resolution when scanning classes * Remove test that’s beyond a practical scope * Add back --diff support * Add --help for --threads * Remove unused vars
2017-07-25 22:11:02 +02:00
$param_type,
$signature_type
Refactor scanning and analysis, introducing multithreading (#191) * Add failing test * Add visitor to soup up classlike references * Move a whole bunch of code into the visitor * Move some methods back, move onto analysis stage * Use the getAliases method everywhere * Fix refs * Fix more refs * Fix some tests * Fix more tests * Fix include tests * Shift config class finding to project checker and fix bugs * Fix a few more tests * transition test to new syntax * Remove var_dump * Delete a bunch of code and fix mutation test * Remove unnecessary visitation * Transition to better mocked out file provider, breaking some cached statement loading * Use different scheme for naming anonymous classes * Fix anonymous class issues * Refactor file/statement loading * Add specific property types * Fix mapped property assignment * Improve how we deal with traits * Fix trait checking * Pass Psalm checks * Add multi-process support * Delay console output until the end * Remove PHP 7 syntax * Update file storage with classes * Fix scanning individual files and add reflection return types * Always turn XDebug off * Add quicker method of getting method mutations * Queue return types for crawling * Interpret all strings as possible classes once we see a `get_class` call * Check invalid return types again * Fix template namespacing issues * Default to class-insensitive file names for includes * Don’t overwrite existing issues data * Add var docblocks for scanning * Add null check * Fix loading of external classes in templates * Only try to populate class when we haven’t yet seen it’s not a class * Fix trait property accessibility * Only ever improve docblock param type * Make param replacement more robust * Fix static const missing inferred type * Fix a few more tests * Register constant definitions * Fix trait aliasing * Skip constant type tests for now * Fix linting issues * Make sure caching is off for tests * Remove unnecessary return * Use emulative parser if on PHP 5.6 * Cache parser for faster first-time parse * Fix constant resolution when scanning classes * Remove test that’s beyond a practical scope * Add back --diff support * Add --help for --threads * Remove unused vars
2017-07-25 22:11:02 +02:00
)
) {
if (IssueBuffer::accepts(
new InvalidDocblock(
'Parameter $' . $function_param->name . ' has wrong type \'' . $param_type .
'\', should be \'' . $signature_type . '\'',
$function_param->location
),
$storage->suppressed_issues
)) {
return false;
}
continue;
}
}
if ($parser_param->default) {
$default_type = StatementsChecker::getSimpleType($parser_param->default);
if ($default_type &&
!TypeChecker::isContainedBy(
$project_checker,
$default_type,
$param_type
)
) {
$method_id = $this->getMethodId();
if (IssueBuffer::accepts(
new InvalidParamDefault(
'Default value for argument ' . ($offset + 1) . ' of method ' . $cased_method_id .
' does not match the given type ' . $param_type,
2017-03-02 00:36:04 +01:00
$function_param->location
)
)) {
2016-12-31 06:14:00 +01:00
// fall through
}
}
}
2017-02-10 02:35:17 +01:00
if ($template_types) {
2017-02-10 06:14:44 +01:00
$substituted_type = clone $param_type;
$generic_types = [];
2017-02-10 06:14:44 +01:00
$substituted_type->replaceTemplateTypes($template_types, $generic_types, null);
$substituted_type->check($this->source, $function_param->location, $this->suppressed_issues, [], false);
2017-02-10 02:35:17 +01:00
} else {
$param_type->check($this->source, $function_param->location, $this->suppressed_issues, [], false);
2017-03-02 00:36:04 +01:00
}
if ($this->getFileChecker()->project_checker->collect_references) {
if ($function_param->location !== $function_param->signature_location &&
$function_param->signature_location &&
$function_param->signature_type
) {
$function_param->signature_type->check(
$this->source,
$function_param->signature_location,
$this->suppressed_issues,
[],
false
2017-03-02 00:36:04 +01:00
);
}
2017-02-10 02:35:17 +01:00
}
2016-09-02 00:02:09 +02:00
if ($function_param->by_ref && !$param_type->isMixed()) {
$context->byref_constraints['$' . $function_param->name] = new \Psalm\ReferenceConstraint($param_type);
}
2017-02-08 08:23:17 +01:00
if ($function_param->by_ref) {
// register by ref params as having been used, to avoid false positives
// @todo change the assignment analysis *just* for byref params
// so that we don't have to do this
$context->hasVariable('$' . $function_param->name);
}
2016-09-02 00:02:09 +02:00
2016-12-07 20:13:39 +01:00
$statements_checker->registerVariable(
2017-02-08 08:23:17 +01:00
'$' . $function_param->name,
2017-03-02 00:36:04 +01:00
$function_param->location
2016-12-07 20:13:39 +01:00
);
}
2016-08-14 05:26:45 +02:00
Refactor scanning and analysis, introducing multithreading (#191) * Add failing test * Add visitor to soup up classlike references * Move a whole bunch of code into the visitor * Move some methods back, move onto analysis stage * Use the getAliases method everywhere * Fix refs * Fix more refs * Fix some tests * Fix more tests * Fix include tests * Shift config class finding to project checker and fix bugs * Fix a few more tests * transition test to new syntax * Remove var_dump * Delete a bunch of code and fix mutation test * Remove unnecessary visitation * Transition to better mocked out file provider, breaking some cached statement loading * Use different scheme for naming anonymous classes * Fix anonymous class issues * Refactor file/statement loading * Add specific property types * Fix mapped property assignment * Improve how we deal with traits * Fix trait checking * Pass Psalm checks * Add multi-process support * Delay console output until the end * Remove PHP 7 syntax * Update file storage with classes * Fix scanning individual files and add reflection return types * Always turn XDebug off * Add quicker method of getting method mutations * Queue return types for crawling * Interpret all strings as possible classes once we see a `get_class` call * Check invalid return types again * Fix template namespacing issues * Default to class-insensitive file names for includes * Don’t overwrite existing issues data * Add var docblocks for scanning * Add null check * Fix loading of external classes in templates * Only try to populate class when we haven’t yet seen it’s not a class * Fix trait property accessibility * Only ever improve docblock param type * Make param replacement more robust * Fix static const missing inferred type * Fix a few more tests * Register constant definitions * Fix trait aliasing * Skip constant type tests for now * Fix linting issues * Make sure caching is off for tests * Remove unnecessary return * Use emulative parser if on PHP 5.6 * Cache parser for faster first-time parse * Fix constant resolution when scanning classes * Remove test that’s beyond a practical scope * Add back --diff support * Add --help for --threads * Remove unused vars
2017-07-25 22:11:02 +02:00
if ($storage->return_type && $storage->signature_return_type && $storage->return_type_location) {
if (!TypeChecker::isContainedBy(
$project_checker,
Refactor scanning and analysis, introducing multithreading (#191) * Add failing test * Add visitor to soup up classlike references * Move a whole bunch of code into the visitor * Move some methods back, move onto analysis stage * Use the getAliases method everywhere * Fix refs * Fix more refs * Fix some tests * Fix more tests * Fix include tests * Shift config class finding to project checker and fix bugs * Fix a few more tests * transition test to new syntax * Remove var_dump * Delete a bunch of code and fix mutation test * Remove unnecessary visitation * Transition to better mocked out file provider, breaking some cached statement loading * Use different scheme for naming anonymous classes * Fix anonymous class issues * Refactor file/statement loading * Add specific property types * Fix mapped property assignment * Improve how we deal with traits * Fix trait checking * Pass Psalm checks * Add multi-process support * Delay console output until the end * Remove PHP 7 syntax * Update file storage with classes * Fix scanning individual files and add reflection return types * Always turn XDebug off * Add quicker method of getting method mutations * Queue return types for crawling * Interpret all strings as possible classes once we see a `get_class` call * Check invalid return types again * Fix template namespacing issues * Default to class-insensitive file names for includes * Don’t overwrite existing issues data * Add var docblocks for scanning * Add null check * Fix loading of external classes in templates * Only try to populate class when we haven’t yet seen it’s not a class * Fix trait property accessibility * Only ever improve docblock param type * Make param replacement more robust * Fix static const missing inferred type * Fix a few more tests * Register constant definitions * Fix trait aliasing * Skip constant type tests for now * Fix linting issues * Make sure caching is off for tests * Remove unnecessary return * Use emulative parser if on PHP 5.6 * Cache parser for faster first-time parse * Fix constant resolution when scanning classes * Remove test that’s beyond a practical scope * Add back --diff support * Add --help for --threads * Remove unused vars
2017-07-25 22:11:02 +02:00
$storage->return_type,
$storage->signature_return_type
Refactor scanning and analysis, introducing multithreading (#191) * Add failing test * Add visitor to soup up classlike references * Move a whole bunch of code into the visitor * Move some methods back, move onto analysis stage * Use the getAliases method everywhere * Fix refs * Fix more refs * Fix some tests * Fix more tests * Fix include tests * Shift config class finding to project checker and fix bugs * Fix a few more tests * transition test to new syntax * Remove var_dump * Delete a bunch of code and fix mutation test * Remove unnecessary visitation * Transition to better mocked out file provider, breaking some cached statement loading * Use different scheme for naming anonymous classes * Fix anonymous class issues * Refactor file/statement loading * Add specific property types * Fix mapped property assignment * Improve how we deal with traits * Fix trait checking * Pass Psalm checks * Add multi-process support * Delay console output until the end * Remove PHP 7 syntax * Update file storage with classes * Fix scanning individual files and add reflection return types * Always turn XDebug off * Add quicker method of getting method mutations * Queue return types for crawling * Interpret all strings as possible classes once we see a `get_class` call * Check invalid return types again * Fix template namespacing issues * Default to class-insensitive file names for includes * Don’t overwrite existing issues data * Add var docblocks for scanning * Add null check * Fix loading of external classes in templates * Only try to populate class when we haven’t yet seen it’s not a class * Fix trait property accessibility * Only ever improve docblock param type * Make param replacement more robust * Fix static const missing inferred type * Fix a few more tests * Register constant definitions * Fix trait aliasing * Skip constant type tests for now * Fix linting issues * Make sure caching is off for tests * Remove unnecessary return * Use emulative parser if on PHP 5.6 * Cache parser for faster first-time parse * Fix constant resolution when scanning classes * Remove test that’s beyond a practical scope * Add back --diff support * Add --help for --threads * Remove unused vars
2017-07-25 22:11:02 +02:00
)
) {
if (IssueBuffer::accepts(
new InvalidDocblock(
'Return type has wrong type \'' . $storage->return_type .
'\', should be \'' . $storage->signature_return_type . '\'',
$storage->return_type_location
),
$storage->suppressed_issues
)) {
return false;
}
}
}
$statements_checker->analyze($function_stmts, $context, null, $global_context);
2016-08-14 05:26:45 +02:00
foreach ($storage->params as $offset => $function_param) {
$signature_type = $function_param->signature_type;
// only complain if there's no type defined by a parent type
if (!$function_param->type
&& $function_param->location
&& !isset($implemented_docblock_param_types[$offset])
) {
$possible_type = null;
if (isset($context->possible_param_types[$function_param->name])) {
$possible_type = $context->possible_param_types[$function_param->name];
}
IssueBuffer::accepts(
new UntypedParam(
'Parameter $' . $function_param->name . ' has no provided type, '
. ($possible_type ? 'should be ' . $possible_type : 'could not infer'),
$function_param->location
),
$storage->suppressed_issues
);
}
}
2016-12-07 20:13:39 +01:00
if ($this->function instanceof Closure) {
$closure_yield_types = [];
2016-08-14 05:26:45 +02:00
$this->verifyReturnType(
2016-12-07 20:13:39 +01:00
false,
$storage->return_type,
2017-01-07 20:35:07 +01:00
$this->source->getFQCLN(),
$storage->return_type_location
2016-12-07 20:13:39 +01:00
);
if (!$storage->return_type || $storage->return_type->isMixed()) {
2016-12-07 20:13:39 +01:00
$closure_yield_types = [];
$closure_return_types = EffectsAnalyser::getReturnTypes(
$this->function->stmts,
$closure_yield_types,
2017-05-10 20:05:26 +02:00
$ignore_nullable_issues,
2016-12-07 20:13:39 +01:00
true
2016-11-02 07:29:00 +01:00
);
2016-08-14 05:26:45 +02:00
2016-12-15 01:19:25 +01:00
if ($closure_return_types && $this->function->inferredType) {
/** @var Type\Atomic\Fn */
2016-12-15 01:19:25 +01:00
$closure_atomic = $this->function->inferredType->types['Closure'];
$closure_atomic->return_type = new Type\Union($closure_return_types);
2016-08-14 05:26:45 +02:00
}
}
2016-12-07 20:13:39 +01:00
}
2016-08-14 05:26:45 +02:00
if ($context->collect_references &&
!$this->getFileChecker()->project_checker->find_references_to &&
$context->check_variables
) {
2017-02-02 06:45:23 +01:00
foreach ($context->vars_possibly_in_scope as $var_name => $_) {
if (strpos($var_name, '->') === false &&
$var_name !== '$this' &&
strpos($var_name, '::$') === false &&
2017-02-02 06:45:23 +01:00
strpos($var_name, '[') === false &&
$var_name !== '$_'
) {
2017-02-08 00:18:33 +01:00
$original_location = $statements_checker->getFirstAppearance($var_name);
if (!isset($context->referenced_vars[$var_name]) && $original_location) {
if (!isset($storage->param_types[substr($var_name, 1)]) ||
!$storage instanceof MethodStorage ||
$storage->visibility === ClassLikeChecker::VISIBILITY_PRIVATE
) {
if (IssueBuffer::accepts(
new UnusedVariable(
'Variable ' . $var_name . ' is never referenced',
$original_location
),
$this->getSuppressedIssues()
)) {
// fall through
}
} else {
if (IssueBuffer::accepts(
new PossiblyUnusedVariable(
'Variable ' . $var_name . ' is never referenced in this method',
$original_location
),
$this->getSuppressedIssues()
)) {
// fall through
}
2017-02-08 00:18:33 +01:00
}
}
}
}
}
2017-01-12 03:37:53 +01:00
if ($add_mutations) {
if (isset($this->return_vars_in_scope[''])) {
$context->vars_in_scope = TypeChecker::combineKeyedTypes(
$context->vars_in_scope,
$this->return_vars_in_scope['']
);
}
2016-12-07 20:13:39 +01:00
2017-01-12 03:37:53 +01:00
if (isset($this->return_vars_possibly_in_scope[''])) {
$context->vars_possibly_in_scope = array_merge(
$context->vars_possibly_in_scope,
$this->return_vars_possibly_in_scope['']
);
}
2016-12-07 20:13:39 +01:00
2017-02-11 01:10:13 +01:00
foreach ($context->vars_in_scope as $var => $_) {
if (strpos($var, '$this->') !== 0 && $var !== '$this') {
2017-01-12 03:37:53 +01:00
unset($context->vars_in_scope[$var]);
}
2016-08-14 05:26:45 +02:00
}
2017-02-11 01:10:13 +01:00
foreach ($context->vars_possibly_in_scope as $var => $_) {
if (strpos($var, '$this->') !== 0 && $var !== '$this') {
2017-01-12 03:37:53 +01:00
unset($context->vars_possibly_in_scope[$var]);
}
2016-08-14 05:26:45 +02:00
}
2016-11-02 07:29:00 +01:00
2017-01-12 03:37:53 +01:00
if ($hash && $this instanceof MethodChecker) {
self::$no_effects_hashes[$hash] = [
$context->vars_in_scope,
2017-05-27 02:05:57 +02:00
$context->vars_possibly_in_scope,
2017-01-12 03:37:53 +01:00
];
}
2016-12-07 20:13:39 +01:00
}
2016-11-02 07:29:00 +01:00
return null;
2016-08-14 05:26:45 +02:00
}
/**
* Adds return types for the given function
2016-11-02 07:29:00 +01:00
*
* @param string $return_type
* @param Context $context
2017-05-27 02:16:18 +02:00
*
2016-11-02 07:29:00 +01:00
* @return void
2016-08-14 05:26:45 +02:00
*/
public function addReturnTypes($return_type, Context $context)
{
if (isset($this->return_vars_in_scope[$return_type])) {
2016-11-02 07:29:00 +01:00
$this->return_vars_in_scope[$return_type] = TypeChecker::combineKeyedTypes(
$context->vars_in_scope,
$this->return_vars_in_scope[$return_type]
);
} else {
2016-08-14 05:26:45 +02:00
$this->return_vars_in_scope[$return_type] = $context->vars_in_scope;
}
if (isset($this->return_vars_possibly_in_scope[$return_type])) {
2016-11-02 07:29:00 +01:00
$this->return_vars_possibly_in_scope[$return_type] = array_merge(
$context->vars_possibly_in_scope,
$this->return_vars_possibly_in_scope[$return_type]
);
} else {
2016-08-14 05:26:45 +02:00
$this->return_vars_possibly_in_scope[$return_type] = $context->vars_possibly_in_scope;
}
}
/**
* @return null|string
*/
public function getMethodName()
{
if ($this->function instanceof ClassMethod) {
return (string)$this->function->name;
}
}
2016-08-14 05:26:45 +02:00
/**
* @param string|null $context_self
2017-05-27 02:16:18 +02:00
*
* @return string
2016-08-14 05:26:45 +02:00
*/
public function getMethodId($context_self = null)
2016-08-14 05:26:45 +02:00
{
2016-11-21 03:49:06 +01:00
if ($this->function instanceof ClassMethod) {
$function_name = (string)$this->function->name;
2016-11-21 20:36:06 +01:00
2017-01-07 20:35:07 +01:00
return ($context_self ?: $this->source->getFQCLN()) . '::' . strtolower($function_name);
2016-11-21 03:49:06 +01:00
}
if ($this->function instanceof Function_) {
return ($this->source->getNamespace() ? strtolower($this->source->getNamespace()) . '\\' : '') .
strtolower($this->function->name);
2016-08-14 05:26:45 +02:00
}
2016-11-02 07:29:00 +01:00
return $this->getFilePath() . ':' . $this->function->getLine() . ':' . 'closure';
2016-08-14 05:26:45 +02:00
}
2016-11-13 00:51:48 +01:00
/**
* @return array<string, string>
*/
public function getAliasedClassesFlipped()
{
if ($this->source instanceof NamespaceChecker ||
$this->source instanceof FileChecker ||
$this->source instanceof ClassLikeChecker
) {
2016-11-13 17:24:46 +01:00
return $this->source->getAliasedClassesFlipped();
}
return [];
2016-11-13 00:51:48 +01:00
}
2016-11-02 07:29:00 +01:00
/**
2017-01-07 20:35:07 +01:00
* @return string|null
2016-11-02 07:29:00 +01:00
*/
2016-11-08 01:16:51 +01:00
public function getFQCLN()
2016-08-14 05:26:45 +02:00
{
2017-01-07 20:35:07 +01:00
return $this->source->getFQCLN();
2016-08-14 05:26:45 +02:00
}
2016-11-02 07:29:00 +01:00
/**
* @return null|string
*/
2016-08-14 05:26:45 +02:00
public function getClassName()
{
2017-01-07 20:35:07 +01:00
return $this->source->getClassName();
2016-08-14 05:26:45 +02:00
}
/**
* @return string|null
*/
2017-01-07 20:35:07 +01:00
public function getParentFQCLN()
2016-08-14 05:26:45 +02:00
{
2017-01-07 20:35:07 +01:00
return $this->source->getParentFQCLN();
2016-08-14 05:26:45 +02:00
}
2016-11-02 07:29:00 +01:00
/**
* @return bool
*/
2016-08-14 05:26:45 +02:00
public function isStatic()
{
return $this->is_static;
}
2016-10-15 06:12:57 +02:00
/**
* @return StatementsSource
*/
2016-08-14 05:26:45 +02:00
public function getSource()
{
return $this->source;
}
/**
2016-12-07 20:13:39 +01:00
* @param bool $update_docblock
* @param Type\Union|null $return_type
* @param string $fq_class_name
2016-12-07 20:13:39 +01:00
* @param CodeLocation|null $return_type_location
* @param CodeLocation|null $secondary_return_type_location
2017-05-27 02:16:18 +02:00
*
2016-11-02 07:29:00 +01:00
* @return false|null
2016-08-14 05:26:45 +02:00
*/
public function verifyReturnType(
2016-12-07 20:13:39 +01:00
$update_docblock = false,
Type\Union $return_type = null,
$fq_class_name = null,
2016-12-07 20:13:39 +01:00
CodeLocation $return_type_location = null,
CodeLocation $secondary_return_type_location = null
) {
if (!$this->function->getStmts() &&
($this->function instanceof ClassMethod &&
($this->getSource() instanceof InterfaceChecker || $this->function->isAbstract())
)
) {
2016-11-02 07:29:00 +01:00
return null;
2016-08-14 05:26:45 +02:00
}
$is_to_string = $this->function instanceof ClassMethod && strtolower($this->function->name) === '__tostring';
if ($this->function instanceof ClassMethod &&
substr($this->function->name, 0, 2) === '__' &&
!$is_to_string
) {
2016-11-07 23:07:59 +01:00
// do not check __construct, __set, __get, __call etc.
return null;
2016-08-14 05:26:45 +02:00
}
2016-10-15 06:12:57 +02:00
$method_id = (string)$this->getMethodId();
2017-02-13 00:06:18 +01:00
$cased_method_id = null;
if ($this instanceof MethodChecker) {
$cased_method_id = MethodChecker::getCasedMethodId($this->file_checker->project_checker, $method_id);
2017-02-13 00:06:18 +01:00
} elseif ($this->function instanceof Function_) {
$cased_method_id = $this->function->name;
}
2016-08-14 05:26:45 +02:00
if (!$return_type_location) {
$return_type_location = new CodeLocation($this, $this->function, null, true);
}
$inferred_yield_types = [];
$inferred_return_types = EffectsAnalyser::getReturnTypes(
$this->function->getStmts(),
$inferred_yield_types,
$ignore_nullable_issues,
true
);
$inferred_return_type = $inferred_return_types ? Type::combineTypes($inferred_return_types) : Type::getVoid();
$inferred_yield_type = $inferred_yield_types ? Type::combineTypes($inferred_yield_types) : null;
$inferred_generator_return_type = null;
if ($inferred_yield_type) {
$inferred_generator_return_type = $inferred_return_type;
$inferred_return_type = $inferred_yield_type;
}
if (!$return_type && !Config::getInstance()->add_void_docblocks && $inferred_return_type->isVoid()) {
return null;
}
$project_checker = $this->getFileChecker()->project_checker;
$inferred_return_type = TypeChecker::simplifyUnionType(
$project_checker,
ExpressionChecker::fleshOutType(
$project_checker,
$inferred_return_type,
$this->source->getFQCLN(),
''
)
);
if (!$return_type && !$update_docblock && !$is_to_string) {
if ($this->function instanceof Closure) {
if (IssueBuffer::accepts(
new MissingClosureReturnType(
'Closure does not have a return type, expecting ' . $inferred_return_type,
new CodeLocation($this, $this->function, null, true)
),
$this->suppressed_issues
)) {
// fall through
}
return null;
}
2016-11-07 23:07:59 +01:00
if (IssueBuffer::accepts(
new MissingReturnType(
2017-01-28 06:44:52 +01:00
'Method ' . $cased_method_id . ' does not have a return type' .
(!$inferred_return_type->isMixed() ? ', expecting ' . $inferred_return_type : ''),
new CodeLocation($this, $this->function, null, true)
2016-11-07 23:07:59 +01:00
),
$this->suppressed_issues
)) {
// fall through
}
2016-11-02 07:29:00 +01:00
return null;
2016-08-14 05:26:45 +02:00
}
if ($is_to_string) {
if (!$inferred_return_type->isMixed() && (string)$inferred_return_type !== 'string') {
if (IssueBuffer::accepts(
new InvalidToString(
'__toString methods must return a string, ' . $inferred_return_type . ' returned',
$secondary_return_type_location ?: $return_type_location
)
)) {
return false;
}
}
if (!$return_type && !$update_docblock) {
return null;
}
}
if (!$return_type) {
2016-11-13 05:59:31 +01:00
if ($inferred_return_type && !$inferred_return_type->isMixed()) {
$this->addDocblockReturnType($inferred_return_type);
2016-11-13 00:51:48 +01:00
}
return null;
}
2016-08-14 05:26:45 +02:00
// passing it through fleshOutTypes eradicates errant $ vars
$declared_return_type = ExpressionChecker::fleshOutType(
$project_checker,
$return_type,
2017-01-07 20:35:07 +01:00
$fq_class_name ?: $this->source->getFQCLN(),
2016-08-14 05:26:45 +02:00
$method_id
);
2016-11-13 05:59:31 +01:00
if (!$inferred_return_types && !$inferred_yield_types) {
2016-11-13 00:51:48 +01:00
if ($declared_return_type->isVoid()) {
return null;
}
2016-08-14 05:26:45 +02:00
2016-11-13 00:51:48 +01:00
if (ScopeChecker::onlyThrows($this->function->getStmts())) {
// if there's a single throw statement, it's presumably an exception saying this method is not to be
// used
return null;
}
2016-08-14 05:26:45 +02:00
2016-11-13 00:51:48 +01:00
if (IssueBuffer::accepts(
new InvalidReturnType(
2016-12-04 05:03:18 +01:00
'No return statements were found for method ' . $cased_method_id .
2016-11-13 00:51:48 +01:00
' but return type \'' . $declared_return_type . '\' was expected',
$secondary_return_type_location ?: $return_type_location
2016-11-13 00:51:48 +01:00
)
)) {
return false;
}
2016-08-14 05:26:45 +02:00
2016-11-13 00:51:48 +01:00
return null;
}
if (!$declared_return_type->isMixed()) {
$declared_return_type->check(
$this,
$secondary_return_type_location ?: $return_type_location,
$this->getSuppressedIssues(),
[],
false
);
}
2016-11-13 00:51:48 +01:00
if ($inferred_return_type && !$declared_return_type->isMixed()) {
2016-11-13 05:59:31 +01:00
if ($inferred_return_type->isVoid() && $declared_return_type->isVoid()) {
2016-11-13 00:51:48 +01:00
return null;
}
if ($inferred_return_type->isMixed() || $inferred_return_type->isEmpty()) {
2016-08-14 05:26:45 +02:00
if (IssueBuffer::accepts(
2016-11-13 00:51:48 +01:00
new MixedInferredReturnType(
'Could not verify return type \'' . $declared_return_type . '\' for ' .
$cased_method_id,
$secondary_return_type_location ?: $return_type_location
2016-11-13 00:51:48 +01:00
),
2017-01-07 20:35:07 +01:00
$this->suppressed_issues
2016-08-14 05:26:45 +02:00
)) {
return false;
}
2016-11-02 07:29:00 +01:00
return null;
2016-08-14 05:26:45 +02:00
}
if (!TypeChecker::isContainedBy(
$this->source->getFileChecker()->project_checker,
$inferred_return_type,
$declared_return_type,
$ignore_nullable_issues,
$has_scalar_match,
$type_coerced
)) {
2016-11-13 05:59:31 +01:00
if ($update_docblock) {
2017-05-27 02:05:57 +02:00
if (!in_array('InvalidReturnType', $this->suppressed_issues, true)) {
$this->addDocblockReturnType($inferred_return_type);
}
2016-08-14 05:26:45 +02:00
2016-11-13 05:59:31 +01:00
return null;
}
// is the declared return type more specific than the inferred one?
if ($type_coerced) {
if (IssueBuffer::accepts(
new MoreSpecificReturnType(
'The declared return type \'' . $declared_return_type . '\' for ' . $cased_method_id .
' is more specific than the inferred return type \'' . $inferred_return_type . '\'',
$secondary_return_type_location ?: $return_type_location
),
$this->suppressed_issues
)) {
return false;
}
} else {
if (IssueBuffer::accepts(
new InvalidReturnType(
'The declared return type \'' . $declared_return_type . '\' for ' . $cased_method_id .
' is incorrect, got \'' . $inferred_return_type . '\'',
$secondary_return_type_location ?: $return_type_location
),
$this->suppressed_issues
)) {
return false;
}
2016-08-14 05:26:45 +02:00
}
} elseif (!$inferred_return_type->isNullable() && $declared_return_type->isNullable()) {
if ($update_docblock) {
2017-05-27 02:05:57 +02:00
if (!in_array('InvalidReturnType', $this->suppressed_issues, true)) {
$this->addDocblockReturnType($inferred_return_type);
}
return null;
}
if (IssueBuffer::accepts(
new LessSpecificReturnType(
'The inferred return type \'' . $inferred_return_type . '\' for ' . $cased_method_id .
' is more specific than the declared return type \'' . $declared_return_type . '\'',
$secondary_return_type_location ?: $return_type_location
),
$this->suppressed_issues
)) {
return false;
}
}
2016-08-14 05:26:45 +02:00
}
2016-11-02 07:29:00 +01:00
return null;
2016-08-14 05:26:45 +02:00
}
/**
* @param Type\Union $inferred_return_type
2017-05-27 02:16:18 +02:00
*
* @return void
*/
private function addDocblockReturnType(Type\Union $inferred_return_type)
{
FileMutator::addDocblockReturnType(
$this->source->getFilePath(),
$this->function->getLine(),
(string)$this->function->getDocComment(),
$inferred_return_type->toNamespacedString(
$this->source->getAliasedClassesFlipped(),
$this->source->getFQCLN(),
false
),
$inferred_return_type->toNamespacedString(
$this->source->getAliasedClassesFlipped(),
$this->source->getFQCLN(),
true
)
);
}
2016-10-15 06:12:57 +02:00
/**
* @param \ReflectionParameter $param
2017-05-27 02:16:18 +02:00
*
2016-10-15 06:12:57 +02:00
* @return FunctionLikeParameter
*/
protected static function getReflectionParamData(\ReflectionParameter $param)
2016-08-14 05:26:45 +02:00
{
$param_type_string = null;
if ($param->isArray()) {
$param_type_string = 'array';
2016-11-02 07:29:00 +01:00
} else {
2016-08-14 05:26:45 +02:00
$param_class = null;
try {
2016-10-15 06:12:57 +02:00
/** @var \ReflectionClass */
2016-08-14 05:26:45 +02:00
$param_class = $param->getClass();
2016-11-02 07:29:00 +01:00
} catch (\ReflectionException $e) {
2016-08-14 05:26:45 +02:00
// do nothing
}
if ($param_class) {
2016-10-15 06:12:57 +02:00
$param_type_string = (string)$param_class->getName();
2016-08-14 05:26:45 +02:00
}
}
$is_nullable = false;
2016-10-15 06:12:57 +02:00
$is_optional = (bool)$param->isOptional();
2016-08-14 05:26:45 +02:00
try {
$is_nullable = $param->getDefaultValue() === null;
if ($param_type_string && $is_nullable) {
$param_type_string .= '|null';
}
2016-11-02 07:29:00 +01:00
} catch (\ReflectionException $e) {
2016-08-14 05:26:45 +02:00
// do nothing
}
2016-10-15 06:12:57 +02:00
$param_name = (string)$param->getName();
2016-08-14 05:26:45 +02:00
$param_type = $param_type_string ? Type::parseString($param_type_string) : Type::getMixed();
return new FunctionLikeParameter(
$param_name,
2016-10-15 06:12:57 +02:00
(bool)$param->isPassedByReference(),
$param_type,
null,
2016-10-10 07:35:12 +02:00
$is_optional,
$is_nullable,
$param->isVariadic()
);
2016-08-14 05:26:45 +02:00
}
2016-10-14 06:53:43 +02:00
/**
2017-02-10 02:35:17 +01:00
* @param string $return_type
* @param StatementsSource $source
* @param array<string, string>|null $template_types
2017-05-27 02:16:18 +02:00
*
2016-10-14 06:53:43 +02:00
* @return string
*/
2017-02-10 02:35:17 +01:00
public static function fixUpLocalType(
$return_type,
Refactor scanning and analysis, introducing multithreading (#191) * Add failing test * Add visitor to soup up classlike references * Move a whole bunch of code into the visitor * Move some methods back, move onto analysis stage * Use the getAliases method everywhere * Fix refs * Fix more refs * Fix some tests * Fix more tests * Fix include tests * Shift config class finding to project checker and fix bugs * Fix a few more tests * transition test to new syntax * Remove var_dump * Delete a bunch of code and fix mutation test * Remove unnecessary visitation * Transition to better mocked out file provider, breaking some cached statement loading * Use different scheme for naming anonymous classes * Fix anonymous class issues * Refactor file/statement loading * Add specific property types * Fix mapped property assignment * Improve how we deal with traits * Fix trait checking * Pass Psalm checks * Add multi-process support * Delay console output until the end * Remove PHP 7 syntax * Update file storage with classes * Fix scanning individual files and add reflection return types * Always turn XDebug off * Add quicker method of getting method mutations * Queue return types for crawling * Interpret all strings as possible classes once we see a `get_class` call * Check invalid return types again * Fix template namespacing issues * Default to class-insensitive file names for includes * Don’t overwrite existing issues data * Add var docblocks for scanning * Add null check * Fix loading of external classes in templates * Only try to populate class when we haven’t yet seen it’s not a class * Fix trait property accessibility * Only ever improve docblock param type * Make param replacement more robust * Fix static const missing inferred type * Fix a few more tests * Register constant definitions * Fix trait aliasing * Skip constant type tests for now * Fix linting issues * Make sure caching is off for tests * Remove unnecessary return * Use emulative parser if on PHP 5.6 * Cache parser for faster first-time parse * Fix constant resolution when scanning classes * Remove test that’s beyond a practical scope * Add back --diff support * Add --help for --threads * Remove unused vars
2017-07-25 22:11:02 +02:00
Aliases $aliases,
2017-02-10 02:35:17 +01:00
array $template_types = null
) {
2016-08-14 05:26:45 +02:00
if (strpos($return_type, '[') !== false) {
$return_type = Type::convertSquareBrackets($return_type);
}
$return_type_tokens = Type::tokenize($return_type);
foreach ($return_type_tokens as $i => &$return_type_token) {
2016-08-14 05:26:45 +02:00
if ($return_type_token[0] === '\\') {
$return_type_token = substr($return_type_token, 1);
continue;
}
2017-05-27 02:05:57 +02:00
if (in_array($return_type_token, ['<', '>', '|', '?', ',', '{', '}', ':'], true)) {
continue;
}
if (isset($return_type_tokens[$i + 1]) && $return_type_tokens[$i + 1] === ':') {
2016-08-14 05:26:45 +02:00
continue;
}
$return_type_token = Type::fixScalarTerms($return_type_token);
2017-02-10 02:35:17 +01:00
if ($return_type_token[0] === strtoupper($return_type_token[0]) &&
!isset($template_types[$return_type_token])
) {
if ($return_type_token[0] === '$') {
if ($return_type === '$this') {
$return_type_token = 'static';
}
2016-08-14 05:26:45 +02:00
continue;
}
2016-11-08 01:16:51 +01:00
$return_type_token = ClassLikeChecker::getFQCLNFromString(
2016-11-02 07:29:00 +01:00
$return_type_token,
Refactor scanning and analysis, introducing multithreading (#191) * Add failing test * Add visitor to soup up classlike references * Move a whole bunch of code into the visitor * Move some methods back, move onto analysis stage * Use the getAliases method everywhere * Fix refs * Fix more refs * Fix some tests * Fix more tests * Fix include tests * Shift config class finding to project checker and fix bugs * Fix a few more tests * transition test to new syntax * Remove var_dump * Delete a bunch of code and fix mutation test * Remove unnecessary visitation * Transition to better mocked out file provider, breaking some cached statement loading * Use different scheme for naming anonymous classes * Fix anonymous class issues * Refactor file/statement loading * Add specific property types * Fix mapped property assignment * Improve how we deal with traits * Fix trait checking * Pass Psalm checks * Add multi-process support * Delay console output until the end * Remove PHP 7 syntax * Update file storage with classes * Fix scanning individual files and add reflection return types * Always turn XDebug off * Add quicker method of getting method mutations * Queue return types for crawling * Interpret all strings as possible classes once we see a `get_class` call * Check invalid return types again * Fix template namespacing issues * Default to class-insensitive file names for includes * Don’t overwrite existing issues data * Add var docblocks for scanning * Add null check * Fix loading of external classes in templates * Only try to populate class when we haven’t yet seen it’s not a class * Fix trait property accessibility * Only ever improve docblock param type * Make param replacement more robust * Fix static const missing inferred type * Fix a few more tests * Register constant definitions * Fix trait aliasing * Skip constant type tests for now * Fix linting issues * Make sure caching is off for tests * Remove unnecessary return * Use emulative parser if on PHP 5.6 * Cache parser for faster first-time parse * Fix constant resolution when scanning classes * Remove test that’s beyond a practical scope * Add back --diff support * Add --help for --threads * Remove unused vars
2017-07-25 22:11:02 +02:00
$aliases
2016-11-02 07:29:00 +01:00
);
2016-08-14 05:26:45 +02:00
}
}
return implode('', $return_type_tokens);
}
2016-08-22 21:00:12 +02:00
/**
2016-12-17 06:48:31 +01:00
* @param string $method_id
* @param array<int, PhpParser\Node\Arg> $args
2017-05-27 02:16:18 +02:00
*
* @return array<int, FunctionLikeParameter>
*/
public static function getMethodParamsById(ProjectChecker $project_checker, $method_id, array $args)
2016-08-22 21:00:12 +02:00
{
$fq_class_name = strpos($method_id, '::') !== false ? explode('::', $method_id)[0] : null;
if ($fq_class_name && ClassLikeChecker::isUserDefined($project_checker, $fq_class_name)) {
$method_params = MethodChecker::getMethodParams($project_checker, $method_id);
2016-12-23 21:06:20 +01:00
return $method_params;
}
$declaring_method_id = MethodChecker::getDeclaringMethodId($project_checker, $method_id);
if (FunctionChecker::inCallMap($declaring_method_id ?: $method_id)) {
$function_param_options = FunctionChecker::getParamsFromCallMap($declaring_method_id ?: $method_id);
2016-12-23 21:06:20 +01:00
if ($function_param_options === null) {
throw new \UnexpectedValueException('Not expecting $function_param_options to be null');
}
2016-11-07 05:29:54 +01:00
return self::getMatchingParamsFromCallMapOptions($project_checker, $function_param_options, $args);
}
2016-12-23 21:06:20 +01:00
return MethodChecker::getMethodParams($project_checker, $method_id);
}
/**
* @param string $method_id
* @param array<int, PhpParser\Node\Arg> $args
2017-05-27 02:16:18 +02:00
*
* @return array<int, FunctionLikeParameter>
*/
public static function getFunctionParamsFromCallMapById(ProjectChecker $project_checker, $method_id, array $args)
{
2017-02-10 02:35:17 +01:00
$function_param_options = FunctionChecker::getParamsFromCallMap($method_id);
2017-02-10 02:35:17 +01:00
if ($function_param_options === null) {
throw new \UnexpectedValueException('Not expecting $function_param_options to be null');
2016-08-22 21:00:12 +02:00
}
return self::getMatchingParamsFromCallMapOptions($project_checker, $function_param_options, $args);
}
2017-05-25 04:07:49 +02:00
/**
* @param array<int, array<int, FunctionLikeParameter>> $function_param_options
* @param array<int, PhpParser\Node\Arg> $args
2017-05-27 02:16:18 +02:00
*
* @return array<int, FunctionLikeParameter>
*/
protected static function getMatchingParamsFromCallMapOptions(
ProjectChecker $project_checker,
array $function_param_options,
array $args
) {
2016-08-22 21:00:12 +02:00
if (count($function_param_options) === 1) {
return $function_param_options[0];
}
foreach ($function_param_options as $possible_function_params) {
$all_args_match = true;
2016-11-02 07:29:00 +01:00
$last_param = count($possible_function_params)
? $possible_function_params[count($possible_function_params) - 1]
: null;
2016-10-26 17:51:59 +02:00
$mandatory_param_count = count($possible_function_params);
foreach ($possible_function_params as $i => $possible_function_param) {
if ($possible_function_param->is_optional) {
$mandatory_param_count = $i;
break;
}
}
if ($mandatory_param_count > count($args)) {
continue;
}
2016-08-22 21:00:12 +02:00
foreach ($args as $argument_offset => $arg) {
if ($argument_offset >= count($possible_function_params)) {
if (!$last_param || !$last_param->is_variadic) {
$all_args_match = false;
}
2016-08-22 21:00:12 +02:00
break;
}
$param_type = $possible_function_params[$argument_offset]->type;
2016-08-22 21:00:12 +02:00
if (!$param_type) {
continue;
}
2016-08-22 21:00:12 +02:00
if (!isset($arg->value->inferredType)) {
continue;
}
2016-10-11 04:49:43 +02:00
if ($arg->value->inferredType->isMixed()) {
continue;
}
if (TypeChecker::isContainedBy($project_checker, $arg->value->inferredType, $param_type)) {
2016-10-11 04:49:43 +02:00
continue;
2016-08-22 21:00:12 +02:00
}
$all_args_match = false;
break;
}
if ($all_args_match) {
return $possible_function_params;
}
}
// if we don't succeed in finding a match, set to the first possible and wait for issues below
return $function_param_options[0];
}
2017-01-07 20:35:07 +01:00
/**
* Get a list of suppressed issues
*
* @return array<string>
*/
public function getSuppressedIssues()
{
return $this->suppressed_issues;
}
2017-07-26 22:09:09 +02:00
/**
* Adds a suppressed issue, useful when creating a method checker from scratch
*
2017-07-27 05:47:29 +02:00
* @param string $issue_name
*
2017-07-26 22:09:09 +02:00
* @return void
*/
2017-07-27 05:47:29 +02:00
public function addSuppressedIssue($issue_name)
2017-07-26 22:09:09 +02:00
{
$this->suppressed_issues[] = $issue_name;
}
/**
* @return void
*/
public static function clearCache()
{
self::$no_effects_hashes = [];
}
public function getFileChecker()
{
return $this->file_checker;
}
2016-08-14 05:26:45 +02:00
}