-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathflake8_rst_docstrings.py
More file actions
1132 lines (983 loc) · 38.8 KB
/
flake8_rst_docstrings.py
File metadata and controls
1132 lines (983 loc) · 38.8 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
"""Check Python docstrings validate as reStructuredText (RST).
This is a plugin for the tool flake8 tool for checking Python
source code.
"""
import logging
import re
import sys
import textwrap
import tokenize as tk
from itertools import chain, dropwhile
try:
from StringIO import StringIO
except ImportError: # Python 3.0 and later
from io import StringIO
from io import TextIOWrapper
import rstcheck
#####################################
# Start of backported tokenize code #
#####################################
# If possible (python >= 3.2) use tokenize.open to open files, so PEP 263
# encoding markers are interpreted.
try:
tokenize_open = tk.open
except AttributeError:
# Fall back on a backport of the encoding aware tokenize open function,
# which requires we back port tokenize.detect_encoding to implement.
from codecs import lookup, BOM_UTF8
from io import open as io_open
cookie_re = re.compile(r"^[ \t\f]*#.*?coding[:=][ \t]*([-\w.]+)")
blank_re = re.compile(br"^[ \t\f]*(?:[#\r\n]|$)")
# I don't think 'blank regular expression' is well named, think
# it looks for blank line after any Python # comment removed.
# Key test case of interest is hashbang lines!
assert blank_re.match(b"\n")
assert blank_re.match(b"# Comment\n")
assert blank_re.match(b"#!/usr/bin/python\n")
assert blank_re.match(b"#!/usr/bin/env python\n")
assert not blank_re.match(b'"""Welcome\n')
assert not blank_re.match(b'"""Welcome"""\n')
def _get_normal_name(orig_enc):
"""Imitates get_normal_name in tokenizer.c (PRIVATE)."""
# sys.stderr.write("DEBUG: _get_normal_name(%r)\n" % orig_enc)
# Only care about the first 12 characters.
enc = orig_enc[:12].lower().replace("_", "-")
if enc == "utf-8" or enc.startswith("utf-8-"):
return "utf-8"
if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or enc.startswith(
("latin-1-", "iso-8859-1-", "iso-latin-1-")
):
return "iso-8859-1"
return orig_enc
def _find_cookie(line, filename, bom_found):
"""Find encoding string in a line of Python (PRIVATE)."""
# sys.stderr.write("DEBUG: _find_cookie(%r, %r, %r)\n"
# % (line, filename, bom_found))
match = cookie_re.match(line)
if not match:
return None
encoding = _get_normal_name(match.group(1))
try:
lookup(encoding)
except LookupError:
# This behaviour mimics the Python interpreter
raise SyntaxError(
"unknown encoding for {!r}: {}".format(filename, encoding)
)
if bom_found:
if encoding != "utf-8":
# This behaviour mimics the Python interpreter
raise SyntaxError("encoding problem for {!r}: utf-8".format(filename))
encoding += "-sig"
return encoding
def tokenize_open(filename):
"""Simulate opening a Python file read only with the correct encoding.
While this was based on the Python 3 standard library function
tokenize.open in order to backport it to Python 2.7, this proved
painful.
Note that because this text will later be fed into ``exex(...)`` we
would hit SyntaxError encoding declaration in Unicode string, so the
handle returned has the encoding line masked out!
Note we don't just remove the line as that would throw off the line
numbers, it is replaced with a Python comment.
"""
# sys.stderr.write("DEBUG: tokenize_open(%r)\n" % filename)
# Will check the first & second lines for an encoding
# AND REMOVE IT FROM THE TEXT RETURNED
with io_open(filename, "rb") as handle:
lines = list(handle)
# Find the encoding
first = lines[0] if lines else b""
second = lines[1] if len(lines) > 1 else b""
default = "utf-8"
bom_found = False
if first.startswith(BOM_UTF8):
bom_found = True
first = first[3:]
default = "utf-8-sig"
encoding = _find_cookie(first, filename, bom_found)
if encoding:
lines[0] = "# original encoding removed\n"
if not encoding and blank_re.match(first):
# sys.stderr.write("DEBUG: Trying second line %r\n"
# % second)
encoding = _find_cookie(second, filename, bom_found)
if encoding:
lines[1] = "# original encoding removed\n"
if not encoding:
encoding = default
# sys.stderr.write("DEBUG: tokenize_open using encoding=%r\n"
# % encoding)
# Apply the encoding, using StringIO as we removed the
# original encoding to help legacy code using exec.
# for b in lines:
# sys.stderr.write(b"DEBUG: " + b)
return StringIO("".join(b.decode(encoding) for b in lines))
###################################
# End of backported tokenize code #
###################################
__version__ = "0.1.0"
log = logging.getLogger(__name__)
rst_prefix = "RST"
rst_fail_load = 900
rst_fail_parse = 901
rst_fail_all = 902
rst_fail_lint = 903
rst_unknown_prefix = 999
# Level 1 - info
code_mapping_info = {
"Possible title underline, too short for the title.": 1,
"Unexpected possible title overline or transition.": 2,
}
# Level 2 - warning
code_mapping_warning = {
# XXX ends without a blank line; unexpected unindent:
"Block quote ends without a blank line; unexpected unindent.": 1,
"Bullet list ends without a blank line; unexpected unindent.": 2,
"Definition list ends without a blank line; unexpected unindent.": 3,
"Enumerated list ends without a blank line; unexpected unindent.": 4,
"Explicit markup ends without a blank line; unexpected unindent.": 5,
"Field list ends without a blank line; unexpected unindent.": 6,
"Literal block ends without a blank line; unexpected unindent.": 7,
"Option list ends without a blank line; unexpected unindent.": 8,
# Other:
"Inline strong start-string without end-string.": 10,
"Blank line required after table.": 11,
"Title underline too short.": 12,
"Inline emphasis start-string without end-string.": 13,
"Inline literal start-string without end-string.": 14,
"Inline interpreted text or phrase reference start-string without end-string.": 15,
"Multiple roles in interpreted text (both prefix and suffix present; only one allowed).": 16, # noqa: E501
"Mismatch: both interpreted text role suffix and reference suffix.": 17,
"Literal block expected; none found.": 18,
"Inline substitution_reference start-string without end-string.": 19,
}
# Level 3 - error
code_mapping_error = {
"Unexpected indentation.": 1,
"Malformed table.": 2,
# e.g. Unknown directive type "req".
"Unknown directive type": 3,
# e.g. Unknown interpreted text role "need".
"Unknown interpreted text role": 4,
# e.g. Undefined substitution referenced: "dict".
"Undefined substitution referenced:": 5,
# e.g. Unknown target name: "license_txt".
"Unknown target name:": 6,
}
# Level 4 - severe
code_mapping_severe = {"Unexpected section title.": 1}
code_mappings_by_level = {
1: code_mapping_info,
2: code_mapping_warning,
3: code_mapping_error,
4: code_mapping_severe,
}
def code_mapping(level, msg, default=99):
"""Return an error code between 0 and 99."""
try:
return code_mappings_by_level[level][msg]
except KeyError:
pass
# Following assumes any variable messages take the format
# of 'Fixed text "variable text".' only:
# e.g. 'Unknown directive type "req".'
# ---> 'Unknown directive type'
# e.g. 'Unknown interpreted text role "need".'
# ---> 'Unknown interpreted text role'
if msg.count('"') == 2 and ' "' in msg and msg.endswith('".'):
txt = msg[: msg.index(' "')]
return code_mappings_by_level[level].get(txt, default)
return default
####################################
# Start of code copied from PEP257 #
####################################
# This is the reference implementation of the alogrithm
# in PEP257 for removing the indentation of a docstring,
# which has been placed in the public domain.
#
# This includes the minor change from sys.maxint to
# sys.maxsize for Python 3 compatibility.
#
# https://www.python.org/dev/peps/pep-0257/#handling-docstring-indentation
def trim(docstring):
"""PEP257 docstring indentation trim function."""
if not docstring:
return ""
# Convert tabs to spaces (following the normal Python rules)
# and split into a list of lines:
lines = docstring.expandtabs().splitlines()
# Determine minimum indentation (first line doesn't count):
indent = sys.maxsize
for line in lines[1:]:
stripped = line.lstrip()
if stripped:
indent = min(indent, len(line) - len(stripped))
# Remove indentation (first line is special):
trimmed = [lines[0].strip()]
if indent < sys.maxsize:
for line in lines[1:]:
trimmed.append(line[indent:].rstrip())
# Strip off trailing and leading blank lines:
while trimmed and not trimmed[-1]:
trimmed.pop()
while trimmed and not trimmed[0]:
trimmed.pop(0)
# Return a single string:
return "\n".join(trimmed)
##################################
# End of code copied from PEP257 #
##################################
def dequote_docstring(text):
"""Remove the quotes delimiting a docstring."""
# TODO: Process escaped characters unless raw mode?
text = text.strip()
if len(text) > 6 and text[:3] == text[-3:] == '"""':
# Standard case, """..."""
return text[3:-3]
if len(text) > 7 and text[:4] in ('u"""', 'r"""') and text[-3:] == '"""':
# Unicode, u"""...""", or raw r"""..."""
return text[4:-3]
# Other flake8 tools will report atypical quotes:
if len(text) > 6 and text[:3] == text[-3:] == "'''":
return text[3:-3]
if len(text) > 7 and text[:4] in ("u'''", "r'''") and text[-3:] == "'''":
return text[4:-3]
if len(text) > 2 and text[0] == text[-1] == '"':
return text[1:-1]
if len(text) > 3 and text[:2] in ('u"', 'r"') and text[-1] == '"':
return text[2:-1]
if len(text) > 2 and text[0] == text[-1] == "'":
return text[1:-1]
if len(text) > 3 and text[:2] in ("u'", "r'") and text[-1] == "'":
return text[2:-1]
raise ValueError("Bad quotes!")
##################################################
# Start of code copied from pydocstyle/parser.py #
##################################################
def humanize(string):
"""Make a string human readable."""
return re.compile(r"(.)([A-Z]+)").sub(r"\1 \2", string).lower()
class Value(object):
"""A generic object with a list of preset fields."""
def __init__(self, *args):
"""Initialize."""
if len(self._fields) != len(args):
raise ValueError(
"got {} arguments for {} fields for {}: {}".format(
len(args), len(self._fields), self.__class__.__name__, self._fields
)
)
vars(self).update(zip(self._fields, args))
def __hash__(self):
"""Hash."""
return hash(repr(self))
def __eq__(self, other):
"""Equality."""
return other and vars(self) == vars(other)
def __repr__(self):
"""Representation."""
kwargs = ", ".join(
"{}={!r}".format(field, getattr(self, field)) for field in self._fields
)
return "{}({})".format(self.__class__.__name__, kwargs)
class Definition(Value):
"""A Python source code definition (could be class, function, etc)."""
_fields = (
"name",
"_source",
"start",
"end",
"decorators",
"docstring",
"children",
"parent",
"skipped_error_codes",
)
_human = property(lambda self: humanize(type(self).__name__))
kind = property(lambda self: self._human.split()[-1])
module = property(lambda self: self.parent.module)
all = property(lambda self: self.module.all)
_slice = property(lambda self: slice(self.start - 1, self.end))
is_class = False
def __iter__(self):
"""Iterate."""
return chain([self], *self.children)
@property
def _publicity(self):
return {True: "public", False: "private"}[self.is_public]
@property
def source(self):
"""Return the source code for the definition."""
full_src = self._source[self._slice]
def is_empty_or_comment(line):
return line.strip() == "" or line.strip().startswith("#")
filtered_src = dropwhile(is_empty_or_comment, reversed(full_src))
return "".join(reversed(list(filtered_src)))
def __str__(self):
"""Definition as a string."""
out = "in {} {} `{}`".format(self._publicity, self._human, self.name)
if self.skipped_error_codes:
out += " (skipping {})".format(self.skipped_error_codes)
return out
class Module(Definition):
"""A Python source code module."""
_fields = (
"name",
"_source",
"start",
"end",
"decorators",
"docstring",
"children",
"parent",
"_all",
"future_imports",
"skipped_error_codes",
)
_nest = staticmethod(lambda s: {"def": Function, "class": Class}[s])
module = property(lambda self: self)
all = property(lambda self: self._all)
@property
def is_public(self):
"""Is the module public."""
return not self.name.startswith("_") or self.name.startswith("__")
def __str__(self):
"""Definition as a string."""
return "at module level"
class Package(Module):
"""A package is a __init__.py module."""
class Function(Definition):
"""A Python source code function."""
_nest = staticmethod(lambda s: {"def": NestedFunction, "class": NestedClass}[s])
@property
def is_public(self):
"""Return True iff this function should be considered public."""
if self.all is not None:
return self.name in self.all
else:
return not self.name.startswith("_")
@property
def is_test(self):
"""Return True if this function is a test function/method.
We exclude tests from the imperative mood check, because to phrase
their docstring in the imperative mood, they would have to start with
a highly redundant "Test that ...".
"""
return self.name.startswith("test") or self.name == "runTest"
class NestedFunction(Function):
"""A Python source code nested function."""
is_public = False
class Method(Function):
"""A Python source code method."""
@property
def is_magic(self):
"""Return True iff this method is a magic method (e.g., `__str__`)."""
return (
self.name.startswith("__")
and self.name.endswith("__")
and self.name not in VARIADIC_MAGIC_METHODS
)
@property
def is_public(self):
"""Return True iff this method should be considered public."""
# Check if we are a setter/deleter method, and mark as private if so.
for decorator in self.decorators:
# Given 'foo', match 'foo.bar' but not 'foobar' or 'sfoo'
if re.compile(r"^{}\.".format(self.name)).match(decorator.name):
return False
name_is_public = (
not self.name.startswith("_")
or self.name in VARIADIC_MAGIC_METHODS
or self.is_magic
)
return self.parent.is_public and name_is_public
class Class(Definition):
"""A Python source code class."""
_nest = staticmethod(lambda s: {"def": Method, "class": NestedClass}[s])
is_public = Function.is_public
is_class = True
class NestedClass(Class):
"""A Python source code nested class."""
@property
def is_public(self):
"""Return True iff this class should be considered public."""
return (
not self.name.startswith("_")
and self.parent.is_class
and self.parent.is_public
)
class Decorator(Value):
"""A decorator for function, method or class."""
_fields = "name arguments".split()
VARIADIC_MAGIC_METHODS = ("__init__", "__call__", "__new__")
class AllError(Exception):
"""Raised when there is a problem with __all__ when parsing."""
def __init__(self, message):
"""Initialize the error with a more specific message."""
Exception.__init__(
self,
message
+ textwrap.dedent(
"""
That means pydocstyle cannot decide which definitions are
public. Variable __all__ should be present at most once in
each file, in form
`__all__ = ('a_public_function', 'APublicClass', ...)`.
More info on __all__: http://stackoverflow.com/q/44834/. ')
"""
),
)
class TokenStream(object):
"""Token stream."""
# A logical newline is where a new expression or statement begins. When
# there is a physical new line, but not a logical one, for example:
# (x +
# y)
# The token will be tk.NL, not tk.NEWLINE.
LOGICAL_NEWLINES = {tk.NEWLINE, tk.INDENT, tk.DEDENT}
def __init__(self, filelike):
"""Initialize."""
self._generator = tk.generate_tokens(filelike.readline)
self.current = Token(*next(self._generator, None))
self.line = self.current.start[0]
self.log = log
self.got_logical_newline = True
def move(self):
"""Move."""
previous = self.current
current = self._next_from_generator()
self.current = None if current is None else Token(*current)
self.line = self.current.start[0] if self.current else self.line
self.got_logical_newline = previous.kind in self.LOGICAL_NEWLINES
return previous
def _next_from_generator(self):
try:
return next(self._generator, None)
except (SyntaxError, tk.TokenError):
self.log.warning("error generating tokens", exc_info=True)
return None
def __iter__(self):
"""Iterate."""
while True:
if self.current is not None:
yield self.current
else:
return
self.move()
class TokenKind(int):
"""Kind of token."""
def __repr__(self):
"""Representation."""
return "tk.{}".format(tk.tok_name[self])
class Token(Value):
"""Token."""
_fields = "kind value start end source".split()
def __init__(self, *args):
"""Initialize."""
super(Token, self).__init__(*args)
self.kind = TokenKind(self.kind)
class Parser(object):
"""A Python source code parser."""
def parse(self, filelike, filename):
"""Parse the given file-like object and return its Module object."""
self.log = log
self.source = filelike.readlines()
src = "".join(self.source)
# This may raise a SyntaxError:
compile(src, filename, "exec")
self.stream = TokenStream(StringIO(src))
self.filename = filename
self.all = None
self.future_imports = set()
self._accumulated_decorators = []
return self.parse_module()
# TODO: remove
def __call__(self, *args, **kwargs):
"""Call the parse method."""
return self.parse(*args, **kwargs)
current = property(lambda self: self.stream.current)
line = property(lambda self: self.stream.line)
def consume(self, kind):
"""Consume one token and verify it is of the expected kind."""
next_token = self.stream.move()
assert next_token.kind == kind
def leapfrog(self, kind, value=None):
"""Skip tokens in the stream until a certain token kind is reached.
If `value` is specified, tokens whose values are different will also
be skipped.
"""
while self.current is not None:
if self.current.kind == kind and (
value is None or self.current.value == value
):
self.consume(kind)
return
self.stream.move()
def parse_docstring(self):
"""Parse a single docstring and return its value."""
self.log.debug(
"parsing docstring, token is %r (%s)", self.current.kind, self.current.value
)
while self.current.kind in (tk.COMMENT, tk.NEWLINE, tk.NL):
self.stream.move()
self.log.debug(
"parsing docstring, token is %r (%s)",
self.current.kind,
self.current.value,
)
if self.current.kind == tk.STRING:
docstring = self.current.value
self.stream.move()
return docstring
return None
def parse_decorators(self): # noqa : D401
"""Called after first @ is found.
Parse decorators into self._accumulated_decorators.
Continue to do so until encountering the 'def' or 'class' start token.
"""
name = []
arguments = []
at_arguments = False
while self.current is not None:
self.log.debug(
"parsing decorators, current token is %r (%s)",
self.current.kind,
self.current.value,
)
if self.current.kind == tk.NAME and self.current.value in ["def", "class"]:
# Done with decorators - found function or class proper
break
elif self.current.kind == tk.OP and self.current.value == "@":
# New decorator found. Store the decorator accumulated so far:
self._accumulated_decorators.append(
Decorator("".join(name), "".join(arguments))
)
# Now reset to begin accumulating the new decorator:
name = []
arguments = []
at_arguments = False
elif self.current.kind == tk.OP and self.current.value == "(":
at_arguments = True
elif self.current.kind == tk.OP and self.current.value == ")":
# Ignore close parenthesis
pass
elif self.current.kind == tk.NEWLINE or self.current.kind == tk.NL:
# Ignore newlines
pass
else:
# Keep accumulating current decorator's name or argument.
if not at_arguments:
name.append(self.current.value)
else:
arguments.append(self.current.value)
self.stream.move()
# Add decorator accumulated so far
self._accumulated_decorators.append(
Decorator("".join(name), "".join(arguments))
)
def parse_definitions(self, class_, all=False):
"""Parse multiple definitions and yield them."""
while self.current is not None:
self.log.debug(
"parsing definition list, current token is %r (%s)",
self.current.kind,
self.current.value,
)
self.log.debug("got_newline: %s", self.stream.got_logical_newline)
if all and self.current.value == "__all__":
self.parse_all()
elif (
self.current.kind == tk.OP
and self.current.value == "@"
and self.stream.got_logical_newline
):
self.consume(tk.OP)
self.parse_decorators()
elif self.current.value in ["def", "class"]:
yield self.parse_definition(class_._nest(self.current.value))
elif self.current.kind == tk.INDENT:
self.consume(tk.INDENT)
for definition in self.parse_definitions(class_):
yield definition
elif self.current.kind == tk.DEDENT:
self.consume(tk.DEDENT)
return
elif self.current.value == "from":
self.parse_from_import_statement()
else:
self.stream.move()
def parse_all(self):
"""Parse the __all__ definition in a module."""
assert self.current.value == "__all__"
self.consume(tk.NAME)
if self.current.value != "=":
raise AllError("Could not evaluate contents of __all__. ")
self.consume(tk.OP)
if self.current.value not in "([":
raise AllError("Could not evaluate contents of __all__. ")
self.consume(tk.OP)
self.all = []
all_content = "("
while self.current.kind != tk.OP or self.current.value not in ")]":
if self.current.kind in (tk.NL, tk.COMMENT):
pass
elif self.current.kind == tk.STRING or self.current.value == ",":
all_content += self.current.value
else:
raise AllError(
"Unexpected token kind in __all__: {!r}. ".format(
self.current.kind
)
)
self.stream.move()
self.consume(tk.OP)
all_content += ")"
try:
self.all = eval(all_content, {})
except BaseException as e:
raise AllError(
"Could not evaluate contents of __all__."
"\bThe value was {}. The exception was:\n{}".format(all_content, e)
)
def parse_module(self):
"""Parse a module (and its children) and return a Module object."""
self.log.debug("parsing module.")
start = self.line
docstring = self.parse_docstring()
children = list(self.parse_definitions(Module, all=True))
assert self.current is None, self.current
end = self.line
cls = Module
if self.filename.endswith("__init__.py"):
cls = Package
module = cls(
self.filename,
self.source,
start,
end,
[],
docstring,
children,
None,
self.all,
None,
"",
)
for child in module.children:
child.parent = module
module.future_imports = self.future_imports
self.log.debug("finished parsing module.")
return module
def parse_definition(self, class_):
"""Parse a definition and return its value in a `class_` object."""
start = self.line
self.consume(tk.NAME)
name = self.current.value
self.log.debug("parsing %s '%s'", class_.__name__, name)
self.stream.move()
if self.current.kind == tk.OP and self.current.value == "(":
parenthesis_level = 0
while True:
if self.current.kind == tk.OP:
if self.current.value == "(":
parenthesis_level += 1
elif self.current.value == ")":
parenthesis_level -= 1
if parenthesis_level == 0:
break
self.stream.move()
if self.current.kind != tk.OP or self.current.value != ":":
self.leapfrog(tk.OP, value=":")
else:
self.consume(tk.OP)
if self.current.kind in (tk.NEWLINE, tk.COMMENT):
skipped_error_codes = self.parse_skip_comment()
self.leapfrog(tk.INDENT)
assert self.current.kind != tk.INDENT
docstring = self.parse_docstring()
decorators = self._accumulated_decorators
self.log.debug("current accumulated decorators: %s", decorators)
self._accumulated_decorators = []
self.log.debug("parsing nested definitions.")
children = list(self.parse_definitions(class_))
self.log.debug("finished parsing nested definitions for '%s'", name)
end = self.line - 1
else: # one-liner definition
skipped_error_codes = ""
docstring = self.parse_docstring()
decorators = [] # TODO
children = []
end = self.line
self.leapfrog(tk.NEWLINE)
definition = class_(
name,
self.source,
start,
end,
decorators,
docstring,
children,
None,
skipped_error_codes,
)
for child in definition.children:
child.parent = definition
self.log.debug(
"finished parsing %s '%s'. Next token is %r (%s)",
class_.__name__,
name,
self.current.kind,
self.current.value,
)
return definition
def parse_skip_comment(self):
"""Parse a definition comment for noqa skips."""
skipped_error_codes = ""
if self.current.kind == tk.COMMENT:
if "noqa: " in self.current.value:
skipped_error_codes = "".join(self.current.value.split("noqa: ")[1:])
elif self.current.value.startswith("# noqa"):
skipped_error_codes = "all"
return skipped_error_codes
def check_current(self, kind=None, value=None):
"""Verify the current token is of type `kind` and equals `value`."""
msg = textwrap.dedent(
"""
Unexpected token at line {self.line}:
In file: {self.filename}
Got kind {self.current.kind!r}
Got value {self.current.value}
""".format(
self=self
)
)
kind_valid = self.current.kind == kind if kind else True
value_valid = self.current.value == value if value else True
assert kind_valid and value_valid, msg
def parse_from_import_statement(self):
"""Parse a 'from x import y' statement.
The purpose is to find __future__ statements.
"""
self.log.debug("parsing from/import statement.")
is_future_import = self._parse_from_import_source()
self._parse_from_import_names(is_future_import)
def _parse_from_import_source(self):
"""Parse the 'from x import' part in a 'from x import y' statement.
Return true iff `x` is __future__.
"""
assert self.current.value == "from", self.current.value
self.stream.move()
is_future_import = self.current.value == "__future__"
self.stream.move()
while (
self.current is not None
and self.current.kind in (tk.DOT, tk.NAME, tk.OP)
and self.current.value != "import"
):
self.stream.move()
if self.current is None or self.current.value != "import":
return False
self.check_current(value="import")
assert self.current.value == "import", self.current.value
self.stream.move()
return is_future_import
def _parse_from_import_names(self, is_future_import):
"""Parse the 'y' part in a 'from x import y' statement."""
if self.current.value == "(":
self.consume(tk.OP)
expected_end_kinds = (tk.OP,)
else:
expected_end_kinds = (tk.NEWLINE, tk.ENDMARKER)
while self.current.kind not in expected_end_kinds and not (
self.current.kind == tk.OP and self.current.value == ";"
):
if self.current.kind != tk.NAME:
self.stream.move()
continue
self.log.debug(
"parsing import, token is %r (%s)",
self.current.kind,
self.current.value,
)
if is_future_import:
self.log.debug("found future import: %s", self.current.value)
self.future_imports.add(self.current.value)
self.consume(tk.NAME)
self.log.debug(
"parsing import, token is %r (%s)",
self.current.kind,
self.current.value,
)
if self.current.kind == tk.NAME and self.current.value == "as":
self.consume(tk.NAME) # as
if self.current.kind == tk.NAME:
self.consume(tk.NAME) # new name, irrelevant
if self.current.value == ",":
self.consume(tk.OP)
self.log.debug(
"parsing import, token is %r (%s)",
self.current.kind,
self.current.value,
)
################################################
# End of code copied from pydocstyle/parser.py #
################################################
parse = Parser()
class reStructuredTextChecker(object):
"""Checker of Python docstrings as reStructuredText."""
name = "rst-docstrings"
version = __version__
STDIN_NAMES = {"stdin", "-", "(none)", None}
def __init__(self, tree, filename="(none)"):
"""Initialise."""
self.tree = tree
self.filename = filename
try:
self.load_source()
self.err = None
except Exception as err:
self.source = None
self.err = err
@classmethod
def add_options(cls, parser):
"""Add RST directives and roles options."""
parser.add_option(
"--rst-directives",
metavar="LIST",
default="",
parse_from_config=True,
comma_separated_list=True,
help="Comma-separated list of additional RST directives.",
)
parser.add_option(
"--rst-roles",
metavar="LIST",
default="",