extract.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789
  1. import re
  2. from rope.base import ast, codeanalyze
  3. from rope.base.change import ChangeSet, ChangeContents
  4. from rope.base.exceptions import RefactoringError
  5. from rope.refactor import (sourceutils, similarfinder,
  6. patchedast, suites, usefunction)
  7. # Extract refactoring has lots of special cases. I tried to split it
  8. # to smaller parts to make it more manageable:
  9. #
  10. # _ExtractInfo: holds information about the refactoring; it is passed
  11. # to the parts that need to have information about the refactoring
  12. #
  13. # _ExtractCollector: merely saves all of the information necessary for
  14. # performing the refactoring.
  15. #
  16. # _DefinitionLocationFinder: finds where to insert the definition.
  17. #
  18. # _ExceptionalConditionChecker: checks for exceptional conditions in
  19. # which the refactoring cannot be applied.
  20. #
  21. # _ExtractMethodParts: generates the pieces of code (like definition)
  22. # needed for performing extract method.
  23. #
  24. # _ExtractVariableParts: like _ExtractMethodParts for variables.
  25. #
  26. # _ExtractPerformer: Uses above classes to collect refactoring
  27. # changes.
  28. #
  29. # There are a few more helper functions and classes used by above
  30. # classes.
  31. class _ExtractRefactoring(object):
  32. def __init__(self, project, resource, start_offset, end_offset,
  33. variable=False):
  34. self.project = project
  35. self.pycore = project.pycore
  36. self.resource = resource
  37. self.start_offset = self._fix_start(resource.read(), start_offset)
  38. self.end_offset = self._fix_end(resource.read(), end_offset)
  39. def _fix_start(self, source, offset):
  40. while offset < len(source) and source[offset].isspace():
  41. offset += 1
  42. return offset
  43. def _fix_end(self, source, offset):
  44. while offset > 0 and source[offset - 1].isspace():
  45. offset -= 1
  46. return offset
  47. def get_changes(self, extracted_name, similar=False, global_=False):
  48. """Get the changes this refactoring makes
  49. :parameters:
  50. - `similar`: if `True`, similar expressions/statements are also
  51. replaced.
  52. - `global_`: if `True`, the extracted method/variable will
  53. be global.
  54. """
  55. info = _ExtractInfo(
  56. self.project, self.resource, self.start_offset, self.end_offset,
  57. extracted_name, variable=self.kind == 'variable',
  58. similar=similar, make_global=global_)
  59. new_contents = _ExtractPerformer(info).extract()
  60. changes = ChangeSet('Extract %s <%s>' % (self.kind,
  61. extracted_name))
  62. changes.add_change(ChangeContents(self.resource, new_contents))
  63. return changes
  64. class ExtractMethod(_ExtractRefactoring):
  65. def __init__(self, *args, **kwds):
  66. super(ExtractMethod, self).__init__(*args, **kwds)
  67. kind = 'method'
  68. class ExtractVariable(_ExtractRefactoring):
  69. def __init__(self, *args, **kwds):
  70. kwds = dict(kwds)
  71. kwds['variable'] = True
  72. super(ExtractVariable, self).__init__(*args, **kwds)
  73. kind = 'variable'
  74. class _ExtractInfo(object):
  75. """Holds information about the extract to be performed"""
  76. def __init__(self, project, resource, start, end, new_name,
  77. variable, similar, make_global):
  78. self.pycore = project.pycore
  79. self.resource = resource
  80. self.pymodule = self.pycore.resource_to_pyobject(resource)
  81. self.global_scope = self.pymodule.get_scope()
  82. self.source = self.pymodule.source_code
  83. self.lines = self.pymodule.lines
  84. self.new_name = new_name
  85. self.variable = variable
  86. self.similar = similar
  87. self._init_parts(start, end)
  88. self._init_scope()
  89. self.make_global = make_global
  90. def _init_parts(self, start, end):
  91. self.region = (self._choose_closest_line_end(start),
  92. self._choose_closest_line_end(end, end=True))
  93. start = self.logical_lines.logical_line_in(
  94. self.lines.get_line_number(self.region[0]))[0]
  95. end = self.logical_lines.logical_line_in(
  96. self.lines.get_line_number(self.region[1]))[1]
  97. self.region_lines = (start, end)
  98. self.lines_region = (self.lines.get_line_start(self.region_lines[0]),
  99. self.lines.get_line_end(self.region_lines[1]))
  100. @property
  101. def logical_lines(self):
  102. return self.pymodule.logical_lines
  103. def _init_scope(self):
  104. start_line = self.region_lines[0]
  105. scope = self.global_scope.get_inner_scope_for_line(start_line)
  106. if scope.get_kind() != 'Module' and scope.get_start() == start_line:
  107. scope = scope.parent
  108. self.scope = scope
  109. self.scope_region = self._get_scope_region(self.scope)
  110. def _get_scope_region(self, scope):
  111. return (self.lines.get_line_start(scope.get_start()),
  112. self.lines.get_line_end(scope.get_end()) + 1)
  113. def _choose_closest_line_end(self, offset, end=False):
  114. lineno = self.lines.get_line_number(offset)
  115. line_start = self.lines.get_line_start(lineno)
  116. line_end = self.lines.get_line_end(lineno)
  117. if self.source[line_start:offset].strip() == '':
  118. if end:
  119. return line_start - 1
  120. else:
  121. return line_start
  122. elif self.source[offset:line_end].strip() == '':
  123. return min(line_end, len(self.source))
  124. return offset
  125. @property
  126. def one_line(self):
  127. return self.region != self.lines_region and \
  128. (self.logical_lines.logical_line_in(self.region_lines[0]) ==
  129. self.logical_lines.logical_line_in(self.region_lines[1]))
  130. @property
  131. def global_(self):
  132. return self.scope.parent is None
  133. @property
  134. def method(self):
  135. return self.scope.parent is not None and \
  136. self.scope.parent.get_kind() == 'Class'
  137. @property
  138. def indents(self):
  139. return sourceutils.get_indents(self.pymodule.lines,
  140. self.region_lines[0])
  141. @property
  142. def scope_indents(self):
  143. if self.global_:
  144. return 0
  145. return sourceutils.get_indents(self.pymodule.lines,
  146. self.scope.get_start())
  147. @property
  148. def extracted(self):
  149. return self.source[self.region[0]:self.region[1]]
  150. _returned = None
  151. @property
  152. def returned(self):
  153. """Does the extracted piece contain return statement"""
  154. if self._returned is None:
  155. node = _parse_text(self.extracted)
  156. self._returned = usefunction._returns_last(node)
  157. return self._returned
  158. class _ExtractCollector(object):
  159. """Collects information needed for performing the extract"""
  160. def __init__(self, info):
  161. self.definition = None
  162. self.body_pattern = None
  163. self.checks = {}
  164. self.replacement_pattern = None
  165. self.matches = None
  166. self.replacements = None
  167. self.definition_location = None
  168. class _ExtractPerformer(object):
  169. def __init__(self, info):
  170. self.info = info
  171. _ExceptionalConditionChecker()(self.info)
  172. def extract(self):
  173. extract_info = self._collect_info()
  174. content = codeanalyze.ChangeCollector(self.info.source)
  175. definition = extract_info.definition
  176. lineno, indents = extract_info.definition_location
  177. offset = self.info.lines.get_line_start(lineno)
  178. indented = sourceutils.fix_indentation(definition, indents)
  179. content.add_change(offset, offset, indented)
  180. self._replace_occurrences(content, extract_info)
  181. return content.get_changed()
  182. def _replace_occurrences(self, content, extract_info):
  183. for match in extract_info.matches:
  184. replacement = similarfinder.CodeTemplate(
  185. extract_info.replacement_pattern)
  186. mapping = {}
  187. for name in replacement.get_names():
  188. node = match.get_ast(name)
  189. if node:
  190. start, end = patchedast.node_region(match.get_ast(name))
  191. mapping[name] = self.info.source[start:end]
  192. else:
  193. mapping[name] = name
  194. region = match.get_region()
  195. content.add_change(region[0], region[1],
  196. replacement.substitute(mapping))
  197. def _collect_info(self):
  198. extract_collector = _ExtractCollector(self.info)
  199. self._find_definition(extract_collector)
  200. self._find_matches(extract_collector)
  201. self._find_definition_location(extract_collector)
  202. return extract_collector
  203. def _find_matches(self, collector):
  204. regions = self._where_to_search()
  205. finder = similarfinder.SimilarFinder(self.info.pymodule)
  206. matches = []
  207. for start, end in regions:
  208. matches.extend((finder.get_matches(collector.body_pattern,
  209. collector.checks, start, end)))
  210. collector.matches = matches
  211. def _where_to_search(self):
  212. if self.info.similar:
  213. if self.info.make_global or self.info.global_:
  214. return [(0, len(self.info.pymodule.source_code))]
  215. if self.info.method and not self.info.variable:
  216. class_scope = self.info.scope.parent
  217. regions = []
  218. method_kind = _get_function_kind(self.info.scope)
  219. for scope in class_scope.get_scopes():
  220. if method_kind == 'method' and \
  221. _get_function_kind(scope) != 'method':
  222. continue
  223. start = self.info.lines.get_line_start(scope.get_start())
  224. end = self.info.lines.get_line_end(scope.get_end())
  225. regions.append((start, end))
  226. return regions
  227. else:
  228. if self.info.variable:
  229. return [self.info.scope_region]
  230. else:
  231. return [self.info._get_scope_region(self.info.scope.parent)]
  232. else:
  233. return [self.info.region]
  234. def _find_definition_location(self, collector):
  235. matched_lines = []
  236. for match in collector.matches:
  237. start = self.info.lines.get_line_number(match.get_region()[0])
  238. start_line = self.info.logical_lines.logical_line_in(start)[0]
  239. matched_lines.append(start_line)
  240. location_finder = _DefinitionLocationFinder(self.info, matched_lines)
  241. collector.definition_location = (location_finder.find_lineno(),
  242. location_finder.find_indents())
  243. def _find_definition(self, collector):
  244. if self.info.variable:
  245. parts = _ExtractVariableParts(self.info)
  246. else:
  247. parts = _ExtractMethodParts(self.info)
  248. collector.definition = parts.get_definition()
  249. collector.body_pattern = parts.get_body_pattern()
  250. collector.replacement_pattern = parts.get_replacement_pattern()
  251. collector.checks = parts.get_checks()
  252. class _DefinitionLocationFinder(object):
  253. def __init__(self, info, matched_lines):
  254. self.info = info
  255. self.matched_lines = matched_lines
  256. # This only happens when subexpressions cannot be matched
  257. if not matched_lines:
  258. self.matched_lines.append(self.info.region_lines[0])
  259. def find_lineno(self):
  260. if self.info.variable and not self.info.make_global:
  261. return self._get_before_line()
  262. if self.info.make_global or self.info.global_:
  263. toplevel = self._find_toplevel(self.info.scope)
  264. ast = self.info.pymodule.get_ast()
  265. newlines = sorted(self.matched_lines + [toplevel.get_end() + 1])
  266. return suites.find_visible(ast, newlines)
  267. return self._get_after_scope()
  268. def _find_toplevel(self, scope):
  269. toplevel = scope
  270. if toplevel.parent is not None:
  271. while toplevel.parent.parent is not None:
  272. toplevel = toplevel.parent
  273. return toplevel
  274. def find_indents(self):
  275. if self.info.variable and not self.info.make_global:
  276. return sourceutils.get_indents(self.info.lines,
  277. self._get_before_line())
  278. else:
  279. if self.info.global_ or self.info.make_global:
  280. return 0
  281. return self.info.scope_indents
  282. def _get_before_line(self):
  283. ast = self.info.scope.pyobject.get_ast()
  284. return suites.find_visible(ast, self.matched_lines)
  285. def _get_after_scope(self):
  286. return self.info.scope.get_end() + 1
  287. class _ExceptionalConditionChecker(object):
  288. def __call__(self, info):
  289. self.base_conditions(info)
  290. if info.one_line:
  291. self.one_line_conditions(info)
  292. else:
  293. self.multi_line_conditions(info)
  294. def base_conditions(self, info):
  295. if info.region[1] > info.scope_region[1]:
  296. raise RefactoringError('Bad region selected for extract method')
  297. end_line = info.region_lines[1]
  298. end_scope = info.global_scope.get_inner_scope_for_line(end_line)
  299. if end_scope != info.scope and end_scope.get_end() != end_line:
  300. raise RefactoringError('Bad region selected for extract method')
  301. try:
  302. extracted = info.source[info.region[0]:info.region[1]]
  303. if info.one_line:
  304. extracted = '(%s)' % extracted
  305. if _UnmatchedBreakOrContinueFinder.has_errors(extracted):
  306. raise RefactoringError('A break/continue without having a '
  307. 'matching for/while loop.')
  308. except SyntaxError:
  309. raise RefactoringError('Extracted piece should '
  310. 'contain complete statements.')
  311. def one_line_conditions(self, info):
  312. if self._is_region_on_a_word(info):
  313. raise RefactoringError('Should extract complete statements.')
  314. if info.variable and not info.one_line:
  315. raise RefactoringError('Extract variable should not '
  316. 'span multiple lines.')
  317. def multi_line_conditions(self, info):
  318. node = _parse_text(info.source[info.region[0]:info.region[1]])
  319. count = usefunction._return_count(node)
  320. if count > 1:
  321. raise RefactoringError('Extracted piece can have only one '
  322. 'return statement.')
  323. if usefunction._yield_count(node):
  324. raise RefactoringError('Extracted piece cannot '
  325. 'have yield statements.')
  326. if count == 1 and not usefunction._returns_last(node):
  327. raise RefactoringError('Return should be the last statement.')
  328. if info.region != info.lines_region:
  329. raise RefactoringError('Extracted piece should '
  330. 'contain complete statements.')
  331. def _is_region_on_a_word(self, info):
  332. if info.region[0] > 0 and self._is_on_a_word(info, info.region[0] - 1) or \
  333. self._is_on_a_word(info, info.region[1] - 1):
  334. return True
  335. def _is_on_a_word(self, info, offset):
  336. prev = info.source[offset]
  337. if not (prev.isalnum() or prev == '_') or \
  338. offset + 1 == len(info.source):
  339. return False
  340. next = info.source[offset + 1]
  341. return next.isalnum() or next == '_'
  342. class _ExtractMethodParts(object):
  343. def __init__(self, info):
  344. self.info = info
  345. self.info_collector = self._create_info_collector()
  346. def get_definition(self):
  347. if self.info.global_:
  348. return '\n%s\n' % self._get_function_definition()
  349. else:
  350. return '\n%s' % self._get_function_definition()
  351. def get_replacement_pattern(self):
  352. variables = []
  353. variables.extend(self._find_function_arguments())
  354. variables.extend(self._find_function_returns())
  355. return similarfinder.make_pattern(self._get_call(), variables)
  356. def get_body_pattern(self):
  357. variables = []
  358. variables.extend(self._find_function_arguments())
  359. variables.extend(self._find_function_returns())
  360. variables.extend(self._find_temps())
  361. return similarfinder.make_pattern(self._get_body(), variables)
  362. def _get_body(self):
  363. result = sourceutils.fix_indentation(self.info.extracted, 0)
  364. if self.info.one_line:
  365. result = '(%s)' % result
  366. return result
  367. def _find_temps(self):
  368. return usefunction.find_temps(self.info.pycore.project,
  369. self._get_body())
  370. def get_checks(self):
  371. if self.info.method and not self.info.make_global:
  372. if _get_function_kind(self.info.scope) == 'method':
  373. class_name = similarfinder._pydefined_to_str(
  374. self.info.scope.parent.pyobject)
  375. return {self._get_self_name(): 'type=' + class_name}
  376. return {}
  377. def _create_info_collector(self):
  378. zero = self.info.scope.get_start() - 1
  379. start_line = self.info.region_lines[0] - zero
  380. end_line = self.info.region_lines[1] - zero
  381. info_collector = _FunctionInformationCollector(start_line, end_line,
  382. self.info.global_)
  383. body = self.info.source[self.info.scope_region[0]:
  384. self.info.scope_region[1]]
  385. node = _parse_text(body)
  386. ast.walk(node, info_collector)
  387. return info_collector
  388. def _get_function_definition(self):
  389. args = self._find_function_arguments()
  390. returns = self._find_function_returns()
  391. result = []
  392. if self.info.method and not self.info.make_global and \
  393. _get_function_kind(self.info.scope) != 'method':
  394. result.append('@staticmethod\n')
  395. result.append('def %s:\n' % self._get_function_signature(args))
  396. unindented_body = self._get_unindented_function_body(returns)
  397. indents = sourceutils.get_indent(self.info.pycore)
  398. function_body = sourceutils.indent_lines(unindented_body, indents)
  399. result.append(function_body)
  400. definition = ''.join(result)
  401. return definition + '\n'
  402. def _get_function_signature(self, args):
  403. args = list(args)
  404. prefix = ''
  405. if self._extracting_method():
  406. self_name = self._get_self_name()
  407. if self_name is None:
  408. raise RefactoringError('Extracting a method from a function '
  409. 'with no self argument.')
  410. if self_name in args:
  411. args.remove(self_name)
  412. args.insert(0, self_name)
  413. return prefix + self.info.new_name + \
  414. '(%s)' % self._get_comma_form(args)
  415. def _extracting_method(self):
  416. return self.info.method and not self.info.make_global and \
  417. _get_function_kind(self.info.scope) == 'method'
  418. def _get_self_name(self):
  419. param_names = self.info.scope.pyobject.get_param_names()
  420. if param_names:
  421. return param_names[0]
  422. def _get_function_call(self, args):
  423. prefix = ''
  424. if self.info.method and not self.info.make_global:
  425. if _get_function_kind(self.info.scope) == 'method':
  426. self_name = self._get_self_name()
  427. if self_name in args:
  428. args.remove(self_name)
  429. prefix = self_name + '.'
  430. else:
  431. prefix = self.info.scope.parent.pyobject.get_name() + '.'
  432. return prefix + '%s(%s)' % (self.info.new_name,
  433. self._get_comma_form(args))
  434. def _get_comma_form(self, names):
  435. result = ''
  436. if names:
  437. result += names[0]
  438. for name in names[1:]:
  439. result += ', ' + name
  440. return result
  441. def _get_call(self):
  442. if self.info.one_line:
  443. args = self._find_function_arguments()
  444. return self._get_function_call(args)
  445. args = self._find_function_arguments()
  446. returns = self._find_function_returns()
  447. call_prefix = ''
  448. if returns:
  449. call_prefix = self._get_comma_form(returns) + ' = '
  450. if self.info.returned:
  451. call_prefix = 'return '
  452. return call_prefix + self._get_function_call(args)
  453. def _find_function_arguments(self):
  454. # if not make_global, do not pass any global names; they are
  455. # all visible.
  456. if self.info.global_ and not self.info.make_global:
  457. return ()
  458. if not self.info.one_line:
  459. result = (self.info_collector.prewritten &
  460. self.info_collector.read)
  461. result |= (self.info_collector.prewritten &
  462. self.info_collector.postread &
  463. (self.info_collector.maybe_written -
  464. self.info_collector.written))
  465. return list(result)
  466. start = self.info.region[0]
  467. if start == self.info.lines_region[0]:
  468. start = start + re.search('\S', self.info.extracted).start()
  469. function_definition = self.info.source[start:self.info.region[1]]
  470. read = _VariableReadsAndWritesFinder.find_reads_for_one_liners(
  471. function_definition)
  472. return list(self.info_collector.prewritten.intersection(read))
  473. def _find_function_returns(self):
  474. if self.info.one_line or self.info.returned:
  475. return []
  476. written = self.info_collector.written | \
  477. self.info_collector.maybe_written
  478. return list(written & self.info_collector.postread)
  479. def _get_unindented_function_body(self, returns):
  480. if self.info.one_line:
  481. return 'return ' + _join_lines(self.info.extracted)
  482. extracted_body = self.info.extracted
  483. unindented_body = sourceutils.fix_indentation(extracted_body, 0)
  484. if returns:
  485. unindented_body += '\nreturn %s' % self._get_comma_form(returns)
  486. return unindented_body
  487. class _ExtractVariableParts(object):
  488. def __init__(self, info):
  489. self.info = info
  490. def get_definition(self):
  491. result = self.info.new_name + ' = ' + \
  492. _join_lines(self.info.extracted) + '\n'
  493. return result
  494. def get_body_pattern(self):
  495. return '(%s)' % self.info.extracted.strip()
  496. def get_replacement_pattern(self):
  497. return self.info.new_name
  498. def get_checks(self):
  499. return {}
  500. class _FunctionInformationCollector(object):
  501. def __init__(self, start, end, is_global):
  502. self.start = start
  503. self.end = end
  504. self.is_global = is_global
  505. self.prewritten = set()
  506. self.maybe_written = set()
  507. self.written = set()
  508. self.read = set()
  509. self.postread = set()
  510. self.postwritten = set()
  511. self.host_function = True
  512. self.conditional = False
  513. def _read_variable(self, name, lineno):
  514. if self.start <= lineno <= self.end:
  515. if name not in self.written:
  516. self.read.add(name)
  517. if self.end < lineno:
  518. if name not in self.postwritten:
  519. self.postread.add(name)
  520. def _written_variable(self, name, lineno):
  521. if self.start <= lineno <= self.end:
  522. if self.conditional:
  523. self.maybe_written.add(name)
  524. else:
  525. self.written.add(name)
  526. if self.start > lineno:
  527. self.prewritten.add(name)
  528. if self.end < lineno:
  529. self.postwritten.add(name)
  530. def _FunctionDef(self, node):
  531. if not self.is_global and self.host_function:
  532. self.host_function = False
  533. for name in _get_argnames(node.args):
  534. self._written_variable(name, node.lineno)
  535. for child in node.body:
  536. ast.walk(child, self)
  537. else:
  538. self._written_variable(node.name, node.lineno)
  539. visitor = _VariableReadsAndWritesFinder()
  540. for child in node.body:
  541. ast.walk(child, visitor)
  542. for name in visitor.read - visitor.written:
  543. self._read_variable(name, node.lineno)
  544. def _Name(self, node):
  545. if isinstance(node.ctx, (ast.Store, ast.AugStore)):
  546. self._written_variable(node.id, node.lineno)
  547. if not isinstance(node.ctx, ast.Store):
  548. self._read_variable(node.id, node.lineno)
  549. def _Assign(self, node):
  550. ast.walk(node.value, self)
  551. for child in node.targets:
  552. ast.walk(child, self)
  553. def _ClassDef(self, node):
  554. self._written_variable(node.name, node.lineno)
  555. def _handle_conditional_node(self, node):
  556. self.conditional = True
  557. try:
  558. for child in ast.get_child_nodes(node):
  559. ast.walk(child, self)
  560. finally:
  561. self.conditional = False
  562. def _If(self, node):
  563. self._handle_conditional_node(node)
  564. def _While(self, node):
  565. self._handle_conditional_node(node)
  566. def _For(self, node):
  567. self._handle_conditional_node(node)
  568. def _get_argnames(arguments):
  569. result = [node.id for node in arguments.args
  570. if isinstance(node, ast.Name)]
  571. if arguments.vararg:
  572. result.append(arguments.vararg)
  573. if arguments.kwarg:
  574. result.append(arguments.kwarg)
  575. return result
  576. class _VariableReadsAndWritesFinder(object):
  577. def __init__(self):
  578. self.written = set()
  579. self.read = set()
  580. def _Name(self, node):
  581. if isinstance(node.ctx, (ast.Store, ast.AugStore)):
  582. self.written.add(node.id)
  583. if not isinstance(node, ast.Store):
  584. self.read.add(node.id)
  585. def _FunctionDef(self, node):
  586. self.written.add(node.name)
  587. visitor = _VariableReadsAndWritesFinder()
  588. for child in ast.get_child_nodes(node):
  589. ast.walk(child, visitor)
  590. self.read.update(visitor.read - visitor.written)
  591. def _Class(self, node):
  592. self.written.add(node.name)
  593. @staticmethod
  594. def find_reads_and_writes(code):
  595. if code.strip() == '':
  596. return set(), set()
  597. if isinstance(code, unicode):
  598. code = code.encode('utf-8')
  599. node = _parse_text(code)
  600. visitor = _VariableReadsAndWritesFinder()
  601. ast.walk(node, visitor)
  602. return visitor.read, visitor.written
  603. @staticmethod
  604. def find_reads_for_one_liners(code):
  605. if code.strip() == '':
  606. return set(), set()
  607. node = _parse_text(code)
  608. visitor = _VariableReadsAndWritesFinder()
  609. ast.walk(node, visitor)
  610. return visitor.read
  611. class _UnmatchedBreakOrContinueFinder(object):
  612. def __init__(self):
  613. self.error = False
  614. self.loop_count = 0
  615. def _For(self, node):
  616. self.loop_encountered(node)
  617. def _While(self, node):
  618. self.loop_encountered(node)
  619. def loop_encountered(self, node):
  620. self.loop_count += 1
  621. for child in node.body:
  622. ast.walk(child, self)
  623. self.loop_count -= 1
  624. if node.orelse:
  625. ast.walk(node.orelse, self)
  626. def _Break(self, node):
  627. self.check_loop()
  628. def _Continue(self, node):
  629. self.check_loop()
  630. def check_loop(self):
  631. if self.loop_count < 1:
  632. self.error = True
  633. def _FunctionDef(self, node):
  634. pass
  635. def _ClassDef(self, node):
  636. pass
  637. @staticmethod
  638. def has_errors(code):
  639. if code.strip() == '':
  640. return False
  641. node = _parse_text(code)
  642. visitor = _UnmatchedBreakOrContinueFinder()
  643. ast.walk(node, visitor)
  644. return visitor.error
  645. def _get_function_kind(scope):
  646. return scope.pyobject.get_kind()
  647. def _parse_text(body):
  648. body = sourceutils.fix_indentation(body, 0)
  649. node = ast.parse(body)
  650. return node
  651. def _join_lines(code):
  652. lines = []
  653. for line in code.splitlines():
  654. if line.endswith('\\'):
  655. lines.append(line[:-1].strip())
  656. else:
  657. lines.append(line.strip())
  658. return ' '.join(lines)