rope / rope / refactor / patchedast.py

The trunk branch has multiple heads

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
import re

from rope.base import ast, codeanalyze, exceptions


def get_patched_ast(source, sorted_children=False):
    """Adds `region` and `sorted_children` fields to nodes"""
    return patch_ast(ast.parse(source), source, sorted_children)


def patch_ast(node, source, sorted_children=False):
    """Patches the given node
    
    After calling, each node in `node` will have a new field named
    `region` that is a tuple containing the start and end offsets
    of the code that generated it.
    
    If `sorted_children` is true, a `sorted_children` field will
    be created for each node, too.  It is a list containing child
    nodes as well as whitespaces and comments that occur between
    them.

    """
    if hasattr(node, 'region'):
        return node
    walker = _PatchingASTWalker(source, children=sorted_children)
    ast.call_for_nodes(node, walker)
    return node


def node_region(patched_ast_node):
    """Get the region of a patched ast node"""
    return patched_ast_node.region


def write_ast(patched_ast_node):
    """Extract source form a patched AST node with `sorted_children` field
    
    If the node is patched with sorted_children turned off you can use
    `node_region` function for obtaining code using module source code.
    """
    result = []
    for child in patched_ast_node.sorted_children:
        if isinstance(child, ast.AST):
            result.append(write_ast(child))
        else:
            result.append(child)
    return ''.join(result)


class MismatchedTokenError(exceptions.RopeError):
    pass


class _PatchingASTWalker(object):

    def __init__(self, source, children=False):
        self.source = _Source(source)
        self.children = children
        self.lines = codeanalyze.SourceLinesAdapter(source)

    Number = object()
    String = object()

    def __call__(self, node):
        method = getattr(self, '_' + node.__class__.__name__, None)
        if method is not None:
            return method(node)
        # ???: Unknown node; What should we do here?
        raise RuntimeError('Unknown node type <%s>' %
                           node.__class__.__name__)

    def _handle(self, node, base_children, eat_parens=False, eat_spaces=False):
        if hasattr(node, 'region'):
            raise RuntimeError('Node <%s> has been already patched!' %
                               node.__class__.__name__)
        children = []
        formats = []
        suspected_start = self.source.offset
        start = suspected_start
        first_token = True
        for child in base_children:
            if child is None:
                continue
            offset = self.source.offset
            if isinstance(child, ast.AST):
                ast.call_for_nodes(child, self)
                token_start = child.region[0]
            else:
                if child is self.String:
                    region = self.source.consume_string()
                elif child is self.Number:
                    region = self.source.consume_number()
                elif child == '!=':
                    # INFO: This has been added to handle deprecated ``<>``
                    region = self.source.consume_not_equal()
                else:
                    region = self.source.consume(child)
                child = self.source.get(region[0], region[1])
                token_start = region[0]
            if not first_token:
                formats.append(self.source.get(offset, token_start))
                children.append(self.source.get(offset, token_start))
            else:
                first_token = False
                start = token_start
            children.append(child)
        start = self._handle_parens(children, start, formats)
        if eat_parens:
            start = self._eat_surrounding_parens(
                children, suspected_start, start)
        if eat_spaces:
            children.insert(0, self.source[0:start])
            end_spaces = self.source[self.source.offset:]
            self.source.consume(end_spaces)
            children.append(end_spaces)
            start = 0
        if self.children:
            node.sorted_children = children
        node.region = (start, self.source.offset)

    def _handle_parens(self, children, start, formats):
        """Changes `children` and returns new start"""
        opens, closes = self._count_needed_parens(formats)
        old_end = self.source.offset
        new_end = None
        for i in range(closes):
            new_end = self.source.consume(')')[1]
        if new_end is not None:
            children.append(self.source.get(old_end, new_end))
        new_start = start
        for i in range(opens):
            new_start = self.source.rfind_token('(', 0, new_start)
        if new_start != start:
            children.insert(0, self.source.get(new_start, start))
            start = new_start
        return start

    def _eat_surrounding_parens(self, children, suspected_start, start):
        index = self.source.rfind_token('(', suspected_start, start)
        if index is not None:
            old_start = start
            old_offset = self.source.offset
            start = index
            children.insert(0, '(')
            children.insert(1, self.source[start + 1:old_start])
            token_start, token_end = self.source.consume(')')
            children.append(self.source[old_offset:token_start])
            children.append(')')
        return start

    def _count_needed_parens(self, children):
        start = 0
        opens = 0
        for child in children:
            if not isinstance(child, basestring):
                continue
            if child == '' or child[0] in '\'"':
                continue
            index = 0
            while index < len(child):
                if child[index] == ')':
                    if opens > 0:
                        opens -= 1
                    else:
                        start += 1
                if child[index] == '(':
                    opens += 1
                if child[index] == '#':
                    try:
                        index = child.index('\n', index)
                    except ValueError:
                        break
                index += 1
        return start, opens

    _operators = {'And': 'and', 'Or': 'or', 'Add': '+', 'Sub': '-', 'Mult': '*',
                  'Div': '/', 'Mod': '%', 'Pow': '**', 'LShift': '<<',
                  'RShift': '>>', 'BitOr': '|', 'BitAnd': '&', 'BitXor': '^',
                  'FloorDiv': '//', 'Invert': '~', 'Not': 'not', 'UAdd': '+',
                  'USub': '-', 'Eq': '==', 'NotEq': '!=', 'Lt': '<',
                  'LtE': '<=', 'Gt': '>', 'GtE': '>=', 'Is': 'is',
                  'IsNot': 'is not', 'In': 'in', 'NotIn': 'not in'}

    def _get_op(self, node):
        return self._operators[node.__class__.__name__].split(' ')

    def _Attribute(self, node):
        self._handle(node, [node.value, '.', node.attr])

    def _Assert(self, node):
        children = ['assert', node.test]
        if node.msg:
            children.append(',')
            children.append(node.msg)
        self._handle(node, children)

    def _Assign(self, node):
        children = self._child_nodes(node.targets, '=')
        children.append('=')
        children.append(node.value)
        self._handle(node, children)

    def _AugAssign(self, node):
        children = [node.target]
        children.extend(self._get_op(node.op))
        children.extend(['=', node.value])
        self._handle(node, children)

    def _Repr(self, node):
        self._handle(node, ['`', node.value, '`'])

    def _BinOp(self, node):
        children = [node.left] + self._get_op(node.op) + [node.right]
        self._handle(node, children)

    def _BoolOp(self, node):
        self._handle(node, self._child_nodes(node.values,
                                             self._get_op(node.op)[0]))

    def _Break(self, node):
        self._handle(node, ['break'])

    def _Call(self, node):
        children = [node.func, '(']
        args = list(node.args) + node.keywords
        children.extend(self._child_nodes(args, ','))
        if node.starargs is not None:
            if args:
                children.append(',')
            children.extend(['*', node.starargs])
        if node.kwargs is not None:
            if args:
                children.append(',')
            children.extend(['**', node.kwargs])
        children.append(')')
        self._handle(node, children)

    def _ClassDef(self, node):
        children = []
        children.extend(['class', node.name])
        if node.bases:
            children.append('(')
            children.extend(self._child_nodes(node.bases, ','))
            children.append(')')
        children.append(':')
        children.extend(node.body)
        self._handle(node, children)

    def _Compare(self, node):
        children = []
        children.append(node.left)
        for op, expr in zip(node.ops, node.comparators):
            children.extend(self._get_op(op))
            children.append(expr)
        self._handle(node, children)

    def _Delete(self, node):
        self._handle(node, ['del'] + self._child_nodes(node.targets, ','))

    def _Num(self, node):
        self._handle(node, [self.Number])

    def _Str(self, node):
        self._handle(node, [self.String])

    def _Continue(self, node):
        self._handle(node, ['continue'])

    def _Dict(self, node):
        children = []
        children.append('{')
        if node.keys:
            for index, (key, value) in enumerate(zip(node.keys, node.values)):
                children.extend([key, ':', value])
                if index < len(node.keys) - 1:
                    children.append(',')
        children.append('}')
        self._handle(node, children)

    def _Ellipsis(self, node):
        self._handle(node, ['...'])

    def _Expr(self, node):
        self._handle(node, [node.value])

    def _Exec(self, node):
        children = []
        children.extend(['exec', node.body])
        if node.globals:
            children.extend(['in', node.globals])
        if node.locals:
            children.extend([',', node.locals])
        self._handle(node, children)

    def _For(self, node):
        children = ['for', node.target, 'in', node.iter, ':']
        children.extend(node.body)
        if node.orelse:
            children.extend(['else', ':'])
            children.extend(node.orelse)
        self._handle(node, children)

    def _ImportFrom(self, node):
        children = ['from']
        if node.level:
            children.append('.' * node.level)
        children.extend([node.module, 'import'])
        children.extend(self._child_nodes(node.names, ','))
        self._handle(node, children)

    def _alias(self, node):
        children = [node.name]
        if node.asname:
            children.extend(['as', node.asname])
        self._handle(node, children)

    def _FunctionDef(self, node):
        children = []
        if node.decorators:
            for decorator in node.decorators:
                children.append('@')
                children.append(decorator)
        children.extend(['def', node.name, '(', node.args])
        children.extend([')', ':'])
        children.extend(node.body)
        self._handle(node, children)

    def _arguments(self, node):
        children = []
        args = list(node.args)
        star_args = node.vararg
        dstar_args = node.kwarg
        defaults = [None] * (len(args) - len(node.defaults)) + list(node.defaults)
        for index, (arg, default) in enumerate(zip(args, defaults)):
            if index > 0:
                children.append(',')
            self._add_args_to_children(children, arg, default)
        if star_args is not None:
            if args:
                children.append(',')
            children.extend(['*', star_args])
        if dstar_args is not None:
            if args:
                children.append(',')
            children.extend(['**', dstar_args])
        self._handle(node, children)

    def _add_args_to_children(self, children, arg, default):
        if isinstance(arg, (list, tuple)):
            self._add_tuple_parameter(children, arg)
        else:
            children.append(arg)
        if default is not None:
            children.append('=')
            children.append(default)

    def _add_tuple_parameter(self, children, arg):
        children.append('(')
        for index, token in enumerate(arg):
            if index > 0:
                children.append(',')
            if isinstance(token, (list, tuple)):
                self._add_tuple_parameter(children, token)
            else:
                children.append(token)
        children.append(')')

    def _GeneratorExp(self, node):
        children = [node.elt]
        children.extend(node.generators)
        self._handle(node, children, eat_parens=True)

    def _comprehension(self, node):
        children = ['for', node.target, 'in', node.iter]
        if node.ifs:
            for if_ in node.ifs:
                children.append('if')
                children.append(if_)
        self._handle(node, children)

    def _Global(self, node):
        children = self._child_nodes(node.names, ',')
        children.insert(0, 'global')
        self._handle(node, children)

    def _If(self, node):
        if self._is_elif(node):
            children = ['elif']
        else:
            children = ['if']
        children.extend([node.test, ':'])
        children.extend(node.body)
        if node.orelse:
            if len(node.orelse) == 1 and self._is_elif(node.orelse[0]):
                pass
            else:
                children.extend(['else', ':'])
            children.extend(node.orelse)
        self._handle(node, children)

    def _is_elif(self, node):
        if not isinstance(node, ast.If):
            return False
        offset = self.lines.get_line_start(node.lineno) + node.col_offset
        word = self.source[offset:offset + 4]
        # XXX: This is a bug; the offset does not point to the first
        alt_word = self.source[offset - 5:offset - 1]
        return 'elif' in (word, alt_word)

    def _IfExp(self, node):
        return self._handle(node, [node.body, 'if', node.test,
                                   'else', node.orelse])

    def _Import(self, node):
        children = ['import']
        children.extend(self._child_nodes(node.names, ','))
        self._handle(node, children)

    def _keyword(self, node):
        self._handle(node, [node.arg, '=', node.value])

    def _Lambda(self, node):
        self._handle(node, ['lambda', node.args, ':', node.body])

    def _List(self, node):
        self._handle(node, ['['] + self._child_nodes(node.elts, ',') + [']'])

    def _ListComp(self, node):
        children = ['[', node.elt]
        children.extend(node.generators)
        children.append(']')
        self._handle(node, children)

    def _Module(self, node):
        self._handle(node, node.body, eat_spaces=True)

    def _Name(self, node):
        self._handle(node, [node.id])

    def _Pass(self, node):
        self._handle(node, ['pass'])

    def _Print(self, node):
        children = ['print']
        if node.dest:
            children.extend(['>>', node.dest])
            if node.values:
                children.append(',')
        children.extend(self._child_nodes(node.values, ','))
        if not node.nl:
            children.append(',')
        self._handle(node, children)

    def _Raise(self, node):
        children = ['raise']
        if node.type:
            children.append(node.type)
        if node.inst:
            children.append(',')
            children.append(node.inst)
        if node.tback:
            children.append(',')
            children.append(node.tback)
        self._handle(node, children)

    def _Return(self, node):
        children = ['return']
        if node.value:
            children.append(node.value)
        self._handle(node, children)

    def _Sliceobj(self, node):
        children = []
        for index, slice in enumerate(node.nodes):
            if index > 0:
                children.append(':')
            if slice:
                children.append(slice)
        self._handle(node, children)

    def _Index(self, node):
        self._handle(node, [node.value])

    def _Subscript(self, node):
        self._handle(node, [node.value, '[', node.slice, ']'])

    def _Slice(self, node):
        children = []
        if node.lower:
            children.append(node.lower)
        children.append(':')
        if node.upper:
            children.append(node.upper)
        if node.step:
            children.append(':')
            children.append(node.step)
        self._handle(node, children)

    def _TryFinally(self, node):
        children = []
        if len(node.body) != 1 or not isinstance(node.body[0], ast.TryExcept):
            children.extend(['try', ':'])
        children.extend(node.body)
        children.extend(['finally', ':'])
        children.extend(node.finalbody)
        self._handle(node, children)

    def _TryExcept(self, node):
        children = ['try', ':']
        children.extend(node.body)
        children.extend(node.handlers)
        if node.orelse:
            children.extend(['else', ':'])
            children.extend(node.orelse)
        self._handle(node, children)

    def _excepthandler(self, node):
        children = ['except']
        if node.type:
            children.append(node.type)
        if node.name:
            children.extend([',', node.name])
        children.append(':')
        children.extend(node.body)
        self._handle(node, children)

    def _Tuple(self, node):
        if node.elts:
            self._handle(node, self._child_nodes(node.elts, ','),
                         eat_parens=True)
        else:
            self._handle(node, ['(', ')'])

    def _UnaryOp(self, node):
        children = self._get_op(node.op)
        children.append(node.operand)
        self._handle(node, children)

    def _Yield(self, node):
        children = ['yield']
        if node.value:
            children.append(node.value)
        self._handle(node, children)

    def _While(self, node):
        children = ['while', node.test, ':']
        children.extend(node.body)
        if node.orelse:
            children.extend(['else', ':'])
            children.extend(node.orelse)
        self._handle(node, children)

    def _With(self, node):
        children = ['with', node.context_expr]
        if node.optional_vars:
            children.extend(['as', node.optional_vars])
        children.append(':')
        children.extend(node.body)
        self._handle(node, children)

    def _child_nodes(self, nodes, separator):
        children = []
        for index, child in enumerate(nodes):
            children.append(child)
            if index < len(nodes) - 1:
                children.append(separator)
        return children


class _Source(object):

    def __init__(self, source):
        self.source = source
        self.offset = 0

    def consume(self, token):
        try:
            while True:
                new_offset = self.source.index(token, self.offset)
                if self._good_token(token, new_offset):
                    break
                else:
                    self._skip_comment()
        except (ValueError, TypeError):
            raise MismatchedTokenError(
                'Token <%s> at %s cannot be matched' %
                (token, self._get_location()))
        self.offset = new_offset + len(token)
        return (new_offset, self.offset)

    def consume_string(self):
        if _Source._string_pattern is None:
            original = codeanalyze.get_string_pattern()
            pattern = r'(%s)((\s|\\\n|#[^\n]*\n)*(%s))*' % \
                      (original, original)
            _Source._string_pattern = re.compile(pattern)
        repattern = _Source._string_pattern
        return self._consume_pattern(repattern)

    def consume_number(self):
        if _Source._number_pattern is None:
            _Source._number_pattern = re.compile(
                self._get_number_pattern())
        repattern = _Source._number_pattern
        return self._consume_pattern(repattern)

    def consume_not_equal(self):
        if _Source._not_equals_pattern is None:
            _Source._not_equals_pattern = re.compile(r'<>|!=')
        repattern = _Source._not_equals_pattern
        return self._consume_pattern(repattern)

    def _good_token(self, token, offset, start=None):
        """Checks whether consumed token is in comments"""
        if start is None:
            start = self.offset
        try:
            comment_index = self.source.rindex('#', start, offset)
        except ValueError:
            return True
        try:
            new_line_index = self.source.rindex('\n', start, offset)
        except ValueError:
            return False
        return comment_index < new_line_index

    def _skip_comment(self):
        self.offset = self.source.index('\n', self.offset + 1)

    def _get_location(self):
        lines = self.source[:self.offset].split('\n')
        return (len(lines), len(lines[-1]))

    def _consume_pattern(self, repattern):
        while True:
            match = repattern.search(self.source, self.offset)
            if self._good_token(match.group(), match.start()):
                break
            else:
                self._skip_comment()
        self.offset = match.end()
        return match.start(), match.end()

    def till_token(self, token):
        new_offset = self.source.index(token, self.offset)
        return self.get(self.offset, new_offset)

    def get(self, start, end):
        return self.source[start:end]

    def rfind_token(self, token, start, end):
        index = start
        while True:
            try:
                index = self.source.rindex(token, start, end)
                if self._good_token(token, index, start=start):
                    return index
                else:
                    end = index
            except ValueError:
                return None

    def from_offset(self, offset):
        return self.get(offset, self.offset)

    def find_backwards(self, pattern, offset):
        return self.source.rindex(pattern, 0, offset)

    def __getitem__(self, index):
        return self.source[index]

    def __getslice__(self, i, j):
        return self.source[i:j]

    def _get_number_pattern(self):
        # HACK: It is merely an approaximation and does the job
        integer = r'(0|0x)?[\da-fA-F]+[lL]?'
        return r'(%s(\.\d*)?|(\.\d+))([eE][-+]?\d*)?[jJ]?' % integer

    _string_pattern = None
    _number_pattern = None
    _not_equals_pattern = None
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.