forked from hhvm/hhast
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnusedParameterLinter.hack
More file actions
99 lines (86 loc) · 2.56 KB
/
Copy pathUnusedParameterLinter.hack
File metadata and controls
99 lines (86 loc) · 2.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/*
* Copyright (c) 2017-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
namespace Facebook\HHAST;
use namespace HH\Lib\Str;
final class UnusedParameterLinter extends AutoFixingASTLinter {
const type TConfig = shape();
const type TNode = ParameterDeclaration;
const type TContext = IFunctionishDeclaration;
<<__Override>>
public function getLintErrorForNode(
IFunctionishDeclaration $functionish,
ParameterDeclaration $node,
): ?ASTLintError {
if ($node->getVisibility() !== null) {
// Constructor parameter promotion
return null;
}
$name_node = $node->getName();
if (!$name_node is VariableToken) {
return null;
}
$name = $name_node->getText();
if (Str\starts_with($name, '$_')) {
return null;
}
// If this is a parameter of a lambda function, we should be looking in the
// lambda's body, not the enclosing function/method's body.
$lambda =
$functionish->getClosestAncestorOfDescendantOfType<LambdaExpression>(
$node,
);
if ($lambda is nonnull) {
$body = $lambda->getBody();
} else if ($functionish is FunctionDeclaration) {
$body = $functionish->getBody();
} else if ($functionish is MethodishDeclaration) {
$body = $functionish->getFunctionBody();
} else {
invariant_violation(
"Couldn't find functionish for parameter declaration",
);
}
if ($body === null || $body is SemicolonToken) {
// Don't require `$_` for abstract or interface methods
return null;
}
foreach ($body->traverse() as $var) {
if (!$var is VariableToken) {
continue;
}
if ($var->getText() === $name) {
return null;
}
}
return new ASTLintError(
$this,
'Parameter is unused',
$node,
() ==> $this->getFixedNode($node),
);
}
public function getFixedNode(
ParameterDeclaration $node,
): ParameterDeclaration {
$name = $node->getName();
if (!$name is VariableToken) {
return $node;
}
return $node->withName(
$name->withText('$_'.Str\strip_prefix($name->getText(), '$')),
);
}
<<__Override>>
public function getTitleForFix(ASTLintError $err): string {
$name = ($err->getBlameNode() as this::TNode)->getName();
invariant($name is VariableToken, 'unhandled type');
$new_name = '$_'.Str\strip_prefix($name->getText(), '$');
return Str\format('Rename to `%s`', $new_name);
}
}