parser.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  1. """Python code parser."""
  2. import sys
  3. import textwrap
  4. import tokenize as tk
  5. from io import StringIO
  6. from itertools import chain, dropwhile
  7. from pathlib import Path
  8. from re import compile as re
  9. from typing import Tuple
  10. from .utils import log
  11. __all__ = (
  12. 'Parser',
  13. 'Definition',
  14. 'Module',
  15. 'Package',
  16. 'Function',
  17. 'NestedFunction',
  18. 'Method',
  19. 'Class',
  20. 'NestedClass',
  21. 'AllError',
  22. 'StringIO',
  23. 'ParseError',
  24. )
  25. class ParseError(Exception):
  26. """An error parsing contents of a Python file."""
  27. def __str__(self):
  28. return "Cannot parse file."
  29. class UnexpectedTokenError(ParseError):
  30. def __init__(self, token, expected_kind):
  31. self.token = token
  32. self.expected_kind = expected_kind
  33. def __str__(self):
  34. return "Unexpected token {}, expected {}".format(
  35. self.token, self.expected_kind
  36. )
  37. def humanize(string):
  38. return re(r'(.)([A-Z]+)').sub(r'\1 \2', string).lower()
  39. class Value:
  40. """A generic object with a list of preset fields."""
  41. def __init__(self, *args):
  42. if len(self._fields) != len(args):
  43. raise ValueError(
  44. 'got {} arguments for {} fields for {}: {}'.format(
  45. len(args),
  46. len(self._fields),
  47. self.__class__.__name__,
  48. self._fields,
  49. )
  50. )
  51. vars(self).update(zip(self._fields, args))
  52. def __hash__(self):
  53. return hash(repr(self))
  54. def __eq__(self, other):
  55. return other and vars(self) == vars(other)
  56. def __repr__(self):
  57. kwargs = ', '.join(
  58. '{}={!r}'.format(field, getattr(self, field))
  59. for field in self._fields
  60. )
  61. return f'{self.__class__.__name__}({kwargs})'
  62. class Definition(Value):
  63. """A Python source code definition (could be class, function, etc)."""
  64. _fields = (
  65. 'name',
  66. '_source',
  67. 'start',
  68. 'end',
  69. 'decorators',
  70. 'docstring',
  71. 'children',
  72. 'callable_args',
  73. 'parent',
  74. 'skipped_error_codes',
  75. ) # type: Tuple[str, ...]
  76. _human = property(lambda self: humanize(type(self).__name__))
  77. kind = property(lambda self: self._human.split()[-1])
  78. module = property(lambda self: self.parent.module)
  79. dunder_all = property(lambda self: self.module.dunder_all)
  80. _slice = property(lambda self: slice(self.start - 1, self.end))
  81. is_class = False
  82. def __iter__(self):
  83. return chain([self], *self.children)
  84. @property
  85. def error_lineno(self):
  86. """Get the line number with which to report violations."""
  87. if isinstance(self.docstring, Docstring):
  88. return self.docstring.start
  89. return self.start
  90. @property
  91. def _publicity(self):
  92. return {True: 'public', False: 'private'}[self.is_public]
  93. @property
  94. def source(self):
  95. """Return the source code for the definition."""
  96. full_src = self._source[self._slice]
  97. def is_empty_or_comment(line):
  98. return line.strip() == '' or line.strip().startswith('#')
  99. filtered_src = dropwhile(is_empty_or_comment, reversed(full_src))
  100. return ''.join(reversed(list(filtered_src)))
  101. def __str__(self):
  102. out = f'in {self._publicity} {self._human} `{self.name}`'
  103. if self.skipped_error_codes:
  104. out += f' (skipping {self.skipped_error_codes})'
  105. return out
  106. class Module(Definition):
  107. """A Python source code module."""
  108. _fields = (
  109. 'name',
  110. '_source',
  111. 'start',
  112. 'end',
  113. 'decorators',
  114. 'docstring',
  115. 'children',
  116. 'parent',
  117. '_dunder_all',
  118. 'dunder_all_error',
  119. 'future_imports',
  120. 'skipped_error_codes',
  121. )
  122. _nest = staticmethod(lambda s: {'def': Function, 'class': Class}[s])
  123. module = property(lambda self: self)
  124. dunder_all = property(lambda self: self._dunder_all)
  125. @property
  126. def is_public(self):
  127. """Return True iff the module is considered public.
  128. This helps determine if it requires a docstring.
  129. """
  130. module_name = Path(self.name).stem
  131. return not self._is_inside_private_package() and self._is_public_name(
  132. module_name
  133. )
  134. def _is_inside_private_package(self):
  135. """Return True if the module is inside a private package."""
  136. path = Path(self.name).parent # Ignore the actual module's name.
  137. syspath = [Path(p) for p in sys.path] # Convert to pathlib.Path.
  138. # Bail if we are at the root directory or in `PYTHONPATH`.
  139. while path != path.parent and path not in syspath:
  140. if self._is_private_name(path.name):
  141. return True
  142. path = path.parent
  143. return False
  144. def _is_public_name(self, module_name):
  145. """Determine whether a "module name" (i.e. module or package name) is public."""
  146. return not module_name.startswith('_') or (
  147. module_name.startswith('__') and module_name.endswith('__')
  148. )
  149. def _is_private_name(self, module_name):
  150. """Determine whether a "module name" (i.e. module or package name) is private."""
  151. return not self._is_public_name(module_name)
  152. def __str__(self):
  153. return 'at module level'
  154. class Package(Module):
  155. """A package is a __init__.py module."""
  156. class Function(Definition):
  157. """A Python source code function."""
  158. _nest = staticmethod(
  159. lambda s: {'def': NestedFunction, 'class': NestedClass}[s]
  160. )
  161. @property
  162. def is_public(self):
  163. """Return True iff this function should be considered public."""
  164. if self.dunder_all is not None:
  165. return self.name in self.dunder_all
  166. else:
  167. return not self.name.startswith('_')
  168. @property
  169. def is_overload(self):
  170. """Return True iff the method decorated with overload."""
  171. return any(
  172. decorator.name == "overload" for decorator in self.decorators
  173. )
  174. def is_property(self, property_decorator_names):
  175. """Return True if the method is decorated with any property decorator."""
  176. return any(
  177. decorator.name in property_decorator_names
  178. for decorator in self.decorators
  179. )
  180. @property
  181. def is_test(self):
  182. """Return True if this function is a test function/method.
  183. We exclude tests from the imperative mood check, because to phrase
  184. their docstring in the imperative mood, they would have to start with
  185. a highly redundant "Test that ...".
  186. """
  187. return self.name.startswith('test') or self.name == 'runTest'
  188. @property
  189. def param_names(self):
  190. """Return the parameter names."""
  191. return self.callable_args
  192. class NestedFunction(Function):
  193. """A Python source code nested function."""
  194. is_public = False
  195. class Method(Function):
  196. """A Python source code method."""
  197. @property
  198. def is_magic(self):
  199. """Return True iff this method is a magic method (e.g., `__str__`)."""
  200. return (
  201. self.name.startswith('__')
  202. and self.name.endswith('__')
  203. and self.name not in VARIADIC_MAGIC_METHODS
  204. )
  205. @property
  206. def is_init(self):
  207. """Return True iff this method is `__init__`."""
  208. return self.name == '__init__'
  209. @property
  210. def is_public(self):
  211. """Return True iff this method should be considered public."""
  212. # Check if we are a setter/deleter method, and mark as private if so.
  213. for decorator in self.decorators:
  214. # Given 'foo', match 'foo.bar' but not 'foobar' or 'sfoo'
  215. if re(fr"^{self.name}\.").match(decorator.name):
  216. return False
  217. name_is_public = (
  218. not self.name.startswith('_')
  219. or self.name in VARIADIC_MAGIC_METHODS
  220. or self.is_magic
  221. )
  222. return self.parent.is_public and name_is_public
  223. @property
  224. def is_static(self):
  225. """Return True iff the method is static."""
  226. for decorator in self.decorators:
  227. if decorator.name == "staticmethod":
  228. return True
  229. return False
  230. class Class(Definition):
  231. """A Python source code class."""
  232. _nest = staticmethod(lambda s: {'def': Method, 'class': NestedClass}[s])
  233. is_public = Function.is_public
  234. is_class = True
  235. class NestedClass(Class):
  236. """A Python source code nested class."""
  237. @property
  238. def is_public(self):
  239. """Return True iff this class should be considered public."""
  240. return (
  241. not self.name.startswith('_')
  242. and self.parent.is_class
  243. and self.parent.is_public
  244. )
  245. class Decorator(Value):
  246. """A decorator for function, method or class."""
  247. _fields = 'name arguments'.split()
  248. class Docstring(str):
  249. """Represent a docstring.
  250. This is a string, but has additional start/end attributes representing
  251. the start and end of the token.
  252. """
  253. def __new__(cls, v, start, end):
  254. return str.__new__(cls, v)
  255. def __init__(self, v, start, end):
  256. self.start = start
  257. self.end = end
  258. VARIADIC_MAGIC_METHODS = ('__init__', '__call__', '__new__')
  259. class AllError(Exception):
  260. """Raised when there is a problem with __all__ when parsing."""
  261. def __init__(self, message):
  262. """Initialize the error with a more specific message."""
  263. Exception.__init__(
  264. self,
  265. message
  266. + textwrap.dedent(
  267. """
  268. That means pydocstyle cannot decide which definitions are
  269. public. Variable __all__ should be present at most once in
  270. each file, in form
  271. `__all__ = ('a_public_function', 'APublicClass', ...)`.
  272. More info on __all__: http://stackoverflow.com/q/44834/. ')
  273. """
  274. ),
  275. )
  276. class TokenStream:
  277. # A logical newline is where a new expression or statement begins. When
  278. # there is a physical new line, but not a logical one, for example:
  279. # (x +
  280. # y)
  281. # The token will be tk.NL, not tk.NEWLINE.
  282. LOGICAL_NEWLINES = {tk.NEWLINE, tk.INDENT, tk.DEDENT}
  283. def __init__(self, filelike):
  284. self._generator = tk.generate_tokens(filelike.readline)
  285. self.current = Token(*next(self._generator, None))
  286. self.line = self.current.start[0]
  287. self.log = log
  288. self.got_logical_newline = True
  289. def move(self):
  290. previous = self.current
  291. current = self._next_from_generator()
  292. self.current = None if current is None else Token(*current)
  293. self.line = self.current.start[0] if self.current else self.line
  294. is_logical_blank = previous.kind in (tk.NL, tk.COMMENT)
  295. self.got_logical_newline = (
  296. previous.kind in self.LOGICAL_NEWLINES
  297. # Retain logical_newline status if last line was logically blank
  298. or (self.got_logical_newline and is_logical_blank)
  299. )
  300. return previous
  301. def _next_from_generator(self):
  302. try:
  303. return next(self._generator, None)
  304. except (SyntaxError, tk.TokenError):
  305. self.log.warning('error generating tokens', exc_info=True)
  306. return None
  307. def __iter__(self):
  308. while True:
  309. if self.current is not None:
  310. yield self.current
  311. else:
  312. return
  313. self.move()
  314. class TokenKind(int):
  315. def __repr__(self):
  316. return "tk.{}".format(tk.tok_name[self])
  317. class Token(Value):
  318. _fields = 'kind value start end source'.split()
  319. def __init__(self, *args):
  320. super().__init__(*args)
  321. self.kind = TokenKind(self.kind)
  322. def __str__(self):
  323. return f"{self.kind!r} ({self.value})"
  324. class Parser:
  325. """A Python source code parser."""
  326. def parse(self, filelike, filename):
  327. """Parse the given file-like object and return its Module object."""
  328. self.log = log
  329. self.source = filelike.readlines()
  330. src = ''.join(self.source)
  331. try:
  332. compile(src, filename, 'exec')
  333. except SyntaxError as error:
  334. raise ParseError() from error
  335. self.stream = TokenStream(StringIO(src))
  336. self.filename = filename
  337. self.dunder_all = None
  338. self.dunder_all_error = None
  339. self.future_imports = set()
  340. self._accumulated_decorators = []
  341. return self.parse_module()
  342. # TODO: remove
  343. def __call__(self, *args, **kwargs):
  344. """Call the parse method."""
  345. return self.parse(*args, **kwargs)
  346. current = property(lambda self: self.stream.current)
  347. line = property(lambda self: self.stream.line)
  348. def consume(self, kind):
  349. """Consume one token and verify it is of the expected kind."""
  350. next_token = self.stream.move()
  351. if next_token.kind != kind:
  352. raise UnexpectedTokenError(token=next_token, expected_kind=kind)
  353. def leapfrog(self, kind, value=None):
  354. """Skip tokens in the stream until a certain token kind is reached.
  355. If `value` is specified, tokens whose values are different will also
  356. be skipped.
  357. """
  358. while self.current is not None:
  359. if self.current.kind == kind and (
  360. value is None or self.current.value == value
  361. ):
  362. self.consume(kind)
  363. return
  364. self.stream.move()
  365. def parse_docstring(self):
  366. """Parse a single docstring and return its value."""
  367. self.log.debug("parsing docstring, token is %s", self.current)
  368. while self.current.kind in (tk.COMMENT, tk.NEWLINE, tk.NL):
  369. self.stream.move()
  370. self.log.debug(
  371. "parsing docstring, token is %r (%s)",
  372. self.current.kind,
  373. self.current.value,
  374. )
  375. if self.current.kind == tk.STRING:
  376. docstring = Docstring(
  377. self.current.value, self.current.start[0], self.current.end[0]
  378. )
  379. self.stream.move()
  380. return docstring
  381. return None
  382. def parse_decorators(self):
  383. """Parse decorators into self._accumulated_decorators.
  384. Called after first @ is found.
  385. Continue to do so until encountering the 'def' or 'class' start token.
  386. """
  387. name = []
  388. arguments = []
  389. at_arguments = False
  390. while self.current is not None:
  391. self.log.debug(
  392. "parsing decorators, current token is %r (%s)",
  393. self.current.kind,
  394. self.current.value,
  395. )
  396. if self.current.kind == tk.NAME and self.current.value in [
  397. 'async',
  398. 'def',
  399. 'class',
  400. ]:
  401. # Done with decorators - found function or class proper
  402. break
  403. elif self.current.kind == tk.OP and self.current.value == '@':
  404. # New decorator found. Store the decorator accumulated so far:
  405. self._accumulated_decorators.append(
  406. Decorator(''.join(name), ''.join(arguments))
  407. )
  408. # Now reset to begin accumulating the new decorator:
  409. name = []
  410. arguments = []
  411. at_arguments = False
  412. elif self.current.kind == tk.OP and self.current.value == '(':
  413. at_arguments = True
  414. elif self.current.kind == tk.OP and self.current.value == ')':
  415. # Ignore close parenthesis
  416. pass
  417. elif self.current.kind == tk.NEWLINE or self.current.kind == tk.NL:
  418. # Ignore newlines
  419. pass
  420. else:
  421. # Keep accumulating current decorator's name or argument.
  422. if not at_arguments:
  423. name.append(self.current.value)
  424. else:
  425. arguments.append(self.current.value)
  426. self.stream.move()
  427. # Add decorator accumulated so far
  428. self._accumulated_decorators.append(
  429. Decorator(''.join(name), ''.join(arguments))
  430. )
  431. def parse_definitions(self, class_, dunder_all=False):
  432. """Parse multiple definitions and yield them."""
  433. while self.current is not None:
  434. self.log.debug(
  435. "parsing definition list, current token is %r (%s)",
  436. self.current.kind,
  437. self.current.value,
  438. )
  439. self.log.debug('got_newline: %s', self.stream.got_logical_newline)
  440. if dunder_all and self.current.value == '__all__':
  441. self.parse_dunder_all()
  442. elif (
  443. self.current.kind == tk.OP
  444. and self.current.value == '@'
  445. and self.stream.got_logical_newline
  446. ):
  447. self.consume(tk.OP)
  448. self.parse_decorators()
  449. elif self.current.value in ['def', 'class']:
  450. yield self.parse_definition(class_._nest(self.current.value))
  451. elif self.current.kind == tk.INDENT:
  452. self.consume(tk.INDENT)
  453. yield from self.parse_definitions(class_)
  454. elif self.current.kind == tk.DEDENT:
  455. self.consume(tk.DEDENT)
  456. return
  457. elif self.current.value == 'from':
  458. self.parse_from_import_statement()
  459. else:
  460. self.stream.move()
  461. def parse_dunder_all(self):
  462. """Parse the __all__ definition in a module."""
  463. assert self.current.value == '__all__'
  464. self.consume(tk.NAME)
  465. # More than one __all__ definition means we ignore all __all__.
  466. if self.dunder_all is not None or self.dunder_all_error is not None:
  467. self.dunder_all = None
  468. self.dunder_all_error = 'Could not evaluate contents of __all__. '
  469. return
  470. if self.current.value != '=':
  471. self.dunder_all_error = 'Could not evaluate contents of __all__. '
  472. return
  473. self.consume(tk.OP)
  474. is_surrounded = False
  475. if self.current.value in '([':
  476. is_surrounded = True
  477. self.consume(tk.OP)
  478. dunder_all_content = "("
  479. while True:
  480. if is_surrounded and self.current.value in ")]":
  481. break
  482. if self.current.kind in (tk.NEWLINE, tk.ENDMARKER):
  483. break
  484. if self.current.kind in (tk.NL, tk.COMMENT):
  485. pass
  486. elif self.current.kind == tk.STRING or self.current.value == ',':
  487. dunder_all_content += self.current.value
  488. else:
  489. self.dunder_all_error = (
  490. 'Could not evaluate contents of __all__.'
  491. )
  492. return
  493. self.stream.move()
  494. if is_surrounded:
  495. self.consume(tk.OP)
  496. if not is_surrounded and ',' not in dunder_all_content:
  497. self.dunder_all_error = (
  498. 'Unexpected token kind in __all__: {!r}. '.format(
  499. self.current.kind
  500. )
  501. )
  502. return
  503. dunder_all_content += ")"
  504. try:
  505. self.dunder_all = eval(dunder_all_content, {})
  506. except BaseException as e:
  507. self.dunder_all_error = (
  508. 'Could not evaluate contents of __all__.'
  509. '\bThe value was {}. The exception was:\n{}'.format(
  510. dunder_all_content, e
  511. )
  512. )
  513. while (
  514. self.current.kind not in self.stream.LOGICAL_NEWLINES
  515. and self.current.kind != tk.ENDMARKER
  516. ):
  517. if self.current.kind != tk.COMMENT:
  518. self.dunder_all = None
  519. self.dunder_all_error = (
  520. 'Could not evaluate contents of __all__. '
  521. )
  522. return
  523. self.stream.move()
  524. def parse_module(self):
  525. """Parse a module (and its children) and return a Module object."""
  526. self.log.debug("parsing module.")
  527. start = self.line
  528. skipped_error_codes = self.parse_skip_comment()
  529. docstring = self.parse_docstring()
  530. children = list(self.parse_definitions(Module, dunder_all=True))
  531. assert self.current is None, self.current
  532. end = self.line
  533. cls = Module
  534. if self.filename.endswith('__init__.py'):
  535. cls = Package
  536. module = cls(
  537. self.filename,
  538. self.source,
  539. start,
  540. end,
  541. [],
  542. docstring,
  543. children,
  544. None,
  545. self.dunder_all,
  546. self.dunder_all_error,
  547. None,
  548. skipped_error_codes,
  549. )
  550. for child in module.children:
  551. child.parent = module
  552. module.future_imports = self.future_imports
  553. self.log.debug("finished parsing module.")
  554. return module
  555. def parse_definition(self, class_):
  556. """Parse a definition and return its value in a `class_` object."""
  557. start = self.line
  558. self.consume(tk.NAME)
  559. name = self.current.value
  560. self.log.debug("parsing %s '%s'", class_.__name__, name)
  561. self.stream.move()
  562. callable_args = []
  563. if self.current.kind == tk.OP and self.current.value == '(':
  564. parenthesis_level = 0
  565. in_default_arg = False
  566. while True:
  567. if self.current.kind == tk.OP:
  568. if self.current.value == '(':
  569. parenthesis_level += 1
  570. elif self.current.value == ')':
  571. parenthesis_level -= 1
  572. if parenthesis_level == 0:
  573. break
  574. elif self.current.value == ',':
  575. in_default_arg = False
  576. elif (
  577. parenthesis_level == 1
  578. and self.current.kind == tk.NAME
  579. and not in_default_arg
  580. ):
  581. callable_args.append(self.current.value)
  582. in_default_arg = True
  583. self.stream.move()
  584. if self.current.kind != tk.OP or self.current.value != ':':
  585. self.leapfrog(tk.OP, value=":")
  586. else:
  587. self.consume(tk.OP)
  588. if self.current.kind in (tk.NEWLINE, tk.COMMENT):
  589. skipped_error_codes = self.parse_skip_comment()
  590. self.leapfrog(tk.INDENT)
  591. assert self.current.kind != tk.INDENT
  592. docstring = self.parse_docstring()
  593. decorators = self._accumulated_decorators
  594. self.log.debug("current accumulated decorators: %s", decorators)
  595. self._accumulated_decorators = []
  596. self.log.debug("parsing nested definitions.")
  597. children = list(self.parse_definitions(class_))
  598. self.log.debug(
  599. "finished parsing nested definitions for '%s'", name
  600. )
  601. end = self.line - 1
  602. else: # one-liner definition
  603. skipped_error_codes = ''
  604. docstring = self.parse_docstring()
  605. decorators = self._accumulated_decorators
  606. self.log.debug("current accumulated decorators: %s", decorators)
  607. self._accumulated_decorators = []
  608. children = []
  609. end = self.line
  610. self.leapfrog(tk.NEWLINE)
  611. definition = class_(
  612. name,
  613. self.source,
  614. start,
  615. end,
  616. decorators,
  617. docstring,
  618. children,
  619. callable_args,
  620. None, # parent
  621. skipped_error_codes,
  622. )
  623. for child in definition.children:
  624. child.parent = definition
  625. self.log.debug(
  626. "finished parsing %s '%s'. Next token is %r",
  627. class_.__name__,
  628. name,
  629. self.current,
  630. )
  631. return definition
  632. def parse_skip_comment(self):
  633. """Parse a definition comment for noqa skips."""
  634. skipped_error_codes = ''
  635. while self.current.kind in (tk.COMMENT, tk.NEWLINE, tk.NL):
  636. if self.current.kind == tk.COMMENT:
  637. if 'noqa: ' in self.current.value:
  638. skipped_error_codes = ''.join(
  639. self.current.value.split('noqa: ')[1:]
  640. )
  641. elif self.current.value.startswith('# noqa'):
  642. skipped_error_codes = 'all'
  643. self.stream.move()
  644. self.log.debug(
  645. "parsing comments before docstring, token is %r (%s)",
  646. self.current.kind,
  647. self.current.value,
  648. )
  649. if skipped_error_codes:
  650. break
  651. return skipped_error_codes
  652. def check_current(self, kind=None, value=None):
  653. """Verify the current token is of type `kind` and equals `value`."""
  654. msg = textwrap.dedent(
  655. """
  656. Unexpected token at line {self.line}:
  657. In file: {self.filename}
  658. Got kind {self.current.kind!r}
  659. Got value {self.current.value}
  660. """.format(
  661. self=self
  662. )
  663. )
  664. kind_valid = self.current.kind == kind if kind else True
  665. value_valid = self.current.value == value if value else True
  666. assert kind_valid and value_valid, msg
  667. def parse_from_import_statement(self):
  668. """Parse a 'from x import y' statement.
  669. The purpose is to find __future__ statements.
  670. """
  671. self.log.debug('parsing from/import statement.')
  672. is_future_import = self._parse_from_import_source()
  673. self._parse_from_import_names(is_future_import)
  674. def _parse_from_import_source(self):
  675. """Parse the 'from x import' part in a 'from x import y' statement.
  676. Return true iff `x` is __future__.
  677. """
  678. assert self.current.value == 'from', self.current.value
  679. self.stream.move()
  680. is_future_import = self.current.value == '__future__'
  681. self.stream.move()
  682. while (
  683. self.current is not None
  684. and self.current.kind in (tk.DOT, tk.NAME, tk.OP)
  685. and self.current.value != 'import'
  686. ):
  687. self.stream.move()
  688. if self.current is None or self.current.value != 'import':
  689. return False
  690. self.check_current(value='import')
  691. assert self.current.value == 'import', self.current.value
  692. self.stream.move()
  693. return is_future_import
  694. def _parse_from_import_names(self, is_future_import):
  695. """Parse the 'y' part in a 'from x import y' statement."""
  696. if self.current.value == '(':
  697. self.consume(tk.OP)
  698. expected_end_kinds = (tk.OP,)
  699. else:
  700. expected_end_kinds = (tk.NEWLINE, tk.ENDMARKER)
  701. while self.current.kind not in expected_end_kinds and not (
  702. self.current.kind == tk.OP and self.current.value == ';'
  703. ):
  704. if self.current.kind != tk.NAME:
  705. self.stream.move()
  706. continue
  707. self.log.debug(
  708. "parsing import, token is %r (%s)",
  709. self.current.kind,
  710. self.current.value,
  711. )
  712. if is_future_import:
  713. self.log.debug('found future import: %s', self.current.value)
  714. self.future_imports.add(self.current.value)
  715. self.consume(tk.NAME)
  716. self.log.debug(
  717. "parsing import, token is %r (%s)",
  718. self.current.kind,
  719. self.current.value,
  720. )
  721. if self.current.kind == tk.NAME and self.current.value == 'as':
  722. self.consume(tk.NAME) # as
  723. if self.current.kind == tk.NAME:
  724. self.consume(tk.NAME) # new name, irrelevant
  725. if self.current.value == ',':
  726. self.consume(tk.OP)
  727. self.log.debug(
  728. "parsing import, token is %r (%s)",
  729. self.current.kind,
  730. self.current.value,
  731. )