-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
format.py
1335 lines (1190 loc) · 47.3 KB
/
format.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
# -*- coding: utf-8 -*-
# Copyright (c) 2006-2014 LOGILAB S.A. (Paris, FRANCE) <[email protected]>
# Copyright (c) 2012-2015 Google, Inc.
# Copyright (c) 2013 moxian <[email protected]>
# Copyright (c) 2014-2018 Claudiu Popa <[email protected]>
# Copyright (c) 2014 frost-nzcr4 <[email protected]>
# Copyright (c) 2014 Brett Cannon <[email protected]>
# Copyright (c) 2014 Michal Nowikowski <[email protected]>
# Copyright (c) 2014 Arun Persaud <[email protected]>
# Copyright (c) 2015 Mike Frysinger <[email protected]>
# Copyright (c) 2015 Fabio Natali <[email protected]>
# Copyright (c) 2015 Harut <[email protected]>
# Copyright (c) 2015 Mihai Balint <[email protected]>
# Copyright (c) 2015 Pavel Roskin <[email protected]>
# Copyright (c) 2015 Ionel Cristian Maries <[email protected]>
# Copyright (c) 2016 Petr Pulc <[email protected]>
# Copyright (c) 2016 Moises Lopez <[email protected]>
# Copyright (c) 2016 Ashley Whetter <[email protected]>
# Copyright (c) 2017-2018 Bryce Guinta <[email protected]>
# Copyright (c) 2017 hippo91 <[email protected]>
# Copyright (c) 2017 Krzysztof Czapla <[email protected]>
# Copyright (c) 2017 Łukasz Rogalski <[email protected]>
# Copyright (c) 2017 James M. Allen <[email protected]>
# Copyright (c) 2017 vinnyrose <[email protected]>
# Copyright (c) 2018 Bryce Guinta <[email protected]>
# Copyright (c) 2018 Mike Frysinger <[email protected]>
# Copyright (c) 2018 ssolanki <[email protected]>
# Copyright (c) 2018 Anthony Sottile <[email protected]>
# Copyright (c) 2018 Fureigh <[email protected]>
# Copyright (c) 2018 Pierre Sassoulas <[email protected]>
# Copyright (c) 2018 Andreas Freimuth <[email protected]>
# Copyright (c) 2018 Jakub Wilk <[email protected]>
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint/blob/master/COPYING
"""Python code format's checker.
By default try to follow Guido's style guide :
https://www.python.org/doc/essays/styleguide/
Some parts of the process_token method is based from The Tab Nanny std module.
"""
import keyword
import sys
import tokenize
from functools import reduce # pylint: disable=redefined-builtin
from astroid import nodes
from pylint.checkers import BaseTokenChecker
from pylint.checkers.utils import check_messages
from pylint.constants import OPTION_RGX, WarningScope
from pylint.interfaces import IAstroidChecker, IRawChecker, ITokenChecker
_ASYNC_TOKEN = "async"
_CONTINUATION_BLOCK_OPENERS = [
"elif",
"except",
"for",
"if",
"while",
"def",
"class",
"with",
]
_KEYWORD_TOKENS = [
"assert",
"del",
"elif",
"except",
"for",
"if",
"in",
"not",
"raise",
"return",
"while",
"yield",
"with",
]
if sys.version_info < (3, 0):
_KEYWORD_TOKENS.append("print")
_SPACED_OPERATORS = [
"==",
"<",
">",
"!=",
"<>",
"<=",
">=",
"+=",
"-=",
"*=",
"**=",
"/=",
"//=",
"&=",
"|=",
"^=",
"%=",
">>=",
"<<=",
]
_OPENING_BRACKETS = ["(", "[", "{"]
_CLOSING_BRACKETS = [")", "]", "}"]
_TAB_LENGTH = 8
_EOL = frozenset([tokenize.NEWLINE, tokenize.NL, tokenize.COMMENT])
_JUNK_TOKENS = (tokenize.COMMENT, tokenize.NL)
# Whitespace checking policy constants
_MUST = 0
_MUST_NOT = 1
_IGNORE = 2
# Whitespace checking config constants
_DICT_SEPARATOR = "dict-separator"
_TRAILING_COMMA = "trailing-comma"
_EMPTY_LINE = "empty-line"
_NO_SPACE_CHECK_CHOICES = [_TRAILING_COMMA, _DICT_SEPARATOR, _EMPTY_LINE]
_DEFAULT_NO_SPACE_CHECK_CHOICES = [_TRAILING_COMMA, _DICT_SEPARATOR]
MSGS = {
"C0301": (
"Line too long (%s/%s)",
"line-too-long",
"Used when a line is longer than a given number of characters.",
),
"C0302": (
"Too many lines in module (%s/%s)", # was W0302
"too-many-lines",
"Used when a module has too many lines, reducing its readability.",
),
"C0303": (
"Trailing whitespace",
"trailing-whitespace",
"Used when there is whitespace between the end of a line and the newline.",
),
"C0304": (
"Final newline missing",
"missing-final-newline",
"Used when the last line in a file is missing a newline.",
),
"C0305": (
"Trailing newlines",
"trailing-newlines",
"Used when there are trailing blank lines in a file.",
),
"W0311": (
"Bad indentation. Found %s %s, expected %s",
"bad-indentation",
"Used when an unexpected number of indentation's tabulations or "
"spaces has been found.",
),
"C0330": ("Wrong %s indentation%s%s.\n%s%s", "bad-continuation", "TODO"),
"W0312": (
"Found indentation with %ss instead of %ss",
"mixed-indentation",
"Used when there are some mixed tabs and spaces in a module.",
),
"W0301": (
"Unnecessary semicolon", # was W0106
"unnecessary-semicolon",
'Used when a statement is ended by a semi-colon (";"), which '
"isn't necessary (that's python, not C ;).",
),
"C0321": (
"More than one statement on a single line",
"multiple-statements",
"Used when more than on statement are found on the same line.",
{"scope": WarningScope.NODE},
),
"C0325": (
"Unnecessary parens after %r keyword",
"superfluous-parens",
"Used when a single item in parentheses follows an if, for, or "
"other keyword.",
),
"C0326": (
"%s space %s %s %s\n%s",
"bad-whitespace",
(
"Used when a wrong number of spaces is used around an operator, "
"bracket or block opener."
),
{
"old_names": [
("C0323", "no-space-after-operator"),
("C0324", "no-space-after-comma"),
("C0322", "no-space-before-operator"),
]
},
),
"C0327": (
"Mixed line endings LF and CRLF",
"mixed-line-endings",
"Used when there are mixed (LF and CRLF) newline signs in a file.",
),
"C0328": (
"Unexpected line ending format. There is '%s' while it should be '%s'.",
"unexpected-line-ending-format",
"Used when there is different newline than expected.",
),
}
def _underline_token(token):
length = token[3][1] - token[2][1]
offset = token[2][1]
referenced_line = token[4]
# If the referenced line does not end with a newline char, fix it
if referenced_line[-1] != "\n":
referenced_line += "\n"
return referenced_line + (" " * offset) + ("^" * length)
def _column_distance(token1, token2):
if token1 == token2:
return 0
if token2[3] < token1[3]:
token1, token2 = token2, token1
if token1[3][0] != token2[2][0]:
return None
return token2[2][1] - token1[3][1]
def _last_token_on_line_is(tokens, line_end, token):
return (
line_end > 0
and tokens.token(line_end - 1) == token
or line_end > 1
and tokens.token(line_end - 2) == token
and tokens.type(line_end - 1) == tokenize.COMMENT
)
def _token_followed_by_eol(tokens, position):
return (
tokens.type(position + 1) == tokenize.NL
or tokens.type(position + 1) == tokenize.COMMENT
and tokens.type(position + 2) == tokenize.NL
)
def _get_indent_string(line):
"""Return the indention string of the given line."""
result = ""
for char in line:
if char in " \t":
result += char
else:
break
return result
def _get_indent_length(line):
"""Return the length of the indentation on the given token's line."""
result = 0
for char in line:
if char == " ":
result += 1
elif char == "\t":
result += _TAB_LENGTH
else:
break
return result
def _get_indent_hint_line(bar_positions, bad_position):
"""Return a line with |s for each of the positions in the given lists."""
if not bar_positions:
return "", ""
bar_positions = [_get_indent_length(indent) for indent in bar_positions]
bad_position = _get_indent_length(bad_position)
delta_message = ""
markers = [(pos, "|") for pos in bar_positions]
if len(markers) == 1:
# if we have only one marker we'll provide an extra hint on how to fix
expected_position = markers[0][0]
delta = abs(expected_position - bad_position)
direction = "add" if expected_position > bad_position else "remove"
delta_message = _CONTINUATION_HINT_MESSAGE % (
direction,
delta,
"s" if delta > 1 else "",
)
markers.append((bad_position, "^"))
markers.sort()
line = [" "] * (markers[-1][0] + 1)
for position, marker in markers:
line[position] = marker
return "".join(line), delta_message
class _ContinuedIndent:
__slots__ = (
"valid_outdent_strings",
"valid_continuation_strings",
"context_type",
"token",
"position",
)
def __init__(
self,
context_type,
token,
position,
valid_outdent_strings,
valid_continuation_strings,
):
self.valid_outdent_strings = valid_outdent_strings
self.valid_continuation_strings = valid_continuation_strings
self.context_type = context_type
self.position = position
self.token = token
# The contexts for hanging indents.
# A hanging indented dictionary value after :
HANGING_DICT_VALUE = "dict-value"
# Hanging indentation in an expression.
HANGING = "hanging"
# Hanging indentation in a block header.
HANGING_BLOCK = "hanging-block"
# Continued indentation inside an expression.
CONTINUED = "continued"
# Continued indentation in a block header.
CONTINUED_BLOCK = "continued-block"
SINGLE_LINE = "single"
WITH_BODY = "multi"
_CONTINUATION_MSG_PARTS = {
HANGING_DICT_VALUE: ("hanging", " in dict value"),
HANGING: ("hanging", ""),
HANGING_BLOCK: ("hanging", " before block"),
CONTINUED: ("continued", ""),
CONTINUED_BLOCK: ("continued", " before block"),
}
_CONTINUATION_HINT_MESSAGE = " (%s %d space%s)" # Ex: (remove 2 spaces)
def _Indentations(*args):
"""Valid indentation strings for a continued line."""
return {a: None for a in args}
def _BeforeBlockIndentations(single, with_body):
"""Valid alternative indentation strings for continued lines before blocks.
:param int single: Valid indentation string for statements on a single logical line.
:param int with_body: Valid indentation string for statements on several lines.
:returns: A dictionary mapping indent offsets to a string representing
whether the indent if for a line or block.
:rtype: dict
"""
return {single: SINGLE_LINE, with_body: WITH_BODY}
class TokenWrapper:
"""A wrapper for readable access to token information."""
def __init__(self, tokens):
self._tokens = tokens
def token(self, idx):
return self._tokens[idx][1]
def type(self, idx):
return self._tokens[idx][0]
def start_line(self, idx):
return self._tokens[idx][2][0]
def start_col(self, idx):
return self._tokens[idx][2][1]
def line(self, idx):
return self._tokens[idx][4]
def line_indent(self, idx):
"""Get the string of TABs and Spaces used for indentation of the line of this token"""
return _get_indent_string(self.line(idx))
def token_indent(self, idx):
"""Get an indentation string for hanging indentation, consisting of the line-indent plus
a number of spaces to fill up to the column of this token.
e.g. the token indent for foo
in "<TAB><TAB>print(foo)"
is "<TAB><TAB> "
"""
line_indent = self.line_indent(idx)
return line_indent + " " * (self.start_col(idx) - len(line_indent))
class ContinuedLineState:
"""Tracker for continued indentation inside a logical line."""
def __init__(self, tokens, config):
self._line_start = -1
self._cont_stack = []
self._is_block_opener = False
self.retained_warnings = []
self._config = config
self._tokens = TokenWrapper(tokens)
@property
def has_content(self):
return bool(self._cont_stack)
@property
def _block_indent_string(self):
return self._config.indent_string.replace("\\t", "\t")
@property
def _continuation_string(self):
return self._block_indent_string[0] * self._config.indent_after_paren
@property
def _continuation_size(self):
return self._config.indent_after_paren
def handle_line_start(self, pos):
"""Record the first non-junk token at the start of a line."""
if self._line_start > -1:
return
check_token_position = pos
if self._tokens.token(pos) == _ASYNC_TOKEN:
check_token_position += 1
self._is_block_opener = (
self._tokens.token(check_token_position) in _CONTINUATION_BLOCK_OPENERS
)
self._line_start = pos
def next_physical_line(self):
"""Prepares the tracker for a new physical line (NL)."""
self._line_start = -1
self._is_block_opener = False
def next_logical_line(self):
"""Prepares the tracker for a new logical line (NEWLINE).
A new logical line only starts with block indentation.
"""
self.next_physical_line()
self.retained_warnings = []
self._cont_stack = []
def add_block_warning(self, token_position, state, valid_indentations):
self.retained_warnings.append((token_position, state, valid_indentations))
def get_valid_indentations(self, idx):
"""Returns the valid offsets for the token at the given position."""
# The closing brace on a dict or the 'for' in a dict comprehension may
# reset two indent levels because the dict value is ended implicitly
stack_top = -1
if (
self._tokens.token(idx) in ("}", "for")
and self._cont_stack[-1].token == ":"
):
stack_top = -2
indent = self._cont_stack[stack_top]
if self._tokens.token(idx) in _CLOSING_BRACKETS:
valid_indentations = indent.valid_outdent_strings
else:
valid_indentations = indent.valid_continuation_strings
return indent, valid_indentations.copy()
def _hanging_indent_after_bracket(self, bracket, position):
"""Extracts indentation information for a hanging indent
Case of hanging indent after a bracket (including parenthesis)
:param str bracket: bracket in question
:param int position: Position of bracket in self._tokens
:returns: the state and valid positions for hanging indentation
:rtype: _ContinuedIndent
"""
indentation = self._tokens.line_indent(position)
if (
self._is_block_opener
and self._continuation_string == self._block_indent_string
):
return _ContinuedIndent(
HANGING_BLOCK,
bracket,
position,
_Indentations(indentation + self._continuation_string, indentation),
_BeforeBlockIndentations(
indentation + self._continuation_string,
indentation + self._continuation_string * 2,
),
)
if bracket == ":":
# If the dict key was on the same line as the open brace, the new
# correct indent should be relative to the key instead of the
# current indent level
paren_align = self._cont_stack[-1].valid_outdent_strings
next_align = self._cont_stack[-1].valid_continuation_strings.copy()
next_align_keys = list(next_align.keys())
next_align[next_align_keys[0] + self._continuation_string] = True
# Note that the continuation of
# d = {
# 'a': 'b'
# 'c'
# }
# is handled by the special-casing for hanging continued string indents.
return _ContinuedIndent(
HANGING_DICT_VALUE, bracket, position, paren_align, next_align
)
return _ContinuedIndent(
HANGING,
bracket,
position,
_Indentations(indentation, indentation + self._continuation_string),
_Indentations(indentation + self._continuation_string),
)
def _continuation_inside_bracket(self, bracket, position):
"""Extracts indentation information for a continued indent."""
indentation = self._tokens.line_indent(position)
token_indent = self._tokens.token_indent(position)
next_token_indent = self._tokens.token_indent(position + 1)
if (
self._is_block_opener
and next_token_indent == indentation + self._block_indent_string
):
return _ContinuedIndent(
CONTINUED_BLOCK,
bracket,
position,
_Indentations(token_indent),
_BeforeBlockIndentations(
next_token_indent, next_token_indent + self._continuation_string
),
)
return _ContinuedIndent(
CONTINUED,
bracket,
position,
_Indentations(token_indent, next_token_indent),
_Indentations(next_token_indent),
)
def pop_token(self):
self._cont_stack.pop()
def push_token(self, token, position):
"""Pushes a new token for continued indentation on the stack.
Tokens that can modify continued indentation offsets are:
* opening brackets
* 'lambda'
* : inside dictionaries
push_token relies on the caller to filter out those
interesting tokens.
:param int token: The concrete token
:param int position: The position of the token in the stream.
"""
if _token_followed_by_eol(self._tokens, position):
self._cont_stack.append(self._hanging_indent_after_bracket(token, position))
else:
self._cont_stack.append(self._continuation_inside_bracket(token, position))
class FormatChecker(BaseTokenChecker):
"""checks for :
* unauthorized constructions
* strict indentation
* line length
"""
__implements__ = (ITokenChecker, IAstroidChecker, IRawChecker)
# configuration section name
name = "format"
# messages
msgs = MSGS
# configuration options
# for available dict keys/values see the optik parser 'add_option' method
options = (
(
"max-line-length",
{
"default": 100,
"type": "int",
"metavar": "<int>",
"help": "Maximum number of characters on a single line.",
},
),
(
"ignore-long-lines",
{
"type": "regexp",
"metavar": "<regexp>",
"default": r"^\s*(# )?<?https?://\S+>?$",
"help": (
"Regexp for a line that is allowed to be longer than " "the limit."
),
},
),
(
"single-line-if-stmt",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": (
"Allow the body of an if to be on the same "
"line as the test if there is no else."
),
},
),
(
"single-line-class-stmt",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": (
"Allow the body of a class to be on the same "
"line as the declaration if body contains "
"single statement."
),
},
),
(
"no-space-check",
{
"default": ",".join(_DEFAULT_NO_SPACE_CHECK_CHOICES),
"metavar": ",".join(_NO_SPACE_CHECK_CHOICES),
"type": "multiple_choice",
"choices": _NO_SPACE_CHECK_CHOICES,
"help": (
"List of optional constructs for which whitespace "
"checking is disabled. "
"`" + _DICT_SEPARATOR + "` is used to allow tabulation "
"in dicts, etc.: {1 : 1,\\n222: 2}. "
"`" + _TRAILING_COMMA + "` allows a space between comma "
"and closing bracket: (a, ). "
"`" + _EMPTY_LINE + "` allows space-only lines."
),
},
),
(
"max-module-lines",
{
"default": 1000,
"type": "int",
"metavar": "<int>",
"help": "Maximum number of lines in a module.",
},
),
(
"indent-string",
{
"default": " ",
"type": "non_empty_string",
"metavar": "<string>",
"help": "String used as indentation unit. This is usually "
'" " (4 spaces) or "\\t" (1 tab).',
},
),
(
"indent-after-paren",
{
"type": "int",
"metavar": "<int>",
"default": 4,
"help": "Number of spaces of indent required inside a hanging "
"or continued line.",
},
),
(
"expected-line-ending-format",
{
"type": "choice",
"metavar": "<empty or LF or CRLF>",
"default": "",
"choices": ["", "LF", "CRLF"],
"help": (
"Expected format of line ending, "
"e.g. empty (any line ending), LF or CRLF."
),
},
),
)
def __init__(self, linter=None):
BaseTokenChecker.__init__(self, linter)
self._lines = None
self._visited_lines = None
self._bracket_stack = [None]
def _pop_token(self):
self._bracket_stack.pop()
self._current_line.pop_token()
def _push_token(self, token, idx):
self._bracket_stack.append(token)
self._current_line.push_token(token, idx)
def new_line(self, tokens, line_end, line_start):
"""a new line has been encountered, process it if necessary"""
if _last_token_on_line_is(tokens, line_end, ";"):
self.add_message("unnecessary-semicolon", line=tokens.start_line(line_end))
line_num = tokens.start_line(line_start)
line = tokens.line(line_start)
if tokens.type(line_start) not in _JUNK_TOKENS:
self._lines[line_num] = line.split("\n")[0]
self.check_lines(line, line_num)
def process_module(self, _module):
self._keywords_with_parens = set()
def _check_keyword_parentheses(self, tokens, start):
"""Check that there are not unnecessary parens after a keyword.
Parens are unnecessary if there is exactly one balanced outer pair on a
line, and it is followed by a colon, and contains no commas (i.e. is not a
tuple).
Args:
tokens: list of Tokens; the entire list of Tokens.
start: int; the position of the keyword in the token list.
"""
# If the next token is not a paren, we're fine.
if self._inside_brackets(":") and tokens[start][1] == "for":
self._pop_token()
if tokens[start + 1][1] != "(":
return
found_and_or = False
depth = 0
keyword_token = str(tokens[start][1])
line_num = tokens[start][2][0]
for i in range(start, len(tokens) - 1):
token = tokens[i]
# If we hit a newline, then assume any parens were for continuation.
if token[0] == tokenize.NL:
return
if token[1] == "(":
depth += 1
elif token[1] == ")":
depth -= 1
if depth:
continue
# ')' can't happen after if (foo), since it would be a syntax error.
if tokens[i + 1][1] in (":", ")", "]", "}", "in") or tokens[i + 1][
0
] in (tokenize.NEWLINE, tokenize.ENDMARKER, tokenize.COMMENT):
# The empty tuple () is always accepted.
if i == start + 2:
return
if keyword_token == "not":
if not found_and_or:
self.add_message(
"superfluous-parens", line=line_num, args=keyword_token
)
elif keyword_token in ("return", "yield"):
self.add_message(
"superfluous-parens", line=line_num, args=keyword_token
)
elif keyword_token not in self._keywords_with_parens:
if not found_and_or:
self.add_message(
"superfluous-parens", line=line_num, args=keyword_token
)
return
elif depth == 1:
# This is a tuple, which is always acceptable.
if token[1] == ",":
return
# 'and' and 'or' are the only boolean operators with lower precedence
# than 'not', so parens are only required when they are found.
if token[1] in ("and", "or"):
found_and_or = True
# A yield inside an expression must always be in parentheses,
# quit early without error.
elif token[1] == "yield":
return
# A generator expression always has a 'for' token in it, and
# the 'for' token is only legal inside parens when it is in a
# generator expression. The parens are necessary here, so bail
# without an error.
elif token[1] == "for":
return
def _opening_bracket(self, tokens, i):
self._push_token(tokens[i][1], i)
# Special case: ignore slices
if tokens[i][1] == "[" and tokens[i + 1][1] == ":":
return
if i > 0 and (
tokens[i - 1][0] == tokenize.NAME
and not (keyword.iskeyword(tokens[i - 1][1]))
or tokens[i - 1][1] in _CLOSING_BRACKETS
):
self._check_space(tokens, i, (_MUST_NOT, _MUST_NOT))
else:
self._check_space(tokens, i, (_IGNORE, _MUST_NOT))
def _closing_bracket(self, tokens, i):
if self._inside_brackets(":"):
self._pop_token()
self._pop_token()
# Special case: ignore slices
if tokens[i - 1][1] == ":" and tokens[i][1] == "]":
return
policy_before = _MUST_NOT
if tokens[i][1] in _CLOSING_BRACKETS and tokens[i - 1][1] == ",":
if _TRAILING_COMMA in self.config.no_space_check:
policy_before = _IGNORE
self._check_space(tokens, i, (policy_before, _IGNORE))
def _has_valid_type_annotation(self, tokens, i):
"""Extended check of PEP-484 type hint presence"""
if not self._inside_brackets("("):
return False
# token_info
# type string start end line
# 0 1 2 3 4
bracket_level = 0
for token in tokens[i - 1 :: -1]:
if token[1] == ":":
return True
if token[1] == "(":
return False
if token[1] == "]":
bracket_level += 1
elif token[1] == "[":
bracket_level -= 1
elif token[1] == ",":
if not bracket_level:
return False
elif token[1] in (".", "..."):
continue
elif token[0] not in (tokenize.NAME, tokenize.STRING, tokenize.NL):
return False
return False
def _check_equals_spacing(self, tokens, i):
"""Check the spacing of a single equals sign."""
if self._has_valid_type_annotation(tokens, i):
self._check_space(tokens, i, (_MUST, _MUST))
elif self._inside_brackets("(") or self._inside_brackets("lambda"):
self._check_space(tokens, i, (_MUST_NOT, _MUST_NOT))
else:
self._check_space(tokens, i, (_MUST, _MUST))
def _open_lambda(self, tokens, i): # pylint:disable=unused-argument
self._push_token("lambda", i)
def _handle_colon(self, tokens, i):
# Special case: ignore slices
if self._inside_brackets("["):
return
if self._inside_brackets("{") and _DICT_SEPARATOR in self.config.no_space_check:
policy = (_IGNORE, _IGNORE)
else:
policy = (_MUST_NOT, _MUST)
self._check_space(tokens, i, policy)
if self._inside_brackets("lambda"):
self._pop_token()
elif self._inside_brackets("{"):
self._push_token(":", i)
def _handle_comma(self, tokens, i):
# Only require a following whitespace if this is
# not a hanging comma before a closing bracket.
if tokens[i + 1][1] in _CLOSING_BRACKETS:
self._check_space(tokens, i, (_MUST_NOT, _IGNORE))
else:
self._check_space(tokens, i, (_MUST_NOT, _MUST))
if self._inside_brackets(":"):
self._pop_token()
def _check_surrounded_by_space(self, tokens, i):
"""Check that a binary operator is surrounded by exactly one space."""
self._check_space(tokens, i, (_MUST, _MUST))
def _check_space(self, tokens, i, policies):
def _policy_string(policy):
if policy == _MUST:
return "Exactly one", "required"
return "No", "allowed"
def _name_construct(token):
if token[1] == ",":
return "comma"
if token[1] == ":":
return ":"
if token[1] in "()[]{}":
return "bracket"
if token[1] in ("<", ">", "<=", ">=", "!=", "=="):
return "comparison"
if self._inside_brackets("("):
return "keyword argument assignment"
return "assignment"
good_space = [True, True]
token = tokens[i]
pairs = [(tokens[i - 1], token), (token, tokens[i + 1])]
for other_idx, (policy, token_pair) in enumerate(zip(policies, pairs)):
if token_pair[other_idx][0] in _EOL or policy == _IGNORE:
continue
distance = _column_distance(*token_pair)
if distance is None:
continue
good_space[other_idx] = (policy == _MUST and distance == 1) or (
policy == _MUST_NOT and distance == 0
)
warnings = []
if not any(good_space) and policies[0] == policies[1]:
warnings.append((policies[0], "around"))
else:
for ok, policy, position in zip(good_space, policies, ("before", "after")):
if not ok:
warnings.append((policy, position))
for policy, position in warnings:
construct = _name_construct(token)
count, state = _policy_string(policy)
self.add_message(
"bad-whitespace",
line=token[2][0],
args=(count, state, position, construct, _underline_token(token)),
col_offset=token[2][1],
)
def _inside_brackets(self, left):
return self._bracket_stack[-1] == left
def _prepare_token_dispatcher(self):
raw = [
(_KEYWORD_TOKENS, self._check_keyword_parentheses),
(_OPENING_BRACKETS, self._opening_bracket),
(_CLOSING_BRACKETS, self._closing_bracket),
(["="], self._check_equals_spacing),
(_SPACED_OPERATORS, self._check_surrounded_by_space),
([","], self._handle_comma),
([":"], self._handle_colon),
(["lambda"], self._open_lambda),
]
dispatch = {}
for tokens, handler in raw:
for token in tokens:
dispatch[token] = handler
return dispatch
def process_tokens(self, tokens):
"""process tokens and search for :
_ non strict indentation (i.e. not always using the <indent> parameter as
indent unit)
_ too long lines (i.e. longer than <max_chars>)
_ optionally bad construct (if given, bad_construct must be a compiled
regular expression).
"""
self._bracket_stack = [None]
indents = [0]
check_equal = False
line_num = 0
self._lines = {}
self._visited_lines = {}
token_handlers = self._prepare_token_dispatcher()
self._last_line_ending = None
last_blank_line_num = 0
self._current_line = ContinuedLineState(tokens, self.config)
for idx, (tok_type, token, start, _, line) in enumerate(tokens):
if start[0] != line_num:
line_num = start[0]
# A tokenizer oddity: if an indented line contains a multi-line
# docstring, the line member of the INDENT token does not contain
# the full line; therefore we check the next token on the line.
if tok_type == tokenize.INDENT: