-
Notifications
You must be signed in to change notification settings - Fork 0
/
NoPHPEqualityLinter.hack
75 lines (66 loc) · 2.04 KB
/
NoPHPEqualityLinter.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
/*
* 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 NoPHPEqualityLinter extends AutoFixingASTLinter {
const type TConfig = shape();
const type TNode = BinaryExpression;
/**
* Changing `==` to `===` and `!=` to `!==` may change
* the behavior of the code.
* `keyset[1, 2] == keyset[2, 1]` is true, but
* `keyset[1, 2] === keyset[2, 1]` is false.
* Each case should be considered individually.
*/
use UnsafeBulkAutoFixesTrait;
<<__Override>>
protected function getTitleForFix(ASTLintError $err): string {
$blame = $err->getBlameNode() as this::TNode;
$fixed = $err->getFixedNode() as this::TNode;
return Str\format(
'Replace `%s` with `%s`',
$blame->getOperator()->getText(),
$fixed->getOperator()->getText(),
);
}
const type TContext = Script;
<<__Override>>
public function getLintErrorForNode(
Script $_context,
BinaryExpression $expr,
): ?ASTLintError {
$token = $expr->getOperator();
$replacement = null;
if ($token is EqualEqualToken) {
$replacement = '===';
} else if ($token is ExclamationEqualToken) {
$replacement = '!==';
} else {
return null;
}
return new ASTLintError(
$this,
'Do not use PHP equality - use "'.$replacement.'" instead.',
$expr,
() ==> $this->getFixedNode($expr),
);
}
public function getFixedNode(BinaryExpression $expr): BinaryExpression {
$op = $expr->getOperator();
if ($op is EqualEqualToken) {
$op = new EqualEqualEqualToken($op->getLeading(), $op->getTrailing());
} else if ($op is ExclamationEqualToken) {
$op =
new ExclamationEqualEqualToken($op->getLeading(), $op->getTrailing());
} else {
invariant_violation("Shouldn't be asked to fix non-equality operators");
}
return $expr->withOperator($op);
}
}