Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

format.py 44KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092
  1. # -*- coding: utf-8 -*-
  2. # Copyright (c) 2006-2014 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr>
  3. # Copyright (c) 2012-2015 Google, Inc.
  4. # Copyright (c) 2013 moxian <aleftmail@inbox.ru>
  5. # Copyright (c) 2014-2018 Claudiu Popa <pcmanticore@gmail.com>
  6. # Copyright (c) 2014 frost-nzcr4 <frost.nzcr4@jagmort.com>
  7. # Copyright (c) 2014 Brett Cannon <brett@python.org>
  8. # Copyright (c) 2014 Michal Nowikowski <godfryd@gmail.com>
  9. # Copyright (c) 2014 Arun Persaud <arun@nubati.net>
  10. # Copyright (c) 2015 Mike Frysinger <vapier@gentoo.org>
  11. # Copyright (c) 2015 Fabio Natali <me@fabionatali.com>
  12. # Copyright (c) 2015 Harut <yes@harutune.name>
  13. # Copyright (c) 2015 Mihai Balint <balint.mihai@gmail.com>
  14. # Copyright (c) 2015 Pavel Roskin <proski@gnu.org>
  15. # Copyright (c) 2015 Ionel Cristian Maries <contact@ionelmc.ro>
  16. # Copyright (c) 2016 Petr Pulc <petrpulc@gmail.com>
  17. # Copyright (c) 2016 Moises Lopez <moylop260@vauxoo.com>
  18. # Copyright (c) 2016 Ashley Whetter <ashley@awhetter.co.uk>
  19. # Copyright (c) 2017 hippo91 <guillaume.peillex@gmail.com>
  20. # Copyright (c) 2017 Krzysztof Czapla <k.czapla68@gmail.com>
  21. # Copyright (c) 2017 Łukasz Rogalski <rogalski.91@gmail.com>
  22. # Copyright (c) 2017 James M. Allen <james.m.allen@gmail.com>
  23. # Copyright (c) 2017 vinnyrose <vinnyrose@users.noreply.github.com>
  24. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  25. # For details: https://github.com/PyCQA/pylint/blob/master/COPYING
  26. """Python code format's checker.
  27. By default try to follow Guido's style guide :
  28. http://www.python.org/doc/essays/styleguide.html
  29. Some parts of the process_token method is based from The Tab Nanny std module.
  30. """
  31. import keyword
  32. import sys
  33. import tokenize
  34. from functools import reduce # pylint: disable=redefined-builtin
  35. import six
  36. from six.moves import zip, map, filter # pylint: disable=redefined-builtin
  37. from astroid import nodes
  38. from pylint.interfaces import ITokenChecker, IAstroidChecker, IRawChecker
  39. from pylint.checkers import BaseTokenChecker
  40. from pylint.checkers.utils import check_messages
  41. from pylint.utils import WarningScope, OPTION_RGX
  42. _ASYNC_TOKEN = 'async'
  43. _CONTINUATION_BLOCK_OPENERS = ['elif', 'except', 'for', 'if', 'while', 'def', 'class']
  44. _KEYWORD_TOKENS = ['assert', 'del', 'elif', 'except', 'for', 'if', 'in', 'not',
  45. 'raise', 'return', 'while', 'yield']
  46. if sys.version_info < (3, 0):
  47. _KEYWORD_TOKENS.append('print')
  48. _SPACED_OPERATORS = ['==', '<', '>', '!=', '<>', '<=', '>=',
  49. '+=', '-=', '*=', '**=', '/=', '//=', '&=', '|=', '^=',
  50. '%=', '>>=', '<<=']
  51. _OPENING_BRACKETS = ['(', '[', '{']
  52. _CLOSING_BRACKETS = [')', ']', '}']
  53. _TAB_LENGTH = 8
  54. _EOL = frozenset([tokenize.NEWLINE, tokenize.NL, tokenize.COMMENT])
  55. _JUNK_TOKENS = (tokenize.COMMENT, tokenize.NL)
  56. # Whitespace checking policy constants
  57. _MUST = 0
  58. _MUST_NOT = 1
  59. _IGNORE = 2
  60. # Whitespace checking config constants
  61. _DICT_SEPARATOR = 'dict-separator'
  62. _TRAILING_COMMA = 'trailing-comma'
  63. _EMPTY_LINE = 'empty-line'
  64. _NO_SPACE_CHECK_CHOICES = [_TRAILING_COMMA, _DICT_SEPARATOR, _EMPTY_LINE]
  65. _DEFAULT_NO_SPACE_CHECK_CHOICES = [_TRAILING_COMMA, _DICT_SEPARATOR]
  66. MSGS = {
  67. 'C0301': ('Line too long (%s/%s)',
  68. 'line-too-long',
  69. 'Used when a line is longer than a given number of characters.'),
  70. 'C0302': ('Too many lines in module (%s/%s)', # was W0302
  71. 'too-many-lines',
  72. 'Used when a module has too much lines, reducing its readability.'
  73. ),
  74. 'C0303': ('Trailing whitespace',
  75. 'trailing-whitespace',
  76. 'Used when there is whitespace between the end of a line and the '
  77. 'newline.'),
  78. 'C0304': ('Final newline missing',
  79. 'missing-final-newline',
  80. 'Used when the last line in a file is missing a newline.'),
  81. 'C0305': ('Trailing newlines',
  82. 'trailing-newlines',
  83. 'Used when there are trailing blank lines in a file.'),
  84. 'W0311': ('Bad indentation. Found %s %s, expected %s',
  85. 'bad-indentation',
  86. 'Used when an unexpected number of indentation\'s tabulations or '
  87. 'spaces has been found.'),
  88. 'C0330': ('Wrong %s indentation%s%s.\n%s%s',
  89. 'bad-continuation',
  90. 'TODO'),
  91. 'W0312': ('Found indentation with %ss instead of %ss',
  92. 'mixed-indentation',
  93. 'Used when there are some mixed tabs and spaces in a module.'),
  94. 'W0301': ('Unnecessary semicolon', # was W0106
  95. 'unnecessary-semicolon',
  96. 'Used when a statement is ended by a semi-colon (";"), which \
  97. isn\'t necessary (that\'s python, not C ;).'),
  98. 'C0321': ('More than one statement on a single line',
  99. 'multiple-statements',
  100. 'Used when more than on statement are found on the same line.',
  101. {'scope': WarningScope.NODE}),
  102. 'C0325' : ('Unnecessary parens after %r keyword',
  103. 'superfluous-parens',
  104. 'Used when a single item in parentheses follows an if, for, or '
  105. 'other keyword.'),
  106. 'C0326': ('%s space %s %s %s\n%s',
  107. 'bad-whitespace',
  108. ('Used when a wrong number of spaces is used around an operator, '
  109. 'bracket or block opener.'),
  110. {'old_names': [('C0323', 'no-space-after-operator'),
  111. ('C0324', 'no-space-after-comma'),
  112. ('C0322', 'no-space-before-operator')]}),
  113. 'W0332': ('Use of "l" as long integer identifier',
  114. 'lowercase-l-suffix',
  115. 'Used when a lower case "l" is used to mark a long integer. You '
  116. 'should use a upper case "L" since the letter "l" looks too much '
  117. 'like the digit "1"',
  118. {'maxversion': (3, 0)}),
  119. 'C0327': ('Mixed line endings LF and CRLF',
  120. 'mixed-line-endings',
  121. 'Used when there are mixed (LF and CRLF) newline signs in a file.'),
  122. 'C0328': ('Unexpected line ending format. There is \'%s\' while it should be \'%s\'.',
  123. 'unexpected-line-ending-format',
  124. 'Used when there is different newline than expected.'),
  125. }
  126. def _underline_token(token):
  127. length = token[3][1] - token[2][1]
  128. offset = token[2][1]
  129. referenced_line = token[4]
  130. # If the referenced line does not end with a newline char, fix it
  131. if referenced_line[-1] != '\n':
  132. referenced_line += '\n'
  133. return referenced_line + (' ' * offset) + ('^' * length)
  134. def _column_distance(token1, token2):
  135. if token1 == token2:
  136. return 0
  137. if token2[3] < token1[3]:
  138. token1, token2 = token2, token1
  139. if token1[3][0] != token2[2][0]:
  140. return None
  141. return token2[2][1] - token1[3][1]
  142. def _last_token_on_line_is(tokens, line_end, token):
  143. return (line_end > 0 and tokens.token(line_end-1) == token or
  144. line_end > 1 and tokens.token(line_end-2) == token
  145. and tokens.type(line_end-1) == tokenize.COMMENT)
  146. def _token_followed_by_eol(tokens, position):
  147. return (tokens.type(position+1) == tokenize.NL or
  148. tokens.type(position+1) == tokenize.COMMENT and
  149. tokens.type(position+2) == tokenize.NL)
  150. def _get_indent_length(line):
  151. """Return the length of the indentation on the given token's line."""
  152. result = 0
  153. for char in line:
  154. if char == ' ':
  155. result += 1
  156. elif char == '\t':
  157. result += _TAB_LENGTH
  158. else:
  159. break
  160. return result
  161. def _get_indent_hint_line(bar_positions, bad_position):
  162. """Return a line with |s for each of the positions in the given lists."""
  163. if not bar_positions:
  164. return ('', '')
  165. delta_message = ''
  166. markers = [(pos, '|') for pos in bar_positions]
  167. if len(markers) == 1:
  168. # if we have only one marker we'll provide an extra hint on how to fix
  169. expected_position = markers[0][0]
  170. delta = abs(expected_position - bad_position)
  171. direction = 'add' if expected_position > bad_position else 'remove'
  172. delta_message = _CONTINUATION_HINT_MESSAGE % (
  173. direction, delta, 's' if delta > 1 else '')
  174. markers.append((bad_position, '^'))
  175. markers.sort()
  176. line = [' '] * (markers[-1][0] + 1)
  177. for position, marker in markers:
  178. line[position] = marker
  179. return (''.join(line), delta_message)
  180. class _ContinuedIndent(object):
  181. __slots__ = ('valid_outdent_offsets',
  182. 'valid_continuation_offsets',
  183. 'context_type',
  184. 'token',
  185. 'position')
  186. def __init__(self,
  187. context_type,
  188. token,
  189. position,
  190. valid_outdent_offsets,
  191. valid_continuation_offsets):
  192. self.valid_outdent_offsets = valid_outdent_offsets
  193. self.valid_continuation_offsets = valid_continuation_offsets
  194. self.context_type = context_type
  195. self.position = position
  196. self.token = token
  197. # The contexts for hanging indents.
  198. # A hanging indented dictionary value after :
  199. HANGING_DICT_VALUE = 'dict-value'
  200. # Hanging indentation in an expression.
  201. HANGING = 'hanging'
  202. # Hanging indentation in a block header.
  203. HANGING_BLOCK = 'hanging-block'
  204. # Continued indentation inside an expression.
  205. CONTINUED = 'continued'
  206. # Continued indentation in a block header.
  207. CONTINUED_BLOCK = 'continued-block'
  208. SINGLE_LINE = 'single'
  209. WITH_BODY = 'multi'
  210. _CONTINUATION_MSG_PARTS = {
  211. HANGING_DICT_VALUE: ('hanging', ' in dict value'),
  212. HANGING: ('hanging', ''),
  213. HANGING_BLOCK: ('hanging', ' before block'),
  214. CONTINUED: ('continued', ''),
  215. CONTINUED_BLOCK: ('continued', ' before block'),
  216. }
  217. _CONTINUATION_HINT_MESSAGE = ' (%s %d space%s)' # Ex: (remove 2 spaces)
  218. def _Offsets(*args):
  219. """Valid indentation offsets for a continued line."""
  220. return dict((a, None) for a in args)
  221. def _BeforeBlockOffsets(single, with_body):
  222. """Valid alternative indent offsets for continued lines before blocks.
  223. :param int single: Valid offset for statements on a single logical line.
  224. :param int with_body: Valid offset for statements on several lines.
  225. :returns: A dictionary mapping indent offsets to a string representing
  226. whether the indent if for a line or block.
  227. :rtype: dict
  228. """
  229. return {single: SINGLE_LINE, with_body: WITH_BODY}
  230. class TokenWrapper(object):
  231. """A wrapper for readable access to token information."""
  232. def __init__(self, tokens):
  233. self._tokens = tokens
  234. def token(self, idx):
  235. return self._tokens[idx][1]
  236. def type(self, idx):
  237. return self._tokens[idx][0]
  238. def start_line(self, idx):
  239. return self._tokens[idx][2][0]
  240. def start_col(self, idx):
  241. return self._tokens[idx][2][1]
  242. def line(self, idx):
  243. return self._tokens[idx][4]
  244. class ContinuedLineState(object):
  245. """Tracker for continued indentation inside a logical line."""
  246. def __init__(self, tokens, config):
  247. self._line_start = -1
  248. self._cont_stack = []
  249. self._is_block_opener = False
  250. self.retained_warnings = []
  251. self._config = config
  252. self._tokens = TokenWrapper(tokens)
  253. @property
  254. def has_content(self):
  255. return bool(self._cont_stack)
  256. @property
  257. def _block_indent_size(self):
  258. return len(self._config.indent_string.replace('\t', ' ' * _TAB_LENGTH))
  259. @property
  260. def _continuation_size(self):
  261. return self._config.indent_after_paren
  262. def handle_line_start(self, pos):
  263. """Record the first non-junk token at the start of a line."""
  264. if self._line_start > -1:
  265. return
  266. check_token_position = pos
  267. if self._tokens.token(pos) == _ASYNC_TOKEN:
  268. check_token_position += 1
  269. self._is_block_opener = self._tokens.token(
  270. check_token_position
  271. ) in _CONTINUATION_BLOCK_OPENERS
  272. self._line_start = pos
  273. def next_physical_line(self):
  274. """Prepares the tracker for a new physical line (NL)."""
  275. self._line_start = -1
  276. self._is_block_opener = False
  277. def next_logical_line(self):
  278. """Prepares the tracker for a new logical line (NEWLINE).
  279. A new logical line only starts with block indentation.
  280. """
  281. self.next_physical_line()
  282. self.retained_warnings = []
  283. self._cont_stack = []
  284. def add_block_warning(self, token_position, state, valid_offsets):
  285. self.retained_warnings.append((token_position, state, valid_offsets))
  286. def get_valid_offsets(self, idx):
  287. """Returns the valid offsets for the token at the given position."""
  288. # The closing brace on a dict or the 'for' in a dict comprehension may
  289. # reset two indent levels because the dict value is ended implicitly
  290. stack_top = -1
  291. if self._tokens.token(idx) in ('}', 'for') and self._cont_stack[-1].token == ':':
  292. stack_top = -2
  293. indent = self._cont_stack[stack_top]
  294. if self._tokens.token(idx) in _CLOSING_BRACKETS:
  295. valid_offsets = indent.valid_outdent_offsets
  296. else:
  297. valid_offsets = indent.valid_continuation_offsets
  298. return indent, valid_offsets.copy()
  299. def _hanging_indent_after_bracket(self, bracket, position):
  300. """Extracts indentation information for a hanging indent."""
  301. indentation = _get_indent_length(self._tokens.line(position))
  302. if self._is_block_opener and self._continuation_size == self._block_indent_size:
  303. return _ContinuedIndent(
  304. HANGING_BLOCK,
  305. bracket,
  306. position,
  307. _Offsets(indentation + self._continuation_size, indentation),
  308. _BeforeBlockOffsets(indentation + self._continuation_size,
  309. indentation + self._continuation_size * 2))
  310. if bracket == ':':
  311. # If the dict key was on the same line as the open brace, the new
  312. # correct indent should be relative to the key instead of the
  313. # current indent level
  314. paren_align = self._cont_stack[-1].valid_outdent_offsets
  315. next_align = self._cont_stack[-1].valid_continuation_offsets.copy()
  316. next_align_keys = list(next_align.keys())
  317. next_align[next_align_keys[0] + self._continuation_size] = True
  318. # Note that the continuation of
  319. # d = {
  320. # 'a': 'b'
  321. # 'c'
  322. # }
  323. # is handled by the special-casing for hanging continued string indents.
  324. return _ContinuedIndent(HANGING_DICT_VALUE, bracket, position, paren_align, next_align)
  325. return _ContinuedIndent(
  326. HANGING,
  327. bracket,
  328. position,
  329. _Offsets(indentation, indentation + self._continuation_size),
  330. _Offsets(indentation + self._continuation_size))
  331. def _continuation_inside_bracket(self, bracket, pos):
  332. """Extracts indentation information for a continued indent."""
  333. indentation = _get_indent_length(self._tokens.line(pos))
  334. token_start = self._tokens.start_col(pos)
  335. next_token_start = self._tokens.start_col(pos + 1)
  336. if self._is_block_opener and next_token_start - indentation == self._block_indent_size:
  337. return _ContinuedIndent(
  338. CONTINUED_BLOCK,
  339. bracket,
  340. pos,
  341. _Offsets(token_start),
  342. _BeforeBlockOffsets(next_token_start, next_token_start + self._continuation_size))
  343. return _ContinuedIndent(
  344. CONTINUED,
  345. bracket,
  346. pos,
  347. _Offsets(token_start),
  348. _Offsets(next_token_start))
  349. def pop_token(self):
  350. self._cont_stack.pop()
  351. def push_token(self, token, position):
  352. """Pushes a new token for continued indentation on the stack.
  353. Tokens that can modify continued indentation offsets are:
  354. * opening brackets
  355. * 'lambda'
  356. * : inside dictionaries
  357. push_token relies on the caller to filter out those
  358. interesting tokens.
  359. :param int token: The concrete token
  360. :param int position: The position of the token in the stream.
  361. """
  362. if _token_followed_by_eol(self._tokens, position):
  363. self._cont_stack.append(
  364. self._hanging_indent_after_bracket(token, position))
  365. else:
  366. self._cont_stack.append(
  367. self._continuation_inside_bracket(token, position))
  368. class FormatChecker(BaseTokenChecker):
  369. """checks for :
  370. * unauthorized constructions
  371. * strict indentation
  372. * line length
  373. """
  374. __implements__ = (ITokenChecker, IAstroidChecker, IRawChecker)
  375. # configuration section name
  376. name = 'format'
  377. # messages
  378. msgs = MSGS
  379. # configuration options
  380. # for available dict keys/values see the optik parser 'add_option' method
  381. options = (('max-line-length',
  382. {'default' : 100, 'type' : "int", 'metavar' : '<int>',
  383. 'help' : 'Maximum number of characters on a single line.'}),
  384. ('ignore-long-lines',
  385. {'type': 'regexp', 'metavar': '<regexp>',
  386. 'default': r'^\s*(# )?<?https?://\S+>?$',
  387. 'help': ('Regexp for a line that is allowed to be longer than '
  388. 'the limit.')}),
  389. ('single-line-if-stmt',
  390. {'default': False, 'type' : 'yn', 'metavar' : '<y_or_n>',
  391. 'help' : ('Allow the body of an if to be on the same '
  392. 'line as the test if there is no else.')}),
  393. ('single-line-class-stmt',
  394. {'default': False, 'type' : 'yn', 'metavar' : '<y_or_n>',
  395. 'help' : ('Allow the body of a class to be on the same '
  396. 'line as the declaration if body contains '
  397. 'single statement.')}),
  398. ('no-space-check',
  399. {'default': ','.join(_DEFAULT_NO_SPACE_CHECK_CHOICES),
  400. 'metavar': ','.join(_NO_SPACE_CHECK_CHOICES),
  401. 'type': 'multiple_choice',
  402. 'choices': _NO_SPACE_CHECK_CHOICES,
  403. 'help': ('List of optional constructs for which whitespace '
  404. 'checking is disabled. '
  405. '`'+ _DICT_SEPARATOR + '` is used to allow tabulation '
  406. 'in dicts, etc.: {1 : 1,\\n222: 2}. '
  407. '`'+ _TRAILING_COMMA + '` allows a space between comma '
  408. 'and closing bracket: (a, ). '
  409. '`'+ _EMPTY_LINE + '` allows space-only lines.')}),
  410. ('max-module-lines',
  411. {'default' : 1000, 'type' : 'int', 'metavar' : '<int>',
  412. 'help': 'Maximum number of lines in a module'}
  413. ),
  414. ('indent-string',
  415. {'default' : ' ', 'type' : "non_empty_string", 'metavar' : '<string>',
  416. 'help' : 'String used as indentation unit. This is usually '
  417. '" " (4 spaces) or "\\t" (1 tab).'}),
  418. ('indent-after-paren',
  419. {'type': 'int', 'metavar': '<int>', 'default': 4,
  420. 'help': 'Number of spaces of indent required inside a hanging '
  421. ' or continued line.'}),
  422. ('expected-line-ending-format',
  423. {'type': 'choice', 'metavar': '<empty or LF or CRLF>', 'default': '',
  424. 'choices': ['', 'LF', 'CRLF'],
  425. 'help': ('Expected format of line ending, '
  426. 'e.g. empty (any line ending), LF or CRLF.')}),
  427. )
  428. def __init__(self, linter=None):
  429. BaseTokenChecker.__init__(self, linter)
  430. self._lines = None
  431. self._visited_lines = None
  432. self._bracket_stack = [None]
  433. def _pop_token(self):
  434. self._bracket_stack.pop()
  435. self._current_line.pop_token()
  436. def _push_token(self, token, idx):
  437. self._bracket_stack.append(token)
  438. self._current_line.push_token(token, idx)
  439. def new_line(self, tokens, line_end, line_start):
  440. """a new line has been encountered, process it if necessary"""
  441. if _last_token_on_line_is(tokens, line_end, ';'):
  442. self.add_message('unnecessary-semicolon', line=tokens.start_line(line_end))
  443. line_num = tokens.start_line(line_start)
  444. line = tokens.line(line_start)
  445. if tokens.type(line_start) not in _JUNK_TOKENS:
  446. self._lines[line_num] = line.split('\n')[0]
  447. self.check_lines(line, line_num)
  448. def process_module(self, module):
  449. self._keywords_with_parens = set()
  450. if 'print_function' in module.future_imports:
  451. self._keywords_with_parens.add('print')
  452. def _check_keyword_parentheses(self, tokens, start):
  453. """Check that there are not unnecessary parens after a keyword.
  454. Parens are unnecessary if there is exactly one balanced outer pair on a
  455. line, and it is followed by a colon, and contains no commas (i.e. is not a
  456. tuple).
  457. Args:
  458. tokens: list of Tokens; the entire list of Tokens.
  459. start: int; the position of the keyword in the token list.
  460. """
  461. # If the next token is not a paren, we're fine.
  462. if self._inside_brackets(':') and tokens[start][1] == 'for':
  463. self._pop_token()
  464. if tokens[start+1][1] != '(':
  465. return
  466. found_and_or = False
  467. depth = 0
  468. keyword_token = str(tokens[start][1])
  469. line_num = tokens[start][2][0]
  470. for i in range(start, len(tokens) - 1):
  471. token = tokens[i]
  472. # If we hit a newline, then assume any parens were for continuation.
  473. if token[0] == tokenize.NL:
  474. return
  475. if token[1] == '(':
  476. depth += 1
  477. elif token[1] == ')':
  478. depth -= 1
  479. if depth:
  480. continue
  481. # ')' can't happen after if (foo), since it would be a syntax error.
  482. if (tokens[i+1][1] in (':', ')', ']', '}', 'in') or
  483. tokens[i+1][0] in (tokenize.NEWLINE,
  484. tokenize.ENDMARKER,
  485. tokenize.COMMENT)):
  486. # The empty tuple () is always accepted.
  487. if i == start + 2:
  488. return
  489. if keyword_token == 'not':
  490. if not found_and_or:
  491. self.add_message('superfluous-parens', line=line_num,
  492. args=keyword_token)
  493. elif keyword_token in ('return', 'yield'):
  494. self.add_message('superfluous-parens', line=line_num,
  495. args=keyword_token)
  496. elif keyword_token not in self._keywords_with_parens:
  497. if not found_and_or:
  498. self.add_message('superfluous-parens', line=line_num,
  499. args=keyword_token)
  500. return
  501. elif depth == 1:
  502. # This is a tuple, which is always acceptable.
  503. if token[1] == ',':
  504. return
  505. # 'and' and 'or' are the only boolean operators with lower precedence
  506. # than 'not', so parens are only required when they are found.
  507. elif token[1] in ('and', 'or'):
  508. found_and_or = True
  509. # A yield inside an expression must always be in parentheses,
  510. # quit early without error.
  511. elif token[1] == 'yield':
  512. return
  513. # A generator expression always has a 'for' token in it, and
  514. # the 'for' token is only legal inside parens when it is in a
  515. # generator expression. The parens are necessary here, so bail
  516. # without an error.
  517. elif token[1] == 'for':
  518. return
  519. def _opening_bracket(self, tokens, i):
  520. self._push_token(tokens[i][1], i)
  521. # Special case: ignore slices
  522. if tokens[i][1] == '[' and tokens[i+1][1] == ':':
  523. return
  524. if (i > 0 and (tokens[i-1][0] == tokenize.NAME and
  525. not (keyword.iskeyword(tokens[i-1][1]))
  526. or tokens[i-1][1] in _CLOSING_BRACKETS)):
  527. self._check_space(tokens, i, (_MUST_NOT, _MUST_NOT))
  528. else:
  529. self._check_space(tokens, i, (_IGNORE, _MUST_NOT))
  530. def _closing_bracket(self, tokens, i):
  531. if self._inside_brackets(':'):
  532. self._pop_token()
  533. self._pop_token()
  534. # Special case: ignore slices
  535. if tokens[i-1][1] == ':' and tokens[i][1] == ']':
  536. return
  537. policy_before = _MUST_NOT
  538. if tokens[i][1] in _CLOSING_BRACKETS and tokens[i-1][1] == ',':
  539. if _TRAILING_COMMA in self.config.no_space_check:
  540. policy_before = _IGNORE
  541. self._check_space(tokens, i, (policy_before, _IGNORE))
  542. def _has_valid_type_annotation(self, tokens, i):
  543. """Extended check of PEP-484 type hint presence"""
  544. if not self._inside_brackets('('):
  545. return False
  546. bracket_level = 0
  547. for token in tokens[i-1::-1]:
  548. if token[1] == ':':
  549. return True
  550. if token[1] == '(':
  551. return False
  552. if token[1] == ']':
  553. bracket_level += 1
  554. elif token[1] == '[':
  555. bracket_level -= 1
  556. elif token[1] == ',':
  557. if not bracket_level:
  558. return False
  559. elif token[1] == '.':
  560. continue
  561. elif token[0] not in (tokenize.NAME, tokenize.STRING):
  562. return False
  563. return False
  564. def _check_equals_spacing(self, tokens, i):
  565. """Check the spacing of a single equals sign."""
  566. if self._has_valid_type_annotation(tokens, i):
  567. self._check_space(tokens, i, (_MUST, _MUST))
  568. elif self._inside_brackets('(') or self._inside_brackets('lambda'):
  569. self._check_space(tokens, i, (_MUST_NOT, _MUST_NOT))
  570. else:
  571. self._check_space(tokens, i, (_MUST, _MUST))
  572. def _open_lambda(self, tokens, i): # pylint:disable=unused-argument
  573. self._push_token('lambda', i)
  574. def _handle_colon(self, tokens, i):
  575. # Special case: ignore slices
  576. if self._inside_brackets('['):
  577. return
  578. if (self._inside_brackets('{') and
  579. _DICT_SEPARATOR in self.config.no_space_check):
  580. policy = (_IGNORE, _IGNORE)
  581. else:
  582. policy = (_MUST_NOT, _MUST)
  583. self._check_space(tokens, i, policy)
  584. if self._inside_brackets('lambda'):
  585. self._pop_token()
  586. elif self._inside_brackets('{'):
  587. self._push_token(':', i)
  588. def _handle_comma(self, tokens, i):
  589. # Only require a following whitespace if this is
  590. # not a hanging comma before a closing bracket.
  591. if tokens[i+1][1] in _CLOSING_BRACKETS:
  592. self._check_space(tokens, i, (_MUST_NOT, _IGNORE))
  593. else:
  594. self._check_space(tokens, i, (_MUST_NOT, _MUST))
  595. if self._inside_brackets(':'):
  596. self._pop_token()
  597. def _check_surrounded_by_space(self, tokens, i):
  598. """Check that a binary operator is surrounded by exactly one space."""
  599. self._check_space(tokens, i, (_MUST, _MUST))
  600. def _check_space(self, tokens, i, policies):
  601. def _policy_string(policy):
  602. if policy == _MUST:
  603. return 'Exactly one', 'required'
  604. return 'No', 'allowed'
  605. def _name_construct(token):
  606. if token[1] == ',':
  607. return 'comma'
  608. if token[1] == ':':
  609. return ':'
  610. if token[1] in '()[]{}':
  611. return 'bracket'
  612. if token[1] in ('<', '>', '<=', '>=', '!=', '=='):
  613. return 'comparison'
  614. if self._inside_brackets('('):
  615. return 'keyword argument assignment'
  616. return 'assignment'
  617. good_space = [True, True]
  618. token = tokens[i]
  619. pairs = [(tokens[i-1], token), (token, tokens[i+1])]
  620. for other_idx, (policy, token_pair) in enumerate(zip(policies, pairs)):
  621. if token_pair[other_idx][0] in _EOL or policy == _IGNORE:
  622. continue
  623. distance = _column_distance(*token_pair)
  624. if distance is None:
  625. continue
  626. good_space[other_idx] = (
  627. (policy == _MUST and distance == 1) or
  628. (policy == _MUST_NOT and distance == 0))
  629. warnings = []
  630. if not any(good_space) and policies[0] == policies[1]:
  631. warnings.append((policies[0], 'around'))
  632. else:
  633. for ok, policy, position in zip(good_space, policies, ('before', 'after')):
  634. if not ok:
  635. warnings.append((policy, position))
  636. for policy, position in warnings:
  637. construct = _name_construct(token)
  638. count, state = _policy_string(policy)
  639. self.add_message('bad-whitespace', line=token[2][0],
  640. args=(count, state, position, construct,
  641. _underline_token(token)))
  642. def _inside_brackets(self, left):
  643. return self._bracket_stack[-1] == left
  644. def _prepare_token_dispatcher(self):
  645. raw = [
  646. (_KEYWORD_TOKENS,
  647. self._check_keyword_parentheses),
  648. (_OPENING_BRACKETS, self._opening_bracket),
  649. (_CLOSING_BRACKETS, self._closing_bracket),
  650. (['='], self._check_equals_spacing),
  651. (_SPACED_OPERATORS, self._check_surrounded_by_space),
  652. ([','], self._handle_comma),
  653. ([':'], self._handle_colon),
  654. (['lambda'], self._open_lambda),
  655. ]
  656. dispatch = {}
  657. for tokens, handler in raw:
  658. for token in tokens:
  659. dispatch[token] = handler
  660. return dispatch
  661. def process_tokens(self, tokens):
  662. """process tokens and search for :
  663. _ non strict indentation (i.e. not always using the <indent> parameter as
  664. indent unit)
  665. _ too long lines (i.e. longer than <max_chars>)
  666. _ optionally bad construct (if given, bad_construct must be a compiled
  667. regular expression).
  668. """
  669. self._bracket_stack = [None]
  670. indents = [0]
  671. check_equal = False
  672. line_num = 0
  673. self._lines = {}
  674. self._visited_lines = {}
  675. token_handlers = self._prepare_token_dispatcher()
  676. self._last_line_ending = None
  677. last_blank_line_num = 0
  678. self._current_line = ContinuedLineState(tokens, self.config)
  679. for idx, (tok_type, token, start, _, line) in enumerate(tokens):
  680. if start[0] != line_num:
  681. line_num = start[0]
  682. # A tokenizer oddity: if an indented line contains a multi-line
  683. # docstring, the line member of the INDENT token does not contain
  684. # the full line; therefore we check the next token on the line.
  685. if tok_type == tokenize.INDENT:
  686. self.new_line(TokenWrapper(tokens), idx-1, idx+1)
  687. else:
  688. self.new_line(TokenWrapper(tokens), idx-1, idx)
  689. if tok_type == tokenize.NEWLINE:
  690. # a program statement, or ENDMARKER, will eventually follow,
  691. # after some (possibly empty) run of tokens of the form
  692. # (NL | COMMENT)* (INDENT | DEDENT+)?
  693. # If an INDENT appears, setting check_equal is wrong, and will
  694. # be undone when we see the INDENT.
  695. check_equal = True
  696. self._process_retained_warnings(TokenWrapper(tokens), idx)
  697. self._current_line.next_logical_line()
  698. self._check_line_ending(token, line_num)
  699. elif tok_type == tokenize.INDENT:
  700. check_equal = False
  701. self.check_indent_level(token, indents[-1]+1, line_num)
  702. indents.append(indents[-1]+1)
  703. elif tok_type == tokenize.DEDENT:
  704. # there's nothing we need to check here! what's important is
  705. # that when the run of DEDENTs ends, the indentation of the
  706. # program statement (or ENDMARKER) that triggered the run is
  707. # equal to what's left at the top of the indents stack
  708. check_equal = True
  709. if len(indents) > 1:
  710. del indents[-1]
  711. elif tok_type == tokenize.NL:
  712. if not line.strip('\r\n'):
  713. last_blank_line_num = line_num
  714. self._check_continued_indentation(TokenWrapper(tokens), idx+1)
  715. self._current_line.next_physical_line()
  716. elif tok_type != tokenize.COMMENT:
  717. self._current_line.handle_line_start(idx)
  718. # This is the first concrete token following a NEWLINE, so it
  719. # must be the first token of the next program statement, or an
  720. # ENDMARKER; the "line" argument exposes the leading whitespace
  721. # for this statement; in the case of ENDMARKER, line is an empty
  722. # string, so will properly match the empty string with which the
  723. # "indents" stack was seeded
  724. if check_equal:
  725. check_equal = False
  726. self.check_indent_level(line, indents[-1], line_num)
  727. if tok_type == tokenize.NUMBER and token.endswith('l'):
  728. self.add_message('lowercase-l-suffix', line=line_num)
  729. try:
  730. handler = token_handlers[token]
  731. except KeyError:
  732. pass
  733. else:
  734. handler(tokens, idx)
  735. line_num -= 1 # to be ok with "wc -l"
  736. if line_num > self.config.max_module_lines:
  737. # Get the line where the too-many-lines (or its message id)
  738. # was disabled or default to 1.
  739. symbol = self.linter.msgs_store.check_message_id('too-many-lines')
  740. names = (symbol.msgid, 'too-many-lines')
  741. line = next(filter(None,
  742. map(self.linter._pragma_lineno.get, names)), 1)
  743. self.add_message('too-many-lines',
  744. args=(line_num, self.config.max_module_lines),
  745. line=line)
  746. # See if there are any trailing lines. Do not complain about empty
  747. # files like __init__.py markers.
  748. if line_num == last_blank_line_num and line_num > 0:
  749. self.add_message('trailing-newlines', line=line_num)
  750. def _check_line_ending(self, line_ending, line_num):
  751. # check if line endings are mixed
  752. if self._last_line_ending is not None:
  753. if line_ending != self._last_line_ending:
  754. self.add_message('mixed-line-endings', line=line_num)
  755. self._last_line_ending = line_ending
  756. # check if line ending is as expected
  757. expected = self.config.expected_line_ending_format
  758. if expected:
  759. # reduce multiple \n\n\n\n to one \n
  760. line_ending = reduce(lambda x, y: x + y if x != y else x, line_ending, "")
  761. line_ending = 'LF' if line_ending == '\n' else 'CRLF'
  762. if line_ending != expected:
  763. self.add_message('unexpected-line-ending-format', args=(line_ending, expected),
  764. line=line_num)
  765. def _process_retained_warnings(self, tokens, current_pos):
  766. single_line_block_stmt = not _last_token_on_line_is(tokens, current_pos, ':')
  767. for indent_pos, state, offsets in self._current_line.retained_warnings:
  768. block_type = offsets[tokens.start_col(indent_pos)]
  769. hints = dict((k, v) for k, v in six.iteritems(offsets)
  770. if v != block_type)
  771. if single_line_block_stmt and block_type == WITH_BODY:
  772. self._add_continuation_message(state, hints, tokens, indent_pos)
  773. elif not single_line_block_stmt and block_type == SINGLE_LINE:
  774. self._add_continuation_message(state, hints, tokens, indent_pos)
  775. def _check_continued_indentation(self, tokens, next_idx):
  776. def same_token_around_nl(token_type):
  777. return (tokens.type(next_idx) == token_type and
  778. tokens.type(next_idx-2) == token_type)
  779. # Do not issue any warnings if the next line is empty.
  780. if not self._current_line.has_content or tokens.type(next_idx) == tokenize.NL:
  781. return
  782. state, valid_offsets = self._current_line.get_valid_offsets(next_idx)
  783. # Special handling for hanging comments and strings. If the last line ended
  784. # with a comment (string) and the new line contains only a comment, the line
  785. # may also be indented to the start of the previous token.
  786. if same_token_around_nl(tokenize.COMMENT) or same_token_around_nl(tokenize.STRING):
  787. valid_offsets[tokens.start_col(next_idx-2)] = True
  788. # We can only decide if the indentation of a continued line before opening
  789. # a new block is valid once we know of the body of the block is on the
  790. # same line as the block opener. Since the token processing is single-pass,
  791. # emitting those warnings is delayed until the block opener is processed.
  792. if (state.context_type in (HANGING_BLOCK, CONTINUED_BLOCK)
  793. and tokens.start_col(next_idx) in valid_offsets):
  794. self._current_line.add_block_warning(next_idx, state, valid_offsets)
  795. elif tokens.start_col(next_idx) not in valid_offsets:
  796. self._add_continuation_message(state, valid_offsets, tokens, next_idx)
  797. def _add_continuation_message(self, state, offsets, tokens, position):
  798. readable_type, readable_position = _CONTINUATION_MSG_PARTS[state.context_type]
  799. hint_line, delta_message = _get_indent_hint_line(offsets, tokens.start_col(position))
  800. self.add_message(
  801. 'bad-continuation',
  802. line=tokens.start_line(position),
  803. args=(readable_type, readable_position, delta_message,
  804. tokens.line(position), hint_line))
  805. @check_messages('multiple-statements')
  806. def visit_default(self, node):
  807. """check the node line number and check it if not yet done"""
  808. if not node.is_statement:
  809. return
  810. if not node.root().pure_python:
  811. return # XXX block visit of child nodes
  812. prev_sibl = node.previous_sibling()
  813. if prev_sibl is not None:
  814. prev_line = prev_sibl.fromlineno
  815. else:
  816. # The line on which a finally: occurs in a try/finally
  817. # is not directly represented in the AST. We infer it
  818. # by taking the last line of the body and adding 1, which
  819. # should be the line of finally:
  820. if (isinstance(node.parent, nodes.TryFinally)
  821. and node in node.parent.finalbody):
  822. prev_line = node.parent.body[0].tolineno + 1
  823. else:
  824. prev_line = node.parent.statement().fromlineno
  825. line = node.fromlineno
  826. assert line, node
  827. if prev_line == line and self._visited_lines.get(line) != 2:
  828. self._check_multi_statement_line(node, line)
  829. return
  830. if line in self._visited_lines:
  831. return
  832. try:
  833. tolineno = node.blockstart_tolineno
  834. except AttributeError:
  835. tolineno = node.tolineno
  836. assert tolineno, node
  837. lines = []
  838. for line in range(line, tolineno + 1):
  839. self._visited_lines[line] = 1
  840. try:
  841. lines.append(self._lines[line].rstrip())
  842. except KeyError:
  843. lines.append('')
  844. def _check_multi_statement_line(self, node, line):
  845. """Check for lines containing multiple statements."""
  846. # Do not warn about multiple nested context managers
  847. # in with statements.
  848. if isinstance(node, nodes.With):
  849. return
  850. # For try... except... finally..., the two nodes
  851. # appear to be on the same line due to how the AST is built.
  852. if (isinstance(node, nodes.TryExcept) and
  853. isinstance(node.parent, nodes.TryFinally)):
  854. return
  855. if (isinstance(node.parent, nodes.If) and not node.parent.orelse
  856. and self.config.single_line_if_stmt):
  857. return
  858. if (isinstance(node.parent, nodes.ClassDef) and len(node.parent.body) == 1
  859. and self.config.single_line_class_stmt):
  860. return
  861. self.add_message('multiple-statements', node=node)
  862. self._visited_lines[line] = 2
  863. def check_lines(self, lines, i):
  864. """check lines have less than a maximum number of characters
  865. """
  866. max_chars = self.config.max_line_length
  867. ignore_long_line = self.config.ignore_long_lines
  868. def check_line(line, i):
  869. if not line.endswith('\n'):
  870. self.add_message('missing-final-newline', line=i)
  871. else:
  872. # exclude \f (formfeed) from the rstrip
  873. stripped_line = line.rstrip('\t\n\r\v ')
  874. if not stripped_line and _EMPTY_LINE in self.config.no_space_check:
  875. # allow empty lines
  876. pass
  877. elif line[len(stripped_line):] not in ('\n', '\r\n'):
  878. self.add_message('trailing-whitespace', line=i)
  879. # Don't count excess whitespace in the line length.
  880. line = stripped_line
  881. mobj = OPTION_RGX.search(line)
  882. if mobj and '=' in line:
  883. front_of_equal, _, back_of_equal = mobj.group(1).partition('=')
  884. if front_of_equal.strip() == 'disable':
  885. if 'line-too-long' in [_msg_id.strip() for _msg_id in back_of_equal.split(',')]:
  886. return None
  887. line = line.rsplit('#', 1)[0].rstrip()
  888. if len(line) > max_chars and not ignore_long_line.search(line):
  889. self.add_message('line-too-long', line=i, args=(len(line), max_chars))
  890. return i + 1
  891. unsplit_ends = {
  892. u'\v',
  893. u'\x0b',
  894. u'\f',
  895. u'\x0c',
  896. u'\x1c',
  897. u'\x1d',
  898. u'\x1e',
  899. u'\x85',
  900. u'\u2028',
  901. u'\u2029'
  902. }
  903. unsplit = []
  904. for line in lines.splitlines(True):
  905. if line[-1] in unsplit_ends:
  906. unsplit.append(line)
  907. continue
  908. if unsplit:
  909. unsplit.append(line)
  910. line = ''.join(unsplit)
  911. unsplit = []
  912. i = check_line(line, i)
  913. if i is None:
  914. break
  915. if unsplit:
  916. check_line(''.join(unsplit), i)
  917. def check_indent_level(self, string, expected, line_num):
  918. """return the indent level of the string
  919. """
  920. indent = self.config.indent_string
  921. if indent == '\\t': # \t is not interpreted in the configuration file
  922. indent = '\t'
  923. level = 0
  924. unit_size = len(indent)
  925. while string[:unit_size] == indent:
  926. string = string[unit_size:]
  927. level += 1
  928. suppl = ''
  929. while string and string[0] in ' \t':
  930. if string[0] != indent[0]:
  931. if string[0] == '\t':
  932. args = ('tab', 'space')
  933. else:
  934. args = ('space', 'tab')
  935. self.add_message('mixed-indentation', args=args, line=line_num)
  936. return level
  937. suppl += string[0]
  938. string = string[1:]
  939. if level != expected or suppl:
  940. i_type = 'spaces'
  941. if indent[0] == '\t':
  942. i_type = 'tabs'
  943. self.add_message('bad-indentation', line=line_num,
  944. args=(level * unit_size + len(suppl), i_type,
  945. expected * unit_size))
  946. return None
  947. def register(linter):
  948. """required method to auto register this checker """
  949. linter.register_checker(FormatChecker(linter))