-
Notifications
You must be signed in to change notification settings - Fork 445
Expand file tree
/
Copy pathrules.py
More file actions
1167 lines (987 loc) · 39.9 KB
/
rules.py
File metadata and controls
1167 lines (987 loc) · 39.9 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Copyright 2023-2026 Hewlett Packard Enterprise Development LP
# Other additional copyright holders may be indicated within.
#
# The entirety of this work is licensed under the Apache License,
# Version 2.0 (the "License"); you may not use this file except
# in compliance with the License.
#
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import re
import typing
import chapel
from chapel import *
from driver import LintDriver
from fixits import Fixit, Edit
from rule_types import (
BasicRuleResult,
AdvancedRuleResult,
LocationRuleResult,
RuleLocation,
)
def variables(node: AstNode):
if isinstance(node, (Variable, Formal)):
if node.name() != "_":
yield node
elif isinstance(node, TupleDecl):
for child in node:
yield from variables(child)
def fixit_remove_unused_node(
node: AstNode,
lines: Optional[List[str]] = None,
context: Optional[Context] = None,
) -> Optional[Fixit]:
"""
Given an unused variable that's either a child of a TupleDecl or an
iterand in a loop, construct a Fixit that removes it or replaces it
with '_' as appropriate.
Expects either a lines list (containing the lines in the file where
the node is being fixed up) or a context object that will be used to
determine these lines. Raises if neither is provided.
"""
parent = node.parent()
if parent is None:
return None
if lines is None:
if context is None:
raise ValueError("Either 'lines' or 'context' must be provided")
else:
lines = chapel.get_file_lines(context, parent)
if parent and isinstance(parent, TupleDecl):
return Fixit.build(Edit.build(node.location(), "_"))
elif parent and isinstance(parent, IndexableLoop):
loc = parent.header_location() or parent.location()
before_loc = loc - node.location()
after_loc = loc.clamp_left(parent.iterand().location())
before_lines = range_to_text(before_loc, lines)
after_lines = range_to_text(after_loc, lines)
return Fixit.build(Edit.build(loc, before_lines + after_lines))
return None
def name_for_linting(
context: Context, node: NamedDecl, internal_prefixes: List[str] = []
) -> str:
name = node.name()
# Strip dollar signs.
name = name.replace("$", "")
# Strip internal prefixes.
for p in internal_prefixes:
if name.startswith(p):
name = name[len(p) :]
break
return name
def check_camel_case(
context: Context, node: NamedDecl, internal_prefixes: List[str] = []
):
return re.fullmatch(
r"([a-z]+([A-Z][a-z]*|\d+)*|[A-Z]+)?",
name_for_linting(context, node, internal_prefixes),
)
def check_pascal_case(
context: Context, node: NamedDecl, internal_prefixes: List[str] = []
):
return re.fullmatch(
r"(([A-Z][a-z]*|\d+)+|[A-Z]+)?",
name_for_linting(context, node, internal_prefixes),
)
def extract_only_bool(
parent: Conditional, node: Optional[Block]
) -> Optional[bool]:
if node is None:
return None
children = list(node)
if len(children) != 1:
return None
check_for_bool = children[0]
if not parent.is_expression_level():
if not isinstance(check_for_bool, Return):
return None
check_for_bool = check_for_bool.value()
if not isinstance(check_for_bool, BoolLiteral):
return None
return check_for_bool.value()
def rules(driver: LintDriver):
@driver.basic_rule(VarLikeDecl, default=False)
def CamelOrPascalCaseVariables(context: Context, node: VarLikeDecl):
"""
Warn for variables that are not 'camelCase' or 'PascalCase'.
"""
if node.name() == "_":
return True
if node.linkage() == "extern" and node.linkage_name() is None:
return True
internal_prefixes = driver.config.internal_prefixes
return check_camel_case(
context, node, internal_prefixes
) or check_pascal_case(context, node, internal_prefixes)
@driver.basic_rule(Record)
def CamelCaseRecords(context: Context, node: Record):
"""
Warn for records that are not 'camelCase'.
"""
if node.linkage() == "extern" and node.linkage_name() is None:
return True
internal_prefixes = driver.config.internal_prefixes
return check_camel_case(context, node, internal_prefixes)
@driver.basic_rule(Function)
def CamelCaseFunctions(context: Context, node: Function):
"""
Warn for functions that are not 'camelCase'.
"""
# Override functions / methods can't control the name, that's up
# to the parent.
if node.is_override():
return True
if node.linkage() == "extern" and node.linkage_name() is None:
return True
if node.kind() == "operator":
return True
if node.name() == "init=":
return True
internal_prefixes = driver.config.internal_prefixes
return check_camel_case(context, node, internal_prefixes)
@driver.basic_rule(Class)
def PascalCaseClasses(context: Context, node: Class):
"""
Warn for classes that are not 'PascalCase'.
"""
internal_prefixes = driver.config.internal_prefixes
return check_pascal_case(context, node, internal_prefixes)
@driver.basic_rule(Module)
def PascalCaseModules(context: Context, node: Module):
"""
Warn for modules that are not 'PascalCase'.
"""
internal_prefixes = driver.config.internal_prefixes
return node.kind() == "implicit" or check_pascal_case(
context, node, internal_prefixes
)
@driver.basic_rule(Module, default=False)
def UseExplicitModules(_, node: Module):
"""
Warn for code that relies on auto-inserted implicit modules.
"""
return node.kind() != "implicit"
@driver.basic_rule(Loop)
@driver.basic_rule(SimpleBlockLike)
@driver.basic_rule(When)
def DoKeywordAndBlock(
context: Context, node: typing.Union[Loop, SimpleBlockLike]
):
"""
Warn for redundant 'do' keyword before a curly brace '{'.
"""
check = node.block_style() != "unnecessary"
if not check:
return BasicRuleResult(node, ignorable=True)
return check
@driver.fixit(DoKeywordAndBlock)
def RemoveUnnecessaryDo(context: Context, result: BasicRuleResult):
"""
Remove the redundant 'do' keyword before a curly brace '{'.
"""
node = result.node
lines = chapel.get_file_lines(context, node)
if isinstance(node, Loop):
header_loc = node.header_location()
if isinstance(node, IndexableLoop) and node.with_clause():
with_ = node.with_clause()
assert with_ is not None
header_loc = header_loc + with_.location()
else:
header_loc = node.block_header()
body_loc = node.curly_braces_location()
if header_loc is None or body_loc is None:
return None
header_text = range_to_text(header_loc, lines)
body_text = range_to_text(body_loc, lines)
sep = " "
if header_loc.end()[0] != body_loc.start()[0]:
indent = " " * (body_loc.start()[1] - 1)
sep = "\n" + indent
new_text = header_text + sep + body_text
fixit = Fixit.build(Edit.build(node.location(), new_text))
return fixit
@driver.basic_rule(set((Loop, Conditional)))
def ControlFlowParentheses(
context: Context, node: typing.Union[Loop, Conditional]
):
"""
Warn for unnecessary parentheses in conditional statements and loops.
"""
subject = None
if isinstance(node, (DoWhile, While, Conditional)):
subject = node.condition()
elif isinstance(node, IndexableLoop):
subject = node.index()
# No supported node to examine for redundant parentheses.
if subject is None:
return True
# Tuples need their parentheses.
if isinstance(subject, Tuple):
return True
# No parentheses to speak of
paren_loc = subject.paren_location()
if paren_loc is None:
return True
# Now, we should warn: there's a node in a conditional or
# if/else, it has parentheses at the top level, but it doesn't need them.
return BasicRuleResult(subject, data=subject)
@driver.fixit(ControlFlowParentheses)
def RemoveControlFlowParentheses(context: Context, result: BasicRuleResult):
# Since we're here, these should already be non-None.
subject = result.data
assert subject
paren_loc = subject.paren_location()
assert paren_loc
# If parentheses span multiple lines, don't provide a fixit,
# since the indentation would need more thought.
start_line, start_col = paren_loc.start()
end_line, end_col = paren_loc.end()
if start_line != end_line:
return []
lines = chapel.get_file_lines(context, result.node)
new_text = range_to_text(paren_loc, lines)[1:-1]
start_line_str = lines[start_line - 1]
end_line_str = lines[end_line - 1]
# For 'if(x)', can't turn this into 'ifx', need an extra space.
if start_col > 1 and not start_line_str[start_col - 2].isspace():
new_text = " " + new_text
# Similarly, '(x)do', can't turn this into 'xdo', need an extra space.
if (
end_col < len(end_line_str)
and not end_line_str[end_col - 1].isspace()
):
new_text += " "
return [Fixit.build(Edit.build(paren_loc, new_text))]
@driver.basic_rule(chapel.OpCall)
def BoolComparison(context, node: chapel.OpCall):
"""
Warn for comparing booleans to 'true' or 'false'.
"""
op = node.op()
if op == "==" or op == "!=":
left = node.actual(0)
right = node.actual(1)
if isinstance(left, chapel.BoolLiteral):
return BasicRuleResult(node, data=(op, left, right))
elif isinstance(right, chapel.BoolLiteral):
return BasicRuleResult(node, data=(op, right, left))
return True
@driver.fixit(BoolComparison)
def FixBoolComparison(context, result: BasicRuleResult):
assert isinstance(result.data, tuple)
op, bool_lit, other = result.data
node = result.node
assert isinstance(node, chapel.OpCall)
lines = chapel.get_file_lines(context, node)
bool_value = bool_lit.value()
other_text = range_to_text(other.location(), lines)
if (op == "==" and bool_value) or (op == "!=" and not bool_value):
replacement = other_text
else:
already_has_parens = other.paren_location() is not None
needs_paren = not isinstance(
other, (chapel.FnCall, chapel.Identifier, chapel.Dot)
)
fmt = "!({0})" if needs_paren or already_has_parens else "!{0}"
replacement = fmt.format(other_text)
return [Fixit.build(Edit.build(node.location(), replacement))]
@driver.basic_rule(chapel.Conditional)
def SimpleBoolConditional(context, node: chapel.Conditional):
"""
Warn for boolean conditionals that can be simplified.
"""
then_ret = extract_only_bool(node, node.then_block())
else_ret = extract_only_bool(node, node.else_block())
if then_ret is None or else_ret is None:
return True
is_only_returns = not node.is_expression_level()
if then_ret != else_ret:
should_invert = not then_ret
return BasicRuleResult(
node,
ignorable=False,
data=(is_only_returns, should_invert, None),
)
else:
return BasicRuleResult(
node, ignorable=False, data=(is_only_returns, None, then_ret)
)
return True
@driver.fixit(SimpleBoolConditional)
def FixSimpleBoolConditional(context, result: BasicRuleResult):
assert isinstance(result.data, tuple)
is_only_returns, should_invert, replace_with_value = result.data
node = result.node
assert isinstance(node, chapel.Conditional)
condition = node.condition()
cond_loc = condition.location()
cond_loc_start_line, cond_loc_start_col = cond_loc.start()
_, cond_loc_end_col = cond_loc.end()
if replace_with_value is None:
# get the conditions text, using its location so we preserve comments
lines = chapel.get_file_lines(context, result.node)
condition_text = lines[cond_loc_start_line - 1][
cond_loc_start_col - 1 : cond_loc_end_col - 1
]
if should_invert:
condition_text = "!(" + condition_text + ")"
else:
condition_text = "true" if replace_with_value else "false"
if is_only_returns:
condition_text = "return " + condition_text + ";"
return [Fixit.build(Edit.build(node.location(), condition_text))]
@driver.basic_rule(Coforall, default=False)
def NestedCoforalls(context: Context, node: Coforall):
"""
Warn for nested 'coforall' loops, which could lead to performance hits.
"""
parent = node.parent()
while parent is not None:
if isinstance(parent, Coforall):
return False
parent = parent.parent()
return True
@driver.basic_rule([Conditional, BoolLiteral, chapel.rest])
def BoolLitInCondStmt(_: Context, node: Conditional):
"""
Warn for boolean literals like 'true' in a conditional statement.
"""
return BasicRuleResult(node.condition(), data=node)
# TODO: at some point, we should support a fixit that removes the
# conditions and the braces, but the way locations work right now makes
# that difficult. Blocks get built and rebuilt in the parser, making it
# hard to tag the resulting block with curky braces locations.
@driver.fixit(BoolLitInCondStmt)
def FixBoolLitInCondStmt_KeepBraces(
context: Context, result: BasicRuleResult
):
"""
Remove the unused branch of a conditional statement, keeping the braces.
"""
node = result.data
assert isinstance(node, Conditional)
lines = chapel.get_file_lines(context, node)
cond = node.condition()
assert isinstance(cond, BoolLiteral)
text = None
if cond.value():
text = range_to_text(node.then_block().location(), lines)
else:
else_block = node.else_block()
if else_block is not None:
text = range_to_text(else_block.location(), lines)
else:
text = ""
# should be set in all branches
assert text is not None
return Fixit.build(Edit.build(node.location(), text))
@driver.basic_rule(NamedDecl)
def ChplPrefixReserved(context: Context, node: NamedDecl):
"""
Warn for user-defined names that start with the 'chpl\\_' reserved prefix.
"""
if node.linkage() == "extern":
return True
if node.name().startswith("chpl_"):
path = node.location().path()
return context.is_bundled_path(path)
return True
@driver.basic_rule(Record)
@driver.basic_rule(Class)
def MethodsAfterFields(context: Context, node: typing.Union[Record, Class]):
"""
Warn for classes or records that mix field and method definitions.
"""
method_seen = False
for child in node:
if isinstance(child, VarLikeDecl) and method_seen:
return BasicRuleResult(node, ignorable=True)
if isinstance(child, Function):
method_seen = True
return True
@driver.basic_rule(EmptyStmt)
def EmptyStmts(_, node: EmptyStmt):
"""
Warn for empty statements (i.e., unnecessary semicolons).
"""
p = node.parent()
if p:
if isinstance(p, SimpleBlockLike) and len(list(p.stmts())) == 1:
# dont warn if the EmptyStmt is the only statement in a block
return True
if (
isinstance(p, Module)
and p.kind() == "implicit"
and len(list(p)) == 1
):
# dont warn if the EmptyStmt is the only statement in an implicit module
return True
return BasicRuleResult(
node, fixits=Fixit.build(Edit.build(node.location(), ""))
)
@driver.basic_rule(TupleDecl)
def UnusedTupleUnpack(context: Context, node: TupleDecl):
"""
Warn for unused tuple unpacking, such as '(_, _)'.
"""
varset = set(variables(node))
if len(varset) == 0:
fixit = fixit_remove_unused_node(node, context=context)
if fixit is not None:
return BasicRuleResult(node, fixits=fixit)
return False
return True
@driver.basic_rule(OpCall)
def ComplexLiteralOrder(context: Context, node: OpCall):
"""
Warn for complex literals that are not in a consistent order.
"""
complex_lit = chapel.is_complex_literal(node)
if not complex_lit:
return True
# If the first element is not the imaginary literal, then we have
# 10+2i, which is the correct order.
if not isinstance(complex_lit[0], ImagLiteral):
return True
# Eventually, auto-fixit will go here. For now, just warn.
return False
# Five things have to match between consecutive decls for this to warn:
# 1. same type
# 2. same kind
# 3. same attributes
# 4. same linkage
# 5. same pragmas
@driver.advanced_rule(default=False)
def ConsecutiveDecls(_, root: AstNode):
"""
Warn for consecutive variable declarations that can be combined.
"""
def is_relevant_decl(node):
var_node = None
if isinstance(node, MultiDecl):
for child in node:
if isinstance(child, Variable):
var_node = child
else:
return None
elif isinstance(node, Variable):
var_node = node
else:
return None
var_type = None
var_type_expr = var_node.type_expression()
if isinstance(var_type_expr, FnCall):
# for function call, we need to match all the components
var_type = ""
for child in var_type_expr:
if child is None:
continue
if "name" in dir(child):
var_type += child.name()
elif "text" in dir(child):
var_type += child.text()
elif isinstance(var_type_expr, Identifier):
var_type = var_type_expr.name()
var_kind = var_node.kind()
var_attributes = ""
var_attribute_group = var_node.attribute_group()
if var_attribute_group:
var_attributes = " ".join(
[a.name() for a in var_attribute_group if a is not None]
)
var_linkage = var_node.linkage()
var_pragmas = " ".join(var_node.pragmas())
return var_type, var_kind, var_attributes, var_linkage, var_pragmas
def recurse(node):
consecutive = []
last_characteristics = None
for child in node:
# we want to skip Comments entirely
if isinstance(child, Comment):
continue
# we want to do MultiDecls and TupleDecls, but not recurse
skip_children = isinstance(child, (MultiDecl, TupleDecl))
if not skip_children:
yield from recurse(child)
new_characteristics = is_relevant_decl(child)
compatible = (
new_characteristics is not None
and new_characteristics == last_characteristics
)
last_characteristics = new_characteristics
if compatible:
consecutive.append(child)
else:
# this one doesn't match, yield any from previous sequence
# and start looking for matches for this one
if len(consecutive) > 1:
yield consecutive[1]
consecutive = [child]
if len(consecutive) > 1:
yield consecutive[1]
yield from recurse(root)
@driver.advanced_rule
def MisleadingIndentation(context: Context, root: AstNode):
"""
Warn for single-statement blocks that look like they might be multi-statement blocks.
"""
if isinstance(root, Comment):
return
prev = []
fix = None
for child in root:
if isinstance(child, Comment):
continue
yield from MisleadingIndentation(context, child)
if prev and any(
p.location().start()[1] == child.location().start()[1]
for p in prev
):
yield AdvancedRuleResult(child, fix)
prev = []
fix = append_nested_single_stmt(child, prev)
def append_nested_single_stmt(node, prev: List[AstNode]):
if isinstance(node, Loop) and node.block_style() == "implicit":
children = list(node)
# safe to access [-1], loops must have at least 1 child
inblock = reversed(list(children[-1]))
elif isinstance(node, On) and node.block_style() == "implicit":
inblock = node.stmts()
else:
# Should we also check for Conditionals here?
return None
for stmt in inblock:
if isinstance(stmt, Comment):
continue
prev.append(stmt)
append_nested_single_stmt(stmt, prev)
return node # Return the outermost on to use an anchor
return None
@driver.fixit(MisleadingIndentation)
def FixMisleadingIndentation(context: Context, result: AdvancedRuleResult):
"""
Align second statement to be outside of the loop.
"""
assert isinstance(result.anchor, AstNode)
prevloop_loc = result.anchor.location()
loc = result.node.location()
lines = chapel.get_file_lines(context, result.node)
fixit = None
# only apply the fixit when the fix is to indent `child`
# and `child ` is a single line
if (
loc.start()[1] != prevloop_loc.start()[1]
and loc.start()[0] == loc.end()[0]
):
line_start = (loc.start()[0], 1)
parent_indent = max(prevloop_loc.start()[1] - 1, 0)
text = " " * parent_indent + range_to_text(loc, lines)
fixit = Fixit.build(Edit(loc.path(), line_start, loc.end(), text))
return [fixit] if fixit else []
@driver.advanced_rule
def UnusedFormal(context: Context, root: AstNode):
"""
Warn for unused formals in functions.
"""
if isinstance(root, Comment):
return
formals = dict()
uses = set()
for formal, _ in chapel.each_matching(root, Formal):
# For now, it's harder to tell if we're ignoring 'this' formals
# (what about method calls with implicit receiver?). So skip
# 'this' formals.
if formal.name() == "this":
continue
# ignore `_`, like from a TupleDecl
if formal.name() == "_":
continue
# extern functions have no bodies that can use their formals.
parent = formal.parent()
if isinstance(parent, NamedDecl) and parent.linkage() == "extern":
continue
# skip formals that are part of function signatures
if isinstance(parent, FunctionSignature):
continue
formals[formal.unique_id()] = formal
for use, _ in chapel.each_matching(root, Identifier):
refersto = use.to_node()
if refersto:
uses.add(refersto.unique_id())
for unused in formals.keys() - uses:
anchor = formals[unused].parent()
while isinstance(anchor, (Variable, TupleDecl)):
anchor = anchor.parent()
yield AdvancedRuleResult(formals[unused], anchor)
@driver.advanced_rule
def UnusedTaskIntent(context: Context, root: AstNode):
"""
Warn for unused task intents in functions.
"""
if isinstance(root, Comment):
return
intents = dict()
uses = set()
for intent, _ in chapel.each_matching(
root, set([TaskVar, ReduceIntent])
):
# task private variables may have side effects,
# so we don't want to warn on them
if isinstance(intent, TaskVar):
if intent.intent() == "var":
continue
if intent.intent() == "<const-var>" and (
intent.type_expression() is not None
or intent.init_expression() is not None
):
continue
intents[intent.unique_id()] = intent
for use, _ in chapel.each_matching(root, Identifier):
refersto = use.to_node()
if refersto:
uses.add(refersto.unique_id())
for unused in intents.keys() - uses:
taskvar = intents[unused]
with_clause = taskvar.parent()
task_block = with_clause.parent()
# only loops can be anchors for attributes
anchor = None
if isinstance(task_block, chapel.Loop):
anchor = task_block
yield AdvancedRuleResult(
taskvar, anchor, data=(with_clause, task_block)
)
@driver.fixit(UnusedTaskIntent)
def RemoveTaskIntent(context: Context, result: AdvancedRuleResult):
"""
Remove the unused task intent from the function.
"""
assert isinstance(result.data, tuple)
with_clause, task_block = result.data
fixit = None
# if the with clause only has one expr, remove the entire with clause
if len(list(with_clause.exprs())) == 1:
with_loc = with_clause.location()
# header_loc is the location of the block header without the `with`
# e.g. `forall i in 1..10`, `begin`, `cobegin`
header_loc = (
task_block.header_location()
if isinstance(task_block, Loop)
else task_block.block_header()
)
if header_loc is not None:
start = header_loc.end()
end = with_loc.end()
else:
start = with_loc.start()
end = with_loc.end()
fixit = Fixit.build(Edit(with_loc.path(), start, end, ""))
else:
# for now, locations are messy enough that we can't easily cleanly
# remove the taskvar
pass
return [fixit] if fixit else []
@driver.advanced_rule
def UnusedTypeQuery(context: Context, root: AstNode):
"""
Warn for unused type queries in functions.
"""
if isinstance(root, Comment):
return
typequeries = dict()
uses = set()
for tq, _ in chapel.each_matching(root, TypeQuery):
typequeries[tq.unique_id()] = tq
for use, _ in chapel.each_matching(root, Identifier):
refersto = use.to_node()
if refersto:
uses.add(refersto.unique_id())
for unused in typequeries.keys() - uses:
yield AdvancedRuleResult(typequeries[unused])
@driver.advanced_rule
def UnusedLoopIndex(context: Context, root: AstNode):
"""
Warn for unused index variables in loops.
"""
if isinstance(root, Comment):
return
indices = dict()
uses = set()
for loop, _ in chapel.each_matching(root, IndexableLoop):
node = loop.index()
if node is None:
continue
for index in variables(node):
indices[index.unique_id()] = (index, loop)
for use, _ in chapel.each_matching(root, Identifier):
refersto = use.to_node()
if refersto:
uses.add(refersto.unique_id())
lines = chapel.get_file_lines(context, root)
for unused in indices.keys() - uses:
node, loop = indices[unused]
fixit = fixit_remove_unused_node(node, lines)
fixits = [fixit] if fixit else []
yield AdvancedRuleResult(node, loop, fixits=fixits)
@driver.advanced_rule
def SimpleDomainAsRange(context: Context, root: AstNode):
"""
Warn for simple domains in loops that can be ranges.
"""
# dyno fault if we try to query .location on a Comment
if isinstance(root, Comment):
return
lines = chapel.get_file_lines(context, root)
def is_range_like(node: AstNode):
"""
a node is range like if its a range, a `count` expr with a
range-like on the lhs, a `by` expr with a range-like on the lhs, or
an `align` expr with a range-like on the lhs
"""
if isinstance(node, Range):
return True
if (
isinstance(node, OpCall)
and node.is_binary_op()
and (
node.op() == "#"
or node.op() == "by"
or node.op() == "align"
)
):
return is_range_like(node.actual(0))
return False
for loop, _ in chapel.each_matching(root, IndexableLoop):
# dont warn for array types
if isinstance(loop, BracketLoop) and loop.is_maybe_array_type():
continue
iterand = loop.iterand()
if not isinstance(iterand, Domain):
continue
exprs = list(iterand.exprs())
if len(exprs) != 1:
continue
# only warn for ranges or count operators
if not is_range_like(exprs[0]):
continue
s = range_to_text(exprs[0].location(), lines)
fixit = Fixit.build(Edit.build(iterand.location(), s))
yield AdvancedRuleResult(iterand, anchor=loop, fixits=[fixit])
@driver.advanced_rule
def IncorrectIndentation(context: Context, root: AstNode):
"""
Warn for inconsistent or missing indentation
"""
# First, recurse and find warnings in children.
for child in root:
yield from IncorrectIndentation(context, child)
def contains_statements(node: AstNode) -> bool:
"""
Returns true for allow-listed AST nodes that contain
just a list of statements.
"""
classes = (
Record,
Class,
Module,
SimpleBlockLike,
Interface,
Union,
Enum,
Cobegin,
)
return isinstance(node, classes)
def unwrap_intermediate_block(node: AstNode) -> Optional[AstNode]:
"""
Given a node, find the reference indentation that its children
should be compared against.
This method also rules out certain nodes that should
not be used for parent-child indentation comparison.
"""
if not isinstance(node, Block):
return node
parent = node.parent()
if not parent:
return node
if isinstance(parent, (Function, Loop)):
return parent
elif isinstance(parent, Conditional):
return None if parent.is_expression_level() else parent
return node
# If root is something else (e.g., function call), do not
# apply indentation rules; only apply them to things that contain
# a list of statements.
is_eligible_parent_for_indentation = contains_statements(root)
if not is_eligible_parent_for_indentation:
return
parent_for_indentation = unwrap_intermediate_block(root)
parent_depth = None
if parent_for_indentation is None:
# don't compare against any parent depth.
pass
# For implicit modules, proper code will technically be on the same
# line as the module's body. But we don't want to warn about that,
# since we don't want to ask all code to be indented one level deeper.
elif not (
isinstance(parent_for_indentation, Module)
and parent_for_indentation.kind() == "implicit"
):
parent_depth = parent_for_indentation.location().start()[1]
prev = None