forked from hhvm/hhast
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNoFinalMethodInFinalClassLinter.hack
More file actions
87 lines (73 loc) · 2.65 KB
/
Copy pathNoFinalMethodInFinalClassLinter.hack
File metadata and controls
87 lines (73 loc) · 2.65 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
/*
* 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\{C, Str};
final class NoFinalMethodInFinalClassLinter extends AutoFixingASTLinter {
const type TConfig = shape();
const type TNode = MethodishDeclaration;
const type TContext = ClassishDeclaration;
<<__Override>>
public function getLintErrorForNode(
ClassishDeclaration $class,
MethodishDeclaration $method,
): ?ASTLintError {
$class_modifiers = $class->getModifiers() ?? new NodeList();
if (!self::hasFinalModifier($class_modifiers)) {
return null;
}
$function_modifiers = $method->getFunctionDeclHeader()->getModifiers() ??
new NodeList();
if (!self::hasFinalModifier($function_modifiers)) {
return null;
}
return new ASTLintError(
$this,
Str\format(
'Method %s is final in the class %s, which is also final. This is redundant.',
Str\trim($method->getFunctionDeclHeader()->getName()->getCode()),
Str\trim($class->getName()->getCode()),
),
$method,
() ==> $this->getFixedNode($method),
);
}
<<__Override>>
public function getTitleForFix(SingleRuleLintError $_): string {
return 'Remove final from method';
}
public function getFixedNode(
MethodishDeclaration $method,
): MethodishDeclaration {
$function_decl_header = $method->getFunctionDeclHeader();
$modifiers = $function_decl_header->getModifiers() as nonnull;
$final = $modifiers
->filterChildren($modifier ==> $modifier is FinalToken)
->getFirstTokenx();
$next_token = $this->getAST()->getNextToken($final);
invariant($next_token is nonnull, 'Could not find token after final');
$decl_without_final = $function_decl_header->withModifiers(
$modifiers->filterChildren($modifier ==> !$modifier is FinalToken),
);
$final_trivia = $final->getTrailing()->getCode() === ' '
// In the /common/ case that final only has one trailing space,
// ignore it for nicer diffs.
? $final->getLeading()
: NodeList::concat($final->getLeading(), $final->getTrailing());
$decl_without_final = $decl_without_final->replace(
$next_token,
$next_token->withLeading(
NodeList::concat($final_trivia, $next_token->getLeading()),
),
);
return $method->withFunctionDeclHeader($decl_without_final);
}
private static function hasFinalModifier(NodeList<Token> $modifiers): bool {
return C\any($modifiers->toVec(), $token ==> $token is FinalToken);
}
}