This repository was archived by the owner on Dec 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathPreferLambdasLinter.hack
101 lines (87 loc) · 2.48 KB
/
PreferLambdasLinter.hack
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
100
101
/*
* 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;
final class PreferLambdasLinter extends AutoFixingASTLinter {
const type TConfig = shape();
const type TContext = Script;
const type TNode = AnonymousFunction;
<<__Override>>
protected function getTitleForFix(SingleRuleLintError $_): string {
return 'Convert to lambda';
}
<<__Override>>
public function getLintErrorForNode(
Script $_context,
AnonymousFunction $node,
): ?ASTLintError {
$use_expr = $node->getUse();
$uses_references = $use_expr is nonnull &&
C\any(
$use_expr->getDescendantsByType<PrefixUnaryExpression>(),
$expr ==> $expr->getOperator() is AmpersandToken,
);
if ($uses_references) {
return null;
}
return new ASTLintError(
$this,
'Use lambdas instead of PHP anonymous functions',
$node,
() ==> $this->getFixedNode($node),
);
}
public function getFixedNode(AnonymousFunction $node): ?Node {
$attribute_spec = $node->getAttributeSpec();
$async = $node->getAsyncKeyword();
$parameters = $node->getParameters();
$left_paren = new LeftParenToken(
$node->getFunctionKeyword()->getLeading(),
null,
);
$right_paren = $node->getRightParen();
$colon = $node->getColon();
$type = $node->getType();
$signature = new LambdaSignature(
$left_paren,
$parameters,
$right_paren,
// capabilities are not supported by anonymous functions
/* capability = */ null,
$colon,
null,
$type,
);
$arrow = new EqualEqualGreaterThanToken(
null,
new NodeList(vec[new WhiteSpace(' ')]),
);
$body = $this->simplifyBody($node->getBody());
return new LambdaExpression(
$attribute_spec,
$async,
$signature,
$arrow,
$body,
);
}
private function simplifyBody(CompoundStatement $body): ILambdaBody {
$statements = $body->getStatements()?->getChildren();
if ($statements is null || C\count($statements) !== 1) {
// Body has no statements, cannot be simplied.
return $body;
}
$statement = C\onlyx($statements);
if (!$statement is ReturnStatement) {
// Only a return statement can be simplified.
return $body;
}
return $statement->getExpressionx();
}
}