forked from hhvm/hhast
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDontHaveTwoEmptyLinesInARowLinter.hack
More file actions
100 lines (87 loc) · 2.54 KB
/
Copy pathDontHaveTwoEmptyLinesInARowLinter.hack
File metadata and controls
100 lines (87 loc) · 2.54 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
100
/*
* 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 DontHaveTwoEmptyLinesInARowLinter extends AutoFixingASTLinter {
const type TConfig = shape();
const type TContext = Script;
const type TNode = Token;
<<__Override>>
public function getLintErrorForNode(
this::TContext $context,
this::TNode $token,
): ?ASTLintError {
if ($this->entireScriptIsClean($context)) {
return null;
}
if (!Str\contains($token->getCode(), \PHP_EOL.\PHP_EOL)) {
// We check for 2 eols, because the previous token may have the first.
return null;
}
$eol_count = $this->getAST()
->getPreviousToken($token)
?->getTrailing()
?->getLast()
|> $$ is EndOfLine ? 1 : 0;
$remove_leading = vec[];
$remove_trailing = vec[];
foreach ($token->getLeading()->toVec() as $trivia) {
if ($trivia is EndOfLine) {
$eol_count++;
if ($eol_count >= 3) {
$remove_leading[] = $trivia;
}
} else {
$eol_count = 0;
}
}
// We don't check the boundary with the next token.
// This will be checked by the loop above when linting
// that token instead.
$eol_count = 0;
foreach ($token->getTrailing()->toVec() as $trivia) {
if ($trivia is EndOfLine) {
$eol_count++;
if ($eol_count >= 3) {
$remove_trailing[] = $trivia;
}
} else {
$eol_count = 0;
}
}
if (C\is_empty($remove_leading) && C\is_empty($remove_trailing)) {
return null;
}
return new ASTLintError(
$this,
"Don't have two empty lines in a row",
$token,
() ==> static::removeTrivia($token, $remove_leading, $remove_trailing),
);
}
<<__Memoize>>
private function entireScriptIsClean(Script $script): bool {
return !Str\contains($script->getCode(), \PHP_EOL.\PHP_EOL.\PHP_EOL);
}
private static function removeTrivia(
this::TNode $token,
vec<Trivia> $leading_trivia,
vec<Trivia> $trailing_trivia,
): this::TNode {
$leading = $token->getLeading();
foreach ($leading_trivia as $t) {
$leading = $leading->withoutChild($t);
}
$trailing = $token->getTrailing();
foreach ($trailing_trivia as $t) {
$trailing = $trailing->withoutChild($t);
}
return $token->withLeading($leading)->withTrailing($trailing);
}
}