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 pathGroupUseStatementAlphabetizationLinter.hack
99 lines (93 loc) · 2.86 KB
/
GroupUseStatementAlphabetizationLinter.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
/*
* 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, Dict, Str, Vec};
final class GroupUseStatementAlphabetizationLinter extends AutoFixingASTLinter {
const type TConfig = shape();
const type TNode = NamespaceGroupUseDeclaration;
const type TContext = Script;
<<__Override>>
public function getLintErrorForNode(
Script $_context,
NamespaceGroupUseDeclaration $node,
): ?ASTLintError {
// NamespaceGroupUseDeclaration has the following structure:
//
// NodeList
// ListItem
// NamespaceUseClause
// NameToken
// CommaToken
//
// Save the NodeList containing the NamespaceUseClauses and the whole
// ListItems (including CommaToken) as we want to preserve trivia as we
// reorder, especially for comments such as:
//
// use type Foo\{
// Baz,
// Bar, // we want this comment to always belong to "Bar"
// }
$items = dict[];
$list = $node->getClauses();
foreach ($list->toVec() as $item) {
$name = $item->getItem()->getName();
$str = $name->getDescendantsByType<NameToken>()
|> Vec\map($$, $t ==> $t->getText())
|> Str\join($$, '\\');
$items[$str] = $item;
}
$sorted = Dict\sort_by_key($items);
if ($sorted === $items) {
return null;
}
return new ASTLintError(
$this,
'Group use statements should be sorted alphabetically',
$node,
() ==> $this->getFixedNode($node, $sorted),
);
}
public function getFixedNode(
NamespaceGroupUseDeclaration $node,
dict<string, ListItem<NamespaceUseClause>> $sorted_clauses,
): NamespaceGroupUseDeclaration {
if (!C\any($sorted_clauses, $c ==> Str\contains($c->getCode(), "\n"))) {
// we want `use {foo, bar, baz}`; no trailng comma
$last = C\lastx($sorted_clauses);
$clauses = Vec\map(
$sorted_clauses,
$clause ==> {
if ($clause === $last) {
return $clause->withSeparator(null);
}
return $clause->hasSeparator()
? $clause
: $clause->withSeparator(
new CommaToken(null, new NodeList(vec[new WhiteSpace(' ')])),
);
},
);
} else {
// we want use `{\n foo,\n bar,\n}` etc
$clauses = Vec\map(
$sorted_clauses,
$clause ==> {
if ($clause->hasSeparator()) {
return $clause;
}
$t = $clause->getLastTokenx();
$trailing = $t->getTrailing();
return $clause->replace($t, $t->withTrailing(null))
->withSeparator(new CommaToken(null, $trailing));
},
);
}
return $node->withClauses(new NodeList($clauses));
}
}