-
Notifications
You must be signed in to change notification settings - Fork 4
/
gaplint.py
executable file
·2265 lines (2007 loc) · 75.9 KB
/
gaplint.py
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
#!/usr/bin/env python3
"""
This module provides functions for automatically checking the format of a GAP
file according to some conventions.
"""
# pylint: disable=fixme, too-many-lines
import argparse
import functools
import itertools
import os
import re
import sys
import time
from copy import deepcopy
from importlib.metadata import version
from os import listdir
from os.path import abspath, exists, isdir, isfile, join
from typing import Any, Callable, Dict, List, Set, Tuple, Union
from dataclasses import dataclass
from rich.console import Console
from rich.table import Table
import yaml
###############################################################################
# Utility
###############################################################################
@dataclass(frozen=True)
class Diagnostic:
"""A diagnostic wrapper class."""
code: str
name: str
line: int
message: str
filename: str
###############################################################################
# Globals
###############################################################################
_VERBOSE = False
_SILENT = False
_GAP_KEYWORDS = {
"and",
"atomic",
"break",
"continue",
"do",
"elif",
"else",
"end",
"false",
"fi",
"for",
"function",
"if",
"in",
"local",
"mod",
"not",
"od",
"or",
"readonly",
"readwrite",
"rec",
"repeat",
"return",
"then",
"true",
"until",
"while",
"quit",
"QUIT",
"IsBound",
"Unbind",
"TryNextMethod",
"Info",
"Assert",
}
_DEFAULT_CONFIG = {
"columns": 80,
"disable": set(),
"dupl-func-min-len": 4,
"enable": "all",
"explain": "",
"files": [],
"indentation": 2,
"max-warnings": 1000,
"silent": False,
"verbose": False,
}
_GLOB_CONFIG = {}
_GLOB_SUPPRESSIONS = set()
_FILE_SUPPRESSIONS = {}
_LINE_SUPPRESSIONS = {}
_LINE_RULES = []
_FILE_RULES = []
_ESCAPE_PATTERN = re.compile(r"(^\\(\\\\)*[^\\]+.*$|^\\(\\\\)*$)")
_DIAGNOSTICS = []
###############################################################################
# Strings helpers
###############################################################################
def _is_tst_or_xml_file(fname: str) -> bool:
"""Returns True if the extension of fname is '.xml' or '.tst'."""
assert isinstance(fname, str)
ext = fname.split(".")[-1]
return ext in ("tst", "xml")
def _is_escaped(lines: str, pos: int) -> Union[bool, re.Match, None]:
assert isinstance(lines, str)
assert isinstance(pos, int)
assert 0 <= pos < len(lines)
if lines[pos - 1] != "\\":
return False
start = lines.rfind("\n", 0, pos)
# Search for an odd number of backslashes immediately before line[pos]
return _ESCAPE_PATTERN.search(lines[start + 1 : pos][::-1])
def _is_double_quote_in_char(line: str, pos: int) -> bool:
assert isinstance(line, str)
assert isinstance(pos, int)
assert 0 <= pos < len(line)
return (
pos > 0
and pos + 1 < len(line)
and line[pos - 1 : pos + 2] == "'\"'"
and not _is_escaped(line, pos - 1)
)
def _is_in_string(lines: str, pos: int) -> bool:
assert isinstance(lines, str)
assert isinstance(pos, int)
start = lines.rfind("\n", 0, pos)
line = re.sub(r"\\.", "", lines[start:pos])
return line.count('"') % 2 == 1 or line.count("'") % 2 == 1
###############################################################################
# Info messages
###############################################################################
def _warn_or_error(rule, fname: str, linenum: int, msg: str) -> None:
if not _SILENT:
assert isinstance(fname, str)
assert isinstance(linenum, int)
assert isinstance(msg, str)
sys.stderr.write(
f"{fname}:{linenum + 1}: {msg} [{rule.code}/{rule.name}]\n"
)
_DIAGNOSTICS.append(
Diagnostic(
code=rule.code,
name=rule.name,
line=linenum + 1,
message=msg,
filename=fname,
)
)
def _warn(rule, fname: str, linenum: int, msg: str) -> None:
_warn_or_error(rule, fname, linenum, msg)
def _error(rule, fname: str, linenum: int, msg: str) -> None:
_warn_or_error(rule, fname, linenum, msg)
sys.stderr.write("Aborting!\n")
sys.exit(1)
def _info_action(msg: str) -> None:
if not _SILENT:
assert isinstance(msg, str)
sys.stdout.write(f"\033[33m{msg}\033[0m\n")
def _info_verbose(msg: str) -> None:
if not _SILENT and _VERBOSE:
assert isinstance(msg, str)
sys.stdout.write(f"\033[2m{msg}\033[0m\n")
###############################################################################
# Rules: a rule must have Rule as a base class.
###############################################################################
class Rule:
"""
Base class for rules.
A rule is a subclass of this class which has a __call__ method that returns
Tuple[int, str] where the \"int\" is the number of warnings issued, and where
the \"str\" is the lines of the file on which the rules are being applied.
"""
all_codes = set()
all_names = {}
@staticmethod
def all_suppressible_codes() -> Set[str]:
"""
Returns the set of all the suppressible rule codes.
"""
return set(x for x in Rule.all_codes if x and not x.startswith("M"))
@staticmethod
def to_code(name_or_code: str) -> str:
"""
Get the code of a rule by its name_or_code.
"""
if name_or_code in Rule.all_names:
return Rule.all_names[name_or_code]
return name_or_code
def __init__(self, name: str, code: str, desc: str = ""):
assert isinstance(name, str)
assert isinstance(code, str)
assert isinstance(desc, str)
if __debug__:
if code in Rule.all_codes:
raise ValueError(f"Duplicate rule code {code}")
Rule.all_codes.add(code)
if name in Rule.all_names:
raise ValueError(f"Duplicate rule name {name}")
Rule.all_names[name] = code
self.name = name
self.code = code
self.desc = desc
def reset(self) -> None:
"""
Reset the rule.
This is only used by rules like those for checking the indentation of
lines. This method is called once per file on which gaplint it run, so
that issues with indentation, for example, in one file do not spill
over into the next file.
"""
class WarnRegexBase(Rule):
"""
Instances of this class produce a warning whenever a line matches the
pattern used to construct the instance except if one of a list of
exceptions is also matched.
"""
# TODO use keyword args
def __init__( # pylint: disable=too-many-arguments, too-many-positional-arguments, dangerous-default-value
self,
name: str,
code: str,
desc: str,
pattern: str,
warning_msg: str,
exceptions: List[str] = [],
skip: Callable[[str], bool] = lambda _: False,
) -> None:
Rule.__init__(self, name, code, desc)
assert isinstance(pattern, str)
assert isinstance(warning_msg, str)
assert isinstance(exceptions, list)
assert all(isinstance(e, str) for e in exceptions)
self._pattern = re.compile(pattern)
self._warning_msg = warning_msg
self._exception_patterns = exceptions
self._exception_group = None
self._exceptions = [re.compile(e) for e in exceptions]
self._skip = skip
def _match(self, line: str, start: int = 0) -> Union[int, None]:
exception_group = self._exception_group
it = self._pattern.finditer(line, start)
for x in it:
exception = False
if len(self._exceptions) > 0:
x_group = x.groups().index(exception_group) + 1
for e in self._exceptions:
ite = e.finditer(line)
for m in ite:
m_group = m.groups().index(exception_group) + 1
if m.start(m_group) == x.start(x_group):
exception = True
break
if exception:
break
if not exception:
return x.start()
return None
def skip(self, fname: str) -> bool:
"""
Returns True if this rule should not be applied to fname.
"""
return self._skip(fname)
###############################################################################
# File rules
###############################################################################
class ReplaceAnnoyUTF8Chars(Rule):
"""
This rule replaces occurrences of annoying UTF characters from an entire
file by their ascii equivalent.
This could issue a warning rather than doing this replacement, but
currently does not.
"""
def __init__(self, name: str, code: str, desc: str = "") -> None:
Rule.__init__(self, name, code, desc)
self._chars = {
"\xc2\x82": ",", # High code comma
"\xc2\x84": ",,", # High code double comma
"\xc2\x85": "...", # Triple dot
"\xc2\x88": "^", # High carat
"\xc2\x91": "\x27", # Forward single quote
"\xc2\x92": "\x27", # Reverse single quote
"\xc2\x93": "\x22", # Forward double quote
"\xc2\x94": "\x22", # Reverse double quote
"\xc2\x95": " ",
"\xc2\x96": "-", # High hyphen
"\xc2\x97": "--", # Double hyphen
"\xc2\x99": " ",
"\xc2\xa0": " ",
"\xc2\xa6": "|", # Split vertical bar
"\xc2\xab": "<<", # Double less than
"\xc2\xbb": ">>", # Double greater than
"\xc2\xbc": "1/4", # one quarter
"\xc2\xbd": "1/2", # one half
"\xc2\xbe": "3/4", # three quarters
"\xca\xbf": "\x27", # c-single quote
"\xcc\xa8": "", # modifier - under curve
"\xcc\xb1": "", # modifier - under line
}
def __call__(
self, fname: str, lines: str, nr_warnings: int = 0
) -> Tuple[int, str]:
assert isinstance(fname, str)
assert isinstance(lines, str)
assert isinstance(nr_warnings, int)
# Remove annoying characters
def replace_chars(
match: re.Match,
) -> str:
char = match.group(0)
return self._chars[char]
return (
nr_warnings,
re.sub(
"(" + "|".join(self._chars.keys()) + ")", replace_chars, lines
),
)
class WarnRegexFile(WarnRegexBase):
"""
A rule that issues a warning if a regex is matched in a file.
"""
def __call__(
self, fname: str, lines: str, nr_warnings: int = 0
) -> Tuple[int, str]:
assert isinstance(fname, str)
assert isinstance(lines, str)
assert isinstance(nr_warnings, int)
if _is_tst_or_xml_file(fname):
return nr_warnings, lines
match = self._match(lines)
while match is not None:
line_num = lines.count("\n", 0, match)
if not _is_rule_suppressed(fname, line_num + 1, self):
_warn(self, fname, line_num, self._warning_msg)
nr_warnings += 1
match = self._match(lines, match + len(self._pattern.pattern))
return nr_warnings, lines
class ReplaceComments(Rule):
"""
Replace between '#+' and the end of a line by '#+' and as many '@' as there
were other characters in the line, call before replacing strings, and
chars, and so on.
This rule does not return any warnings.
"""
def __call__(
self, fname: str, lines: str, nr_warnings: int = 0
) -> Tuple[int, str]:
assert isinstance(fname, str)
assert isinstance(lines, str)
assert isinstance(nr_warnings, int)
start = lines.find("#", 0)
while start != -1 and _is_in_string(lines, start):
start = lines.find("#", start + 1)
while start != -1:
end = lines.find("\n", start)
repl = ""
octo = start
while octo < len(lines) and lines[octo] == "#":
repl += "#"
octo += 1
repl += re.sub(r"[^!\s]", "@", lines[octo:end])
lines = lines[:start] + repl + lines[end:]
start = lines.find("#", end)
while _is_in_string(lines, start):
start = lines.find("#", start + 1)
return nr_warnings, lines
class ReplaceBetweenDelimiters(Rule):
"""
Replace all characters between delim1 and delim2 by #'s except possibly
whitespace.
This rule does not return any warnings.
"""
def __init__( # pylint: disable=too-many-arguments, too-many-positional-arguments
self, name: str, code: str, desc: str, delim1: str, delim2: str
) -> None:
Rule.__init__(self, name, code, desc)
assert isinstance(delim1, str)
assert isinstance(delim2, str)
self._delims = [re.compile(delim1), re.compile(delim2)]
def __find_next(self, which: int, lines: str, start: int) -> int:
assert which in (0, 1)
assert isinstance(lines, str)
assert isinstance(start, int)
if start >= len(lines):
return -1
delim = self._delims[which]
match = delim.search(lines, start)
while match is not None and (
_is_escaped(lines, match.start())
or _is_double_quote_in_char(lines, match.start())
):
match = delim.search(lines, match.start() + len(delim.pattern))
return -1 if match is None else match.start()
def __call__(
self, fname: str, lines: str, nr_warnings: int = 0
) -> Tuple[int, str]:
assert isinstance(fname, str)
assert isinstance(lines, str)
assert isinstance(nr_warnings, int)
start = self.__find_next(0, lines, 0)
while start != -1:
end = self.__find_next(1, lines, start + 1)
if end == -1:
_error(
self,
fname,
lines.count("\n", 0, start),
f"Unmatched {self._delims[0].pattern}",
)
end += len(self._delims[1].pattern)
repl = re.sub("[^\n ]", "@", lines[start:end])
assert len(repl) == end - start
lines = lines[:start] + repl + lines[end:]
start = self.__find_next(0, lines, end + 1)
return nr_warnings, lines
class ReplaceOutputTstOrXMLFile(Rule):
"""
This rule removes the prefix 'gap>' or '>' if called with a line from a
file with extension 'tst' or 'xml', if the line does not start with a
'gap>' or '>', then the entire line is replaced with an equal number of
'@''s.
"""
def __init__(self, name: str, code: str, desc: str = "") -> None:
Rule.__init__(self, name, code, desc)
self._consuming = False
self._sol_p = re.compile(r"(^|\n)gap>\s*")
self._eol_p = re.compile(r"($|\n)")
self._rep_p = re.compile(r"[^\n]")
def __call__(
self, fname: str, lines: str, nr_warnings: int = 0
) -> Tuple[int, str]:
assert isinstance(fname, str)
assert isinstance(lines, str)
assert isinstance(nr_warnings, int)
if _is_tst_or_xml_file(fname):
eol, out = 0, ""
for sol in self._sol_p.finditer(lines):
# Replace everything except '\n' with '@'
out += re.sub(self._rep_p, "@", lines[eol : sol.start() + 1])
eol = self._eol_p.search(lines, sol.end())
if eol is None:
# Found a start of line marker without a corresponding end
# of line marker, i.e. no newline or end of line marker.
# This should not be possible, unless the file is somehow
# corrupt. Either way we just quietly skip the line and
# hope nothing bad happens.
continue
eol = eol.end()
out += lines[sol.end() : eol]
while eol + 1 < len(lines) and lines[eol] == ">":
start = eol + 2
eol = self._eol_p.search(lines, start)
if eol is None:
# See above comment.
break
eol = eol.end()
out += lines[start:eol]
return nr_warnings, out
return nr_warnings, lines
class AnalyseLVars(Rule): # pylint: disable=too-many-instance-attributes
"""
This rule checks if there are unused local variables in a function.
"""
SubRules = {
"W040": Rule(
"use-id-func",
"W040",
"Warns that [code]function(x) return x; end;[/code] can be "
"replaced by [code]IdFunc[/code].",
),
"W046": Rule(
"unused-func-args",
"W046",
"Warns if there are unused function parameters (use [code]_[/code] to suppress).",
),
"W047": Rule(
"duplicate-function",
"W047",
"Warns if there is a duplicate function.",
),
}
def __init__(self, name: str, code: str, desc: str = "") -> None:
Rule.__init__(self, name, code, desc)
self.reset()
self._function_p = re.compile(r"\bfunction\b")
self._end_p = re.compile(r"\bend\b")
self._local_p = re.compile(r"\blocal\b")
self._var_p = re.compile(r"\w+\s*\w*")
self._ass_var_p = re.compile(r"([a-zA-Z0-9_\.]+)\s*:=")
self._use_var_p = re.compile(r"(\b\w+\b)(?!\s*:=)\W*")
self._ws1_p = re.compile(r"[ \t\r\f\v]+")
self._ws2_p = re.compile(r"\n[ \t\r\f\v]+")
self._rec_p = re.compile(r"\brec\(")
self._comment_p = re.compile(r" *#.*?\n")
self._func_bodies = []
self._func_position = []
def reset(self) -> None:
self._depth = -1
self._func_args = []
self._declared_lvars = []
self._assigned_lvars = []
self._used_lvars = []
self._func_start_pos = []
def _remove_recs_and_whitespace(self, lines: str) -> str:
# Remove almost all whitespace
lines = re.sub(self._comment_p, "\n", lines)
lines = re.sub(self._ws1_p, " ", lines)
lines = re.sub(self._ws2_p, "\n", lines)
stack = []
pos = 0
# Replace rec( -> ) so that we do not match assignments inside records
while pos < len(lines):
if self._rec_p.search(lines, pos, pos + 5):
stack.append(pos)
pos += 4
elif lines[pos] == "(" and len(stack) > 0:
stack.append(None)
elif lines[pos] == ")" and len(stack) > 0:
start = stack.pop()
if start is not None:
nr_newlines = lines.count("\n", start + 1, pos + 1)
var = self._use_var_p.findall(lines, start + 5, pos + 1)
var = [a for a in var if a not in _GAP_KEYWORDS]
var = " ".join(var)
replacement = "rec(" + var + "\n" * nr_newlines + ")"
lines = lines[: start + 1] + replacement + lines[pos + 1 :]
pos -= pos - start
pos += len(replacement)
pos += 1
assert len(stack) == 0
return lines
def _start_function(
self, fname: str, lines: str, pos: int, nr_warnings: int
) -> Tuple[int, int]:
self._depth += 1
assert self._depth == len(self._func_args)
assert self._depth == len(self._declared_lvars)
assert self._depth == len(self._assigned_lvars)
assert self._depth == len(self._used_lvars)
assert self._depth == len(self._func_start_pos)
self._func_args.append([])
self._declared_lvars.append(set())
self._assigned_lvars.append(set())
self._used_lvars.append(set())
self._func_start_pos.append(pos)
start = lines.find("(", pos) + 1
end = lines.find(")", start)
new_args = self._var_p.findall(lines, start, end)
args = self._func_args[self._depth]
for var in new_args:
var = [x.strip() for x in var.split(" ") if len(x) != 0]
if len(var) == 1:
var = var[0].strip()
elif len(var) != 2 or var[0] not in ("readonly", "readwrite"):
_error(
self,
fname,
lines.count("\n", 0, pos),
f'Invalid syntax: "{lines[start:end]}"',
)
else:
var = var[1].strip()
if var in args:
_error(
self,
fname,
lines.count("\n", 0, pos),
f"Duplicate function argument: {var}",
)
elif var in _GAP_KEYWORDS:
_error(
self,
fname,
lines.count("\n", 0, pos),
f"Function argument is keyword: {var}",
)
else:
args.append(var)
return end + 1, nr_warnings
def _check_assigned_but_never_used_lvars(
self, ass_lvars, fname, linenum, nr_warnings
):
if len(ass_lvars) != 0 and not _is_rule_suppressed(
fname, linenum + 1, self
):
ass_lvars = [key for key in ass_lvars if key.find(".") == -1]
msg = f"Variables assigned but never used: {', '.join(sorted(ass_lvars))}"
_warn(self, fname, linenum, msg)
nr_warnings += 1
return nr_warnings
def _check_unused_lvars(self, decl_lvars, fname, linenum, nr_warnings):
if len(decl_lvars) != 0 and not _is_rule_suppressed(
fname, linenum + 1, self
):
decl_lvars = list(decl_lvars)
msg = f"Unused local variables: {', '.join(sorted(decl_lvars))}"
_warn(self, fname, linenum, msg)
nr_warnings += 1
return nr_warnings
def _check_unused_func_args(self, func_args, fname, linenum, nr_warnings):
func_args = [arg for arg in func_args if arg != "_"]
if len(func_args) != 0:
if not _is_rule_suppressed(
fname, linenum + 1, AnalyseLVars.SubRules["W046"]
):
msg = (
f"Unused function arguments: {', '.join(sorted(func_args))}"
)
_warn(self.SubRules["W046"], fname, linenum, msg)
nr_warnings += 1
return nr_warnings
def _check_dupl_funcs(self, func_body, fname, linenum, nr_warnings):
num_func_lines = func_body.count("\n")
limit = _GLOB_CONFIG["dupl-func-min-len"]
if num_func_lines + 1 > limit:
if not _is_rule_suppressed(
fname, linenum + 1, AnalyseLVars.SubRules["W047"]
):
func_body = re.sub(r"\n", "", func_body)
try:
index = self._func_bodies.index(func_body)
_warn(
AnalyseLVars.SubRules["W047"],
fname,
linenum,
f"Duplicate function with {num_func_lines + 1} > {limit}"
' lines (from "function" to "end" inclusive), previously '
f"defined at {self._func_position[index]}!",
)
nr_warnings += 1
except ValueError:
self._func_bodies.append(func_body)
self._func_position.append(f"{fname}:{linenum + 1}")
return nr_warnings
# TODO use keyword args?
def _check_for_return_fail_etc( # pylint: disable=too-many-arguments, too-many-positional-arguments
self, func_body, func_args_all, fname, linenum, nr_warnings
):
num_func_lines = func_body.count("\n")
if num_func_lines != 2:
return nr_warnings
line = func_body.split("\n")[-2]
for bval, code in (
("true", "W036"),
("false", "W037"),
("fail", "W038"),
):
if not _is_rule_suppressed(
fname, linenum + 1, all_rules()[code]
) and re.search(rf"^\s*\breturn\b\s+\b{bval}\b", line):
_warn(
all_rules()[code],
fname,
linenum,
f"Replace one line function by Return{bval.capitalize()}",
)
nr_warnings += 1
if (
len(func_args_all) > 1
and not _is_rule_suppressed(fname, linenum + 1, all_rules()["W039"])
and re.search(rf"^\s*\breturn\b\s+\b{func_args_all[0]}\s*;", line)
):
_warn(
all_rules()["W039"],
fname,
linenum,
"Replace function(x, y, z, ...) return x; end; by ReturnFirst",
)
nr_warnings += 1
if (
len(func_args_all) == 1
and not _is_rule_suppressed(
fname, linenum + 1, AnalyseLVars.SubRules["W040"]
)
and re.search(rf"^\s*return\b\s+\b{func_args_all[0]}\s*;", line)
):
_warn(
self.SubRules["W040"],
fname,
linenum,
'Replace "function(x) return x; end;" by IdFunc',
)
nr_warnings += 1
return nr_warnings
def _end_function(
self, fname: str, lines: str, pos: int, nr_warnings: int
) -> Tuple[int, int]:
if len(self._declared_lvars) == 0:
_error(
self, fname, lines.count("\n", 0, pos), "'end' outside function"
)
self._depth -= 1
ass_lvars = self._assigned_lvars.pop()
decl_lvars = self._declared_lvars.pop()
use_lvars = self._used_lvars.pop()
func_args_all = self._func_args.pop()
if len(self._used_lvars) > 0:
self._used_lvars[-1] |= use_lvars # union
ass_lvars -= use_lvars # difference
ass_lvars &= decl_lvars # intersection
decl_lvars -= ass_lvars # difference
decl_lvars -= use_lvars # difference
func_args = set(func_args_all) - use_lvars # difference
linenum = lines.count("\n", 0, self._func_start_pos[-1])
nr_warnings = self._check_assigned_but_never_used_lvars(
ass_lvars, fname, linenum, nr_warnings
)
nr_warnings = self._check_unused_lvars(
decl_lvars, fname, linenum, nr_warnings
)
nr_warnings = self._check_unused_func_args(
func_args, fname, linenum, nr_warnings
)
func_body = lines[self._func_start_pos[-1] : pos]
nr_warnings = self._check_dupl_funcs(
func_body, fname, linenum, nr_warnings
)
nr_warnings = self._check_for_return_fail_etc(
func_body, func_args_all, fname, linenum, nr_warnings
)
self._func_start_pos.pop()
return pos + len("end"), nr_warnings
def _add_declared_lvars(
self, fname: str, lines: str, pos: int, nr_warnings: int
) -> Tuple[int, int]:
end = lines.find(";", pos)
lvars = self._declared_lvars[self._depth]
args = self._func_args[self._depth]
new_lvars = self._var_p.findall(lines, pos, end)
for var in new_lvars:
var = var.strip()
if var in lvars:
_error(
self,
fname,
lines.count("\n", 0, pos),
f"Name used for two local variables: {var}",
)
elif var in args:
_error(
self,
fname,
lines.count("\n", 0, pos),
f"Name used for function argument and local variable: {var}",
)
elif var in _GAP_KEYWORDS:
_error(
self,
fname,
lines.count("\n", 0, pos),
f"Local variable is keyword: {var}",
)
else:
lvars.add(var)
return end, nr_warnings
def _find_lvars(
self, fname: str, lines: str, pos: int, nr_warnings: int
) -> Tuple[int, int]:
end = self._end_p.search(lines, pos + 1)
func = self._function_p.search(lines, pos + 1)
if end is None and func is None:
return len(lines), nr_warnings
if end is None and func is not None:
_error(
self,
fname,
lines.count("\n", 0, pos),
"'function' without 'end'",
)
if func is not None and end is not None and func.start() < end.start():
end = func.start()
else:
assert end is not None
end = end.start()
if self._depth >= 0:
a_lvars = self._assigned_lvars[self._depth]
a_lvars |= set(self._ass_var_p.findall(lines, pos, end))
u_lvars = self._used_lvars[self._depth]
u_lvars |= set(self._use_var_p.findall(lines, pos, end))
return end, nr_warnings
def __call__(
self, fname: str, lines: str, nr_warnings: int = 0
) -> Tuple[int, str]:
assert isinstance(fname, str)
assert isinstance(lines, str)
assert isinstance(nr_warnings, int)
if _is_tst_or_xml_file(fname):
return nr_warnings, lines
orig_lines = lines[:]
lines = self._remove_recs_and_whitespace(lines)
pos = 0
while pos < len(lines):
if self._function_p.search(lines, pos, pos + len("function")):
pos, nr_warnings = self._start_function(
fname, lines, pos, nr_warnings
)
elif self._local_p.search(lines, pos, pos + len("local") + 1):
pos, nr_warnings = self._add_declared_lvars(
fname, lines, pos + len("local") + 1, nr_warnings
)
elif self._end_p.search(lines, pos, pos + len("end")):
pos, nr_warnings = self._end_function(
fname, lines, pos, nr_warnings
)
else:
pos, nr_warnings = self._find_lvars(
fname, lines, pos, nr_warnings
)
return nr_warnings, orig_lines
###############################################################################
# Line rules
###############################################################################
class LineTooLong(Rule):
"""
Warn if the length of a line exceeds 80 characters.
This rule does not modify the line.
"""
def __init__(self, name: str, code: str, desc: str = "") -> None:
Rule.__init__(self, name, code, desc)
def __call__(
self, fname: str, lines: str, linenum: int, nr_warnings: int = 0
) -> Tuple[int, str]:
cols = _GLOB_CONFIG["columns"]
if _is_tst_or_xml_file(fname):
return nr_warnings, lines
if len(lines[linenum]) - 1 > cols:
_warn(
self,
fname,
linenum,
f"Too long line ({len(lines[linenum]) - 1} / {cols})",
)
nr_warnings += 1
return nr_warnings, lines
class WarnRegexLine(WarnRegexBase):
"""
Warn if regex matches.
"""
def __call__(
self, fname: str, lines: str, linenum: int, nr_warnings: int = 0
) -> Tuple[int, str]:
assert isinstance(fname, str)
assert isinstance(lines, list)
assert isinstance(linenum, int)
assert linenum < len(lines)
assert isinstance(nr_warnings, int)
if not self.skip(fname):
if self._match(lines[linenum]) is not None:
_warn(self, fname, linenum, self._warning_msg)
return nr_warnings + 1, lines
return nr_warnings, lines
class WhitespaceOperator(WarnRegexLine):
"""
Instances of this class produce a warning whenever the whitespace around an
operator is incorrect.
"""
def __init__( # pylint: disable=too-many-arguments, too-many-positional-arguments
self,
name: str,
code: str,
desc: str,
op: str,
exceptions: List[str] = [],
): # pylint: disable=W0102
WarnRegexLine.__init__(self, name, code, desc, "", "")
assert isinstance(op, str)
assert op[0] != "(" and op[-1] != ")"
assert exceptions is None or isinstance(exceptions, list)
assert all(isinstance(e, str) for e in exceptions)
gop = "(" + op + ")"
pattern = rf"(\S{gop}|{gop}\S|\s{{2,}}{gop}|{gop}\s{{2,}})"