forked from hhvm/hhast
-
Notifications
You must be signed in to change notification settings - Fork 0
/
UseStatementWithLeadingBackslashLinter.hack
91 lines (83 loc) · 2.48 KB
/
UseStatementWithLeadingBackslashLinter.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
/*
* 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 UseStatementWithLeadingBackslashLinter extends AutoFixingASTLinter {
const type TNode = INamespaceUseDeclaration;
const type TContext = Script;
<<__Override>>
public function getLintErrorForNode(
Script $_context,
INamespaceUseDeclaration $node,
): ?ASTLintError {
$matched = false;
if ($node is NamespaceGroupUseDeclaration) {
$prefix = $node->getPrefix()->getFirstToken();
if (!$prefix is BackslashToken) {
return null;
}
$matched = true;
} else {
foreach ($node->getClausesx()->getChildrenOfItems() as $clause) {
$name = $clause->getName()->getFirstToken();
if ($name is BackslashToken) {
$matched = true;
break;
}
}
}
if (!$matched) {
return null;
}
return new ASTLintError(
$this,
'Leading backslashes on `use` statements do nothing',
$node,
() ==> $this->getFixedNode($node),
);
}
<<__Override>>
protected function getTitleForFix(LintError $_): string {
return 'Remove leading backslash';
}
public function getFixedNode(
INamespaceUseDeclaration $node,
): INamespaceUseDeclaration {
if ($node is NamespaceUseDeclaration) {
$clauses = $node->getClauses();
foreach ($clauses->getChildrenOfItems() as $clause) {
$name = $clause->getName();
if (!$name is QualifiedName) {
continue;
}
$first = C\firstx($name->getParts()->toVec());
if ($first->getItem() !== null) {
// null item means we just have a separator - a leading backslash
continue;
}
$clauses = $name->getParts()->withoutChild($first)
|> $name->withParts($$)
|> $clause->withName($$)
|> $clauses->replace($clause, $$);
}
return $node->withClauses($clauses);
}
invariant(
$node is NamespaceGroupUseDeclaration,
'Got an unexpected INamespaceUseDeclaration subclass',
);
$first = C\firstx($node->getPrefix()->getParts()->toVec());
if ($first->getItem() !== null) {
return $node;
}
return $node->getPrefix()->getParts()->withoutChild($first)
|> $node->getPrefix()->withParts($$)
|> $node->withPrefix($$);
}
}