Edit File by line
/home/barbar84/public_h.../wp-conte.../plugins/sujqvwi/ShExBy/shex_roo.../lib64/python3..../lib2to3
File: pytree.py
# Copyright 2006 Google, Inc. All Rights Reserved.
[0] Fix | Delete
# Licensed to PSF under a Contributor Agreement.
[1] Fix | Delete
[2] Fix | Delete
"""
[3] Fix | Delete
Python parse tree definitions.
[4] Fix | Delete
[5] Fix | Delete
This is a very concrete parse tree; we need to keep every token and
[6] Fix | Delete
even the comments and whitespace between tokens.
[7] Fix | Delete
[8] Fix | Delete
There's also a pattern matching implementation here.
[9] Fix | Delete
"""
[10] Fix | Delete
[11] Fix | Delete
__author__ = "Guido van Rossum <guido@python.org>"
[12] Fix | Delete
[13] Fix | Delete
import sys
[14] Fix | Delete
import warnings
[15] Fix | Delete
from io import StringIO
[16] Fix | Delete
[17] Fix | Delete
HUGE = 0x7FFFFFFF # maximum repeat count, default max
[18] Fix | Delete
[19] Fix | Delete
_type_reprs = {}
[20] Fix | Delete
def type_repr(type_num):
[21] Fix | Delete
global _type_reprs
[22] Fix | Delete
if not _type_reprs:
[23] Fix | Delete
from .pygram import python_symbols
[24] Fix | Delete
# printing tokens is possible but not as useful
[25] Fix | Delete
# from .pgen2 import token // token.__dict__.items():
[26] Fix | Delete
for name, val in python_symbols.__dict__.items():
[27] Fix | Delete
if type(val) == int: _type_reprs[val] = name
[28] Fix | Delete
return _type_reprs.setdefault(type_num, type_num)
[29] Fix | Delete
[30] Fix | Delete
class Base(object):
[31] Fix | Delete
[32] Fix | Delete
"""
[33] Fix | Delete
Abstract base class for Node and Leaf.
[34] Fix | Delete
[35] Fix | Delete
This provides some default functionality and boilerplate using the
[36] Fix | Delete
template pattern.
[37] Fix | Delete
[38] Fix | Delete
A node may be a subnode of at most one parent.
[39] Fix | Delete
"""
[40] Fix | Delete
[41] Fix | Delete
# Default values for instance variables
[42] Fix | Delete
type = None # int: token number (< 256) or symbol number (>= 256)
[43] Fix | Delete
parent = None # Parent node pointer, or None
[44] Fix | Delete
children = () # Tuple of subnodes
[45] Fix | Delete
was_changed = False
[46] Fix | Delete
was_checked = False
[47] Fix | Delete
[48] Fix | Delete
def __new__(cls, *args, **kwds):
[49] Fix | Delete
"""Constructor that prevents Base from being instantiated."""
[50] Fix | Delete
assert cls is not Base, "Cannot instantiate Base"
[51] Fix | Delete
return object.__new__(cls)
[52] Fix | Delete
[53] Fix | Delete
def __eq__(self, other):
[54] Fix | Delete
"""
[55] Fix | Delete
Compare two nodes for equality.
[56] Fix | Delete
[57] Fix | Delete
This calls the method _eq().
[58] Fix | Delete
"""
[59] Fix | Delete
if self.__class__ is not other.__class__:
[60] Fix | Delete
return NotImplemented
[61] Fix | Delete
return self._eq(other)
[62] Fix | Delete
[63] Fix | Delete
__hash__ = None # For Py3 compatibility.
[64] Fix | Delete
[65] Fix | Delete
def _eq(self, other):
[66] Fix | Delete
"""
[67] Fix | Delete
Compare two nodes for equality.
[68] Fix | Delete
[69] Fix | Delete
This is called by __eq__ and __ne__. It is only called if the two nodes
[70] Fix | Delete
have the same type. This must be implemented by the concrete subclass.
[71] Fix | Delete
Nodes should be considered equal if they have the same structure,
[72] Fix | Delete
ignoring the prefix string and other context information.
[73] Fix | Delete
"""
[74] Fix | Delete
raise NotImplementedError
[75] Fix | Delete
[76] Fix | Delete
def clone(self):
[77] Fix | Delete
"""
[78] Fix | Delete
Return a cloned (deep) copy of self.
[79] Fix | Delete
[80] Fix | Delete
This must be implemented by the concrete subclass.
[81] Fix | Delete
"""
[82] Fix | Delete
raise NotImplementedError
[83] Fix | Delete
[84] Fix | Delete
def post_order(self):
[85] Fix | Delete
"""
[86] Fix | Delete
Return a post-order iterator for the tree.
[87] Fix | Delete
[88] Fix | Delete
This must be implemented by the concrete subclass.
[89] Fix | Delete
"""
[90] Fix | Delete
raise NotImplementedError
[91] Fix | Delete
[92] Fix | Delete
def pre_order(self):
[93] Fix | Delete
"""
[94] Fix | Delete
Return a pre-order iterator for the tree.
[95] Fix | Delete
[96] Fix | Delete
This must be implemented by the concrete subclass.
[97] Fix | Delete
"""
[98] Fix | Delete
raise NotImplementedError
[99] Fix | Delete
[100] Fix | Delete
def replace(self, new):
[101] Fix | Delete
"""Replace this node with a new one in the parent."""
[102] Fix | Delete
assert self.parent is not None, str(self)
[103] Fix | Delete
assert new is not None
[104] Fix | Delete
if not isinstance(new, list):
[105] Fix | Delete
new = [new]
[106] Fix | Delete
l_children = []
[107] Fix | Delete
found = False
[108] Fix | Delete
for ch in self.parent.children:
[109] Fix | Delete
if ch is self:
[110] Fix | Delete
assert not found, (self.parent.children, self, new)
[111] Fix | Delete
if new is not None:
[112] Fix | Delete
l_children.extend(new)
[113] Fix | Delete
found = True
[114] Fix | Delete
else:
[115] Fix | Delete
l_children.append(ch)
[116] Fix | Delete
assert found, (self.children, self, new)
[117] Fix | Delete
self.parent.changed()
[118] Fix | Delete
self.parent.children = l_children
[119] Fix | Delete
for x in new:
[120] Fix | Delete
x.parent = self.parent
[121] Fix | Delete
self.parent = None
[122] Fix | Delete
[123] Fix | Delete
def get_lineno(self):
[124] Fix | Delete
"""Return the line number which generated the invocant node."""
[125] Fix | Delete
node = self
[126] Fix | Delete
while not isinstance(node, Leaf):
[127] Fix | Delete
if not node.children:
[128] Fix | Delete
return
[129] Fix | Delete
node = node.children[0]
[130] Fix | Delete
return node.lineno
[131] Fix | Delete
[132] Fix | Delete
def changed(self):
[133] Fix | Delete
if self.parent:
[134] Fix | Delete
self.parent.changed()
[135] Fix | Delete
self.was_changed = True
[136] Fix | Delete
[137] Fix | Delete
def remove(self):
[138] Fix | Delete
"""
[139] Fix | Delete
Remove the node from the tree. Returns the position of the node in its
[140] Fix | Delete
parent's children before it was removed.
[141] Fix | Delete
"""
[142] Fix | Delete
if self.parent:
[143] Fix | Delete
for i, node in enumerate(self.parent.children):
[144] Fix | Delete
if node is self:
[145] Fix | Delete
self.parent.changed()
[146] Fix | Delete
del self.parent.children[i]
[147] Fix | Delete
self.parent = None
[148] Fix | Delete
return i
[149] Fix | Delete
[150] Fix | Delete
@property
[151] Fix | Delete
def next_sibling(self):
[152] Fix | Delete
"""
[153] Fix | Delete
The node immediately following the invocant in their parent's children
[154] Fix | Delete
list. If the invocant does not have a next sibling, it is None
[155] Fix | Delete
"""
[156] Fix | Delete
if self.parent is None:
[157] Fix | Delete
return None
[158] Fix | Delete
[159] Fix | Delete
# Can't use index(); we need to test by identity
[160] Fix | Delete
for i, child in enumerate(self.parent.children):
[161] Fix | Delete
if child is self:
[162] Fix | Delete
try:
[163] Fix | Delete
return self.parent.children[i+1]
[164] Fix | Delete
except IndexError:
[165] Fix | Delete
return None
[166] Fix | Delete
[167] Fix | Delete
@property
[168] Fix | Delete
def prev_sibling(self):
[169] Fix | Delete
"""
[170] Fix | Delete
The node immediately preceding the invocant in their parent's children
[171] Fix | Delete
list. If the invocant does not have a previous sibling, it is None.
[172] Fix | Delete
"""
[173] Fix | Delete
if self.parent is None:
[174] Fix | Delete
return None
[175] Fix | Delete
[176] Fix | Delete
# Can't use index(); we need to test by identity
[177] Fix | Delete
for i, child in enumerate(self.parent.children):
[178] Fix | Delete
if child is self:
[179] Fix | Delete
if i == 0:
[180] Fix | Delete
return None
[181] Fix | Delete
return self.parent.children[i-1]
[182] Fix | Delete
[183] Fix | Delete
def leaves(self):
[184] Fix | Delete
for child in self.children:
[185] Fix | Delete
yield from child.leaves()
[186] Fix | Delete
[187] Fix | Delete
def depth(self):
[188] Fix | Delete
if self.parent is None:
[189] Fix | Delete
return 0
[190] Fix | Delete
return 1 + self.parent.depth()
[191] Fix | Delete
[192] Fix | Delete
def get_suffix(self):
[193] Fix | Delete
"""
[194] Fix | Delete
Return the string immediately following the invocant node. This is
[195] Fix | Delete
effectively equivalent to node.next_sibling.prefix
[196] Fix | Delete
"""
[197] Fix | Delete
next_sib = self.next_sibling
[198] Fix | Delete
if next_sib is None:
[199] Fix | Delete
return ""
[200] Fix | Delete
return next_sib.prefix
[201] Fix | Delete
[202] Fix | Delete
if sys.version_info < (3, 0):
[203] Fix | Delete
def __str__(self):
[204] Fix | Delete
return str(self).encode("ascii")
[205] Fix | Delete
[206] Fix | Delete
class Node(Base):
[207] Fix | Delete
[208] Fix | Delete
"""Concrete implementation for interior nodes."""
[209] Fix | Delete
[210] Fix | Delete
def __init__(self,type, children,
[211] Fix | Delete
context=None,
[212] Fix | Delete
prefix=None,
[213] Fix | Delete
fixers_applied=None):
[214] Fix | Delete
"""
[215] Fix | Delete
Initializer.
[216] Fix | Delete
[217] Fix | Delete
Takes a type constant (a symbol number >= 256), a sequence of
[218] Fix | Delete
child nodes, and an optional context keyword argument.
[219] Fix | Delete
[220] Fix | Delete
As a side effect, the parent pointers of the children are updated.
[221] Fix | Delete
"""
[222] Fix | Delete
assert type >= 256, type
[223] Fix | Delete
self.type = type
[224] Fix | Delete
self.children = list(children)
[225] Fix | Delete
for ch in self.children:
[226] Fix | Delete
assert ch.parent is None, repr(ch)
[227] Fix | Delete
ch.parent = self
[228] Fix | Delete
if prefix is not None:
[229] Fix | Delete
self.prefix = prefix
[230] Fix | Delete
if fixers_applied:
[231] Fix | Delete
self.fixers_applied = fixers_applied[:]
[232] Fix | Delete
else:
[233] Fix | Delete
self.fixers_applied = None
[234] Fix | Delete
[235] Fix | Delete
def __repr__(self):
[236] Fix | Delete
"""Return a canonical string representation."""
[237] Fix | Delete
return "%s(%s, %r)" % (self.__class__.__name__,
[238] Fix | Delete
type_repr(self.type),
[239] Fix | Delete
self.children)
[240] Fix | Delete
[241] Fix | Delete
def __unicode__(self):
[242] Fix | Delete
"""
[243] Fix | Delete
Return a pretty string representation.
[244] Fix | Delete
[245] Fix | Delete
This reproduces the input source exactly.
[246] Fix | Delete
"""
[247] Fix | Delete
return "".join(map(str, self.children))
[248] Fix | Delete
[249] Fix | Delete
if sys.version_info > (3, 0):
[250] Fix | Delete
__str__ = __unicode__
[251] Fix | Delete
[252] Fix | Delete
def _eq(self, other):
[253] Fix | Delete
"""Compare two nodes for equality."""
[254] Fix | Delete
return (self.type, self.children) == (other.type, other.children)
[255] Fix | Delete
[256] Fix | Delete
def clone(self):
[257] Fix | Delete
"""Return a cloned (deep) copy of self."""
[258] Fix | Delete
return Node(self.type, [ch.clone() for ch in self.children],
[259] Fix | Delete
fixers_applied=self.fixers_applied)
[260] Fix | Delete
[261] Fix | Delete
def post_order(self):
[262] Fix | Delete
"""Return a post-order iterator for the tree."""
[263] Fix | Delete
for child in self.children:
[264] Fix | Delete
yield from child.post_order()
[265] Fix | Delete
yield self
[266] Fix | Delete
[267] Fix | Delete
def pre_order(self):
[268] Fix | Delete
"""Return a pre-order iterator for the tree."""
[269] Fix | Delete
yield self
[270] Fix | Delete
for child in self.children:
[271] Fix | Delete
yield from child.pre_order()
[272] Fix | Delete
[273] Fix | Delete
def _prefix_getter(self):
[274] Fix | Delete
"""
[275] Fix | Delete
The whitespace and comments preceding this node in the input.
[276] Fix | Delete
"""
[277] Fix | Delete
if not self.children:
[278] Fix | Delete
return ""
[279] Fix | Delete
return self.children[0].prefix
[280] Fix | Delete
[281] Fix | Delete
def _prefix_setter(self, prefix):
[282] Fix | Delete
if self.children:
[283] Fix | Delete
self.children[0].prefix = prefix
[284] Fix | Delete
[285] Fix | Delete
prefix = property(_prefix_getter, _prefix_setter)
[286] Fix | Delete
[287] Fix | Delete
def set_child(self, i, child):
[288] Fix | Delete
"""
[289] Fix | Delete
Equivalent to 'node.children[i] = child'. This method also sets the
[290] Fix | Delete
child's parent attribute appropriately.
[291] Fix | Delete
"""
[292] Fix | Delete
child.parent = self
[293] Fix | Delete
self.children[i].parent = None
[294] Fix | Delete
self.children[i] = child
[295] Fix | Delete
self.changed()
[296] Fix | Delete
[297] Fix | Delete
def insert_child(self, i, child):
[298] Fix | Delete
"""
[299] Fix | Delete
Equivalent to 'node.children.insert(i, child)'. This method also sets
[300] Fix | Delete
the child's parent attribute appropriately.
[301] Fix | Delete
"""
[302] Fix | Delete
child.parent = self
[303] Fix | Delete
self.children.insert(i, child)
[304] Fix | Delete
self.changed()
[305] Fix | Delete
[306] Fix | Delete
def append_child(self, child):
[307] Fix | Delete
"""
[308] Fix | Delete
Equivalent to 'node.children.append(child)'. This method also sets the
[309] Fix | Delete
child's parent attribute appropriately.
[310] Fix | Delete
"""
[311] Fix | Delete
child.parent = self
[312] Fix | Delete
self.children.append(child)
[313] Fix | Delete
self.changed()
[314] Fix | Delete
[315] Fix | Delete
[316] Fix | Delete
class Leaf(Base):
[317] Fix | Delete
[318] Fix | Delete
"""Concrete implementation for leaf nodes."""
[319] Fix | Delete
[320] Fix | Delete
# Default values for instance variables
[321] Fix | Delete
_prefix = "" # Whitespace and comments preceding this token in the input
[322] Fix | Delete
lineno = 0 # Line where this token starts in the input
[323] Fix | Delete
column = 0 # Column where this token tarts in the input
[324] Fix | Delete
[325] Fix | Delete
def __init__(self, type, value,
[326] Fix | Delete
context=None,
[327] Fix | Delete
prefix=None,
[328] Fix | Delete
fixers_applied=[]):
[329] Fix | Delete
"""
[330] Fix | Delete
Initializer.
[331] Fix | Delete
[332] Fix | Delete
Takes a type constant (a token number < 256), a string value, and an
[333] Fix | Delete
optional context keyword argument.
[334] Fix | Delete
"""
[335] Fix | Delete
assert 0 <= type < 256, type
[336] Fix | Delete
if context is not None:
[337] Fix | Delete
self._prefix, (self.lineno, self.column) = context
[338] Fix | Delete
self.type = type
[339] Fix | Delete
self.value = value
[340] Fix | Delete
if prefix is not None:
[341] Fix | Delete
self._prefix = prefix
[342] Fix | Delete
self.fixers_applied = fixers_applied[:]
[343] Fix | Delete
[344] Fix | Delete
def __repr__(self):
[345] Fix | Delete
"""Return a canonical string representation."""
[346] Fix | Delete
return "%s(%r, %r)" % (self.__class__.__name__,
[347] Fix | Delete
self.type,
[348] Fix | Delete
self.value)
[349] Fix | Delete
[350] Fix | Delete
def __unicode__(self):
[351] Fix | Delete
"""
[352] Fix | Delete
Return a pretty string representation.
[353] Fix | Delete
[354] Fix | Delete
This reproduces the input source exactly.
[355] Fix | Delete
"""
[356] Fix | Delete
return self.prefix + str(self.value)
[357] Fix | Delete
[358] Fix | Delete
if sys.version_info > (3, 0):
[359] Fix | Delete
__str__ = __unicode__
[360] Fix | Delete
[361] Fix | Delete
def _eq(self, other):
[362] Fix | Delete
"""Compare two nodes for equality."""
[363] Fix | Delete
return (self.type, self.value) == (other.type, other.value)
[364] Fix | Delete
[365] Fix | Delete
def clone(self):
[366] Fix | Delete
"""Return a cloned (deep) copy of self."""
[367] Fix | Delete
return Leaf(self.type, self.value,
[368] Fix | Delete
(self.prefix, (self.lineno, self.column)),
[369] Fix | Delete
fixers_applied=self.fixers_applied)
[370] Fix | Delete
[371] Fix | Delete
def leaves(self):
[372] Fix | Delete
yield self
[373] Fix | Delete
[374] Fix | Delete
def post_order(self):
[375] Fix | Delete
"""Return a post-order iterator for the tree."""
[376] Fix | Delete
yield self
[377] Fix | Delete
[378] Fix | Delete
def pre_order(self):
[379] Fix | Delete
"""Return a pre-order iterator for the tree."""
[380] Fix | Delete
yield self
[381] Fix | Delete
[382] Fix | Delete
def _prefix_getter(self):
[383] Fix | Delete
"""
[384] Fix | Delete
The whitespace and comments preceding this token in the input.
[385] Fix | Delete
"""
[386] Fix | Delete
return self._prefix
[387] Fix | Delete
[388] Fix | Delete
def _prefix_setter(self, prefix):
[389] Fix | Delete
self.changed()
[390] Fix | Delete
self._prefix = prefix
[391] Fix | Delete
[392] Fix | Delete
prefix = property(_prefix_getter, _prefix_setter)
[393] Fix | Delete
[394] Fix | Delete
def convert(gr, raw_node):
[395] Fix | Delete
"""
[396] Fix | Delete
Convert raw node information to a Node or Leaf instance.
[397] Fix | Delete
[398] Fix | Delete
This is passed to the parser driver which calls it whenever a reduction of a
[399] Fix | Delete
grammar rule produces a new complete node, so that the tree is build
[400] Fix | Delete
strictly bottom-up.
[401] Fix | Delete
"""
[402] Fix | Delete
type, value, context, children = raw_node
[403] Fix | Delete
if children or type in gr.number2symbol:
[404] Fix | Delete
# If there's exactly one child, return that child instead of
[405] Fix | Delete
# creating a new node.
[406] Fix | Delete
if len(children) == 1:
[407] Fix | Delete
return children[0]
[408] Fix | Delete
return Node(type, children, context=context)
[409] Fix | Delete
else:
[410] Fix | Delete
return Leaf(type, value, context=context)
[411] Fix | Delete
[412] Fix | Delete
[413] Fix | Delete
class BasePattern(object):
[414] Fix | Delete
[415] Fix | Delete
"""
[416] Fix | Delete
A pattern is a tree matching pattern.
[417] Fix | Delete
[418] Fix | Delete
It looks for a specific node type (token or symbol), and
[419] Fix | Delete
optionally for a specific content.
[420] Fix | Delete
[421] Fix | Delete
This is an abstract base class. There are three concrete
[422] Fix | Delete
subclasses:
[423] Fix | Delete
[424] Fix | Delete
- LeafPattern matches a single leaf node;
[425] Fix | Delete
- NodePattern matches a single node (usually non-leaf);
[426] Fix | Delete
- WildcardPattern matches a sequence of nodes of variable length.
[427] Fix | Delete
"""
[428] Fix | Delete
[429] Fix | Delete
# Defaults for instance variables
[430] Fix | Delete
type = None # Node type (token if < 256, symbol if >= 256)
[431] Fix | Delete
content = None # Optional content matching pattern
[432] Fix | Delete
name = None # Optional name used to store match in results dict
[433] Fix | Delete
[434] Fix | Delete
def __new__(cls, *args, **kwds):
[435] Fix | Delete
"""Constructor that prevents BasePattern from being instantiated."""
[436] Fix | Delete
assert cls is not BasePattern, "Cannot instantiate BasePattern"
[437] Fix | Delete
return object.__new__(cls)
[438] Fix | Delete
[439] Fix | Delete
def __repr__(self):
[440] Fix | Delete
args = [type_repr(self.type), self.content, self.name]
[441] Fix | Delete
while args and args[-1] is None:
[442] Fix | Delete
del args[-1]
[443] Fix | Delete
return "%s(%s)" % (self.__class__.__name__, ", ".join(map(repr, args)))
[444] Fix | Delete
[445] Fix | Delete
def optimize(self):
[446] Fix | Delete
"""
[447] Fix | Delete
A subclass can define this as a hook for optimizations.
[448] Fix | Delete
[449] Fix | Delete
Returns either self or another node with the same effect.
[450] Fix | Delete
"""
[451] Fix | Delete
return self
[452] Fix | Delete
[453] Fix | Delete
def match(self, node, results=None):
[454] Fix | Delete
"""
[455] Fix | Delete
Does this pattern exactly match a node?
[456] Fix | Delete
[457] Fix | Delete
Returns True if it matches, False if not.
[458] Fix | Delete
[459] Fix | Delete
If results is not None, it must be a dict which will be
[460] Fix | Delete
updated with the nodes matching named subpatterns.
[461] Fix | Delete
[462] Fix | Delete
Default implementation for non-wildcard patterns.
[463] Fix | Delete
"""
[464] Fix | Delete
if self.type is not None and node.type != self.type:
[465] Fix | Delete
return False
[466] Fix | Delete
if self.content is not None:
[467] Fix | Delete
r = None
[468] Fix | Delete
if results is not None:
[469] Fix | Delete
r = {}
[470] Fix | Delete
if not self._submatch(node, r):
[471] Fix | Delete
return False
[472] Fix | Delete
if r:
[473] Fix | Delete
results.update(r)
[474] Fix | Delete
if results is not None and self.name:
[475] Fix | Delete
results[self.name] = node
[476] Fix | Delete
return True
[477] Fix | Delete
[478] Fix | Delete
def match_seq(self, nodes, results=None):
[479] Fix | Delete
"""
[480] Fix | Delete
Does this pattern exactly match a sequence of nodes?
[481] Fix | Delete
[482] Fix | Delete
Default implementation for non-wildcard patterns.
[483] Fix | Delete
"""
[484] Fix | Delete
if len(nodes) != 1:
[485] Fix | Delete
return False
[486] Fix | Delete
return self.match(nodes[0], results)
[487] Fix | Delete
[488] Fix | Delete
def generate_matches(self, nodes):
[489] Fix | Delete
"""
[490] Fix | Delete
Generator yielding all matches for this pattern.
[491] Fix | Delete
[492] Fix | Delete
Default implementation for non-wildcard patterns.
[493] Fix | Delete
"""
[494] Fix | Delete
r = {}
[495] Fix | Delete
if nodes and self.match(nodes[0], r):
[496] Fix | Delete
yield 1, r
[497] Fix | Delete
[498] Fix | Delete
[499] Fix | Delete
12
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function