desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Return whether object supports random access. If False, seek(), tell() and truncate() will raise IOError. This method may need to do a test seek().'
def seekable(self):
return False
'Internal: raise an IOError if file is not seekable'
def _checkSeekable(self, msg=None):
if (not self.seekable()): raise IOError((u'File or stream is not seekable.' if (msg is None) else msg))
'Return whether object was opened for reading. If False, read() will raise IOError.'
def readable(self):
return False
'Internal: raise an IOError if file is not readable'
def _checkReadable(self, msg=None):
if (not self.readable()): raise IOError((u'File or stream is not readable.' if (msg is None) else msg))
'Return whether object was opened for writing. If False, write() and truncate() will raise IOError.'
def writable(self):
return False
'Internal: raise an IOError if file is not writable'
def _checkWritable(self, msg=None):
if (not self.writable()): raise IOError((u'File or stream is not writable.' if (msg is None) else msg))
'closed: bool. True iff the file has been closed. For backwards compatibility, this is a property, not a predicate.'
@property def closed(self):
return self.__closed
'Internal: raise a ValueError if file is closed'
def _checkClosed(self, msg=None):
if self.closed: raise ValueError((u'I/O operation on closed file.' if (msg is None) else msg))
'Context management protocol. Returns self.'
def __enter__(self):
self._checkClosed() return self
'Context management protocol. Calls close()'
def __exit__(self, *args):
self.close()
'Returns underlying file descriptor if one exists. An IOError is raised if the IO object does not use a file descriptor.'
def fileno(self):
self._unsupported(u'fileno')
'Return whether this is an \'interactive\' stream. Return False if it can\'t be determined.'
def isatty(self):
self._checkClosed() return False
'Read and return a line from the stream. If limit is specified, at most limit bytes will be read. The line terminator is always b\'\n\' for binary files; for text files, the newlines argument to open can be used to select the line terminator(s) recognized.'
def readline(self, limit=(-1)):
if hasattr(self, u'peek'): def nreadahead(): readahead = self.peek(1) if (not readahead): return 1 n = ((readahead.find('\n') + 1) or len(readahead)) if (limit >= 0): n = min(n, limit) return n else: def nreadahead(): return 1 if (limit is None): limit = (-1) elif (not isinstance(limit, (int, long))): raise TypeError(u'limit must be an integer') res = bytearray() while ((limit < 0) or (len(res) < limit)): b = self.read(nreadahead()) if (not b): break res += b if res.endswith('\n'): break return bytes(res)
'Return a list of lines from the stream. hint can be specified to control the number of lines read: no more lines will be read if the total size (in bytes/characters) of all lines so far exceeds hint.'
def readlines(self, hint=None):
if ((hint is not None) and (not isinstance(hint, (int, long)))): raise TypeError(u'integer or None expected') if ((hint is None) or (hint <= 0)): return list(self) n = 0 lines = [] for line in self: lines.append(line) n += len(line) if (n >= hint): break return lines
'Read and return up to n bytes. Returns an empty bytes object on EOF, or None if the object is set not to block and has no data to read.'
def read(self, n=(-1)):
if (n is None): n = (-1) if (n < 0): return self.readall() b = bytearray(n.__index__()) n = self.readinto(b) if (n is None): return None del b[n:] return bytes(b)
'Read until EOF, using multiple read() call.'
def readall(self):
res = bytearray() while True: data = self.read(DEFAULT_BUFFER_SIZE) if (not data): break res += data if res: return bytes(res) else: return data
'Read up to len(b) bytes into b. Returns number of bytes read (0 for EOF), or None if the object is set not to block and has no data to read.'
def readinto(self, b):
self._unsupported(u'readinto')
'Write the given buffer to the IO stream. Returns the number of bytes written, which may be less than len(b).'
def write(self, b):
self._unsupported(u'write')
'Read and return up to n bytes. If the argument is omitted, None, or negative, reads and returns all data until EOF. If the argument is positive, and the underlying raw stream is not \'interactive\', multiple raw reads may be issued to satisfy the byte count (unless EOF is reached first). But for interactive raw streams (XXX and for pipes?), at most one raw read will be issued, and a short result does not imply that EOF is imminent. Returns an empty bytes array on EOF. Raises BlockingIOError if the underlying raw stream has no data at the moment.'
def read(self, n=None):
self._unsupported(u'read')
'Read up to n bytes with at most one read() system call.'
def read1(self, n=None):
self._unsupported(u'read1')
'Read up to len(b) bytes into b. Like read(), this may issue multiple reads to the underlying raw stream, unless the latter is \'interactive\'. Returns the number of bytes read (0 for EOF). Raises BlockingIOError if the underlying raw stream has no data at the moment.'
def readinto(self, b):
data = self.read(len(b)) n = len(data) try: b[:n] = data except TypeError as err: import array if (not isinstance(b, array.array)): raise err b[:n] = array.array('b', data) return n
'Write the given buffer to the IO stream. Return the number of bytes written, which is always len(b). Raises BlockingIOError if the buffer is full and the underlying raw stream cannot accept more data at the moment.'
def write(self, b):
self._unsupported(u'write')
'Separate the underlying raw stream from the buffer and return it. After the raw stream has been detached, the buffer is in an unusable state.'
def detach(self):
self._unsupported(u'detach')
'Return the bytes value (contents) of the buffer'
def getvalue(self):
if self.closed: raise ValueError(u'getvalue on closed file') return bytes(self._buffer)
'This is the same as read.'
def read1(self, n):
return self.read(n)
'Create a new buffered reader using the given readable raw IO object.'
def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
if (not raw.readable()): raise IOError(u'"raw" argument must be readable.') _BufferedIOMixin.__init__(self, raw) if (buffer_size <= 0): raise ValueError(u'invalid buffer size') self.buffer_size = buffer_size self._reset_read_buf() self._read_lock = Lock()
'Read n bytes. Returns exactly n bytes of data unless the underlying raw IO stream reaches EOF or if the call would block in non-blocking mode. If n is negative, read until EOF or until read() would block.'
def read(self, n=None):
if ((n is not None) and (n < (-1))): raise ValueError(u'invalid number of bytes to read') with self._read_lock: return self._read_unlocked(n)
'Returns buffered bytes without advancing the position. The argument indicates a desired minimal number of bytes; we do at most one raw read to satisfy it. We never return more than self.buffer_size.'
def peek(self, n=0):
with self._read_lock: return self._peek_unlocked(n)
'Reads up to n bytes, with at most one read() system call.'
def read1(self, n):
if (n < 0): raise ValueError(u'number of bytes to read must be positive') if (n == 0): return '' with self._read_lock: self._peek_unlocked(1) return self._read_unlocked(min(n, (len(self._read_buf) - self._read_pos)))
'Constructor. The arguments are two RawIO instances.'
def __init__(self, reader, writer, buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
if (max_buffer_size is not None): warnings.warn(u'max_buffer_size is deprecated', DeprecationWarning, 2) if (not reader.readable()): raise IOError(u'"reader" argument must be readable.') if (not writer.writable()): raise IOError(u'"writer" argument must be writable.') self.reader = BufferedReader(reader, buffer_size) self.writer = BufferedWriter(writer, buffer_size)
'Read at most n characters from stream. Read from underlying buffer until we have n characters or we hit EOF. If n is negative or omitted, read until EOF.'
def read(self, n=(-1)):
self._unsupported(u'read')
'Write string s to stream.'
def write(self, s):
self._unsupported(u'write')
'Truncate size to pos.'
def truncate(self, pos=None):
self._unsupported(u'truncate')
'Read until newline or EOF. Returns an empty string if EOF is hit immediately.'
def readline(self):
self._unsupported(u'readline')
'Separate the underlying buffer from the TextIOBase and return it. After the underlying buffer has been detached, the TextIO is in an unusable state.'
def detach(self):
self._unsupported(u'detach')
'Subclasses should override.'
@property def encoding(self):
return None
'Line endings translated so far. Only line endings translated during reading are considered. Subclasses should override.'
@property def newlines(self):
return None
'Error setting of the decoder or encoder. Subclasses should override.'
@property def errors(self):
return None
'Set the _decoded_chars buffer.'
def _set_decoded_chars(self, chars):
self._decoded_chars = chars self._decoded_chars_used = 0
'Advance into the _decoded_chars buffer.'
def _get_decoded_chars(self, n=None):
offset = self._decoded_chars_used if (n is None): chars = self._decoded_chars[offset:] else: chars = self._decoded_chars[offset:(offset + n)] self._decoded_chars_used += len(chars) return chars
'Rewind the _decoded_chars buffer.'
def _rewind_decoded_chars(self, n):
if (self._decoded_chars_used < n): raise AssertionError(u'rewind decoded_chars out of bounds') self._decoded_chars_used -= n
'Read and decode the next chunk of data from the BufferedReader.'
def _read_chunk(self):
if (self._decoder is None): raise ValueError(u'no decoder') if self._telling: (dec_buffer, dec_flags) = self._decoder.getstate() input_chunk = self.buffer.read1(self._CHUNK_SIZE) eof = (not input_chunk) self._set_decoded_chars(self._decoder.decode(input_chunk, eof)) if self._telling: self._snapshot = (dec_flags, (dec_buffer + input_chunk)) return (not eof)
'Format a paragraph of free-form text for inclusion in the help output at the current indentation level.'
def _format_text(self, text):
text_width = max((self.width - self.current_indent), 11) indent = (' ' * self.current_indent) return textwrap.fill(text, text_width, initial_indent=indent, subsequent_indent=indent)
'Return a comma-separated list of option strings & metavariables.'
def format_option_strings(self, option):
if option.takes_value(): metavar = (option.metavar or option.dest.upper()) short_opts = [(self._short_opt_fmt % (sopt, metavar)) for sopt in option._short_opts] long_opts = [(self._long_opt_fmt % (lopt, metavar)) for lopt in option._long_opts] else: short_opts = option._short_opts long_opts = option._long_opts if self.short_first: opts = (short_opts + long_opts) else: opts = (long_opts + short_opts) return ', '.join(opts)
'Update the option values from an arbitrary dictionary, but only use keys from dict that already have a corresponding attribute in self. Any keys in dict without a corresponding attribute are silently ignored.'
def _update_careful(self, dict):
for attr in dir(self): if (attr in dict): dval = dict[attr] if (dval is not None): setattr(self, attr, dval)
'Update the option values from an arbitrary dictionary, using all keys from the dictionary regardless of whether they have a corresponding attribute in self or not.'
def _update_loose(self, dict):
self.__dict__.update(dict)
'see OptionParser.destroy().'
def destroy(self):
del self._short_opt del self._long_opt del self.defaults
'add_option(Option) add_option(opt_str, ..., kwarg=val, ...)'
def add_option(self, *args, **kwargs):
if (type(args[0]) in types.StringTypes): option = self.option_class(*args, **kwargs) elif ((len(args) == 1) and (not kwargs)): option = args[0] if (not isinstance(option, Option)): raise TypeError, ('not an Option instance: %r' % option) else: raise TypeError, 'invalid arguments' self._check_conflict(option) self.option_list.append(option) option.container = self for opt in option._short_opts: self._short_opt[opt] = option for opt in option._long_opts: self._long_opt[opt] = option if (option.dest is not None): if (option.default is not NO_DEFAULT): self.defaults[option.dest] = option.default elif (option.dest not in self.defaults): self.defaults[option.dest] = None return option
'see OptionParser.destroy().'
def destroy(self):
OptionContainer.destroy(self) del self.option_list
'Declare that you are done with this OptionParser. This cleans up reference cycles so the OptionParser (and all objects referenced by it) can be garbage-collected promptly. After calling destroy(), the OptionParser is unusable.'
def destroy(self):
OptionContainer.destroy(self) for group in self.option_groups: group.destroy() del self.option_list del self.option_groups del self.formatter
'Set parsing to not stop on the first non-option, allowing interspersing switches with command arguments. This is the default behavior. See also disable_interspersed_args() and the class documentation description of the attribute allow_interspersed_args.'
def enable_interspersed_args(self):
self.allow_interspersed_args = True
'Set parsing to stop on the first non-option. Use this if you have a command processor which runs another command that has options of its own and you want to make sure these options don\'t get confused.'
def disable_interspersed_args(self):
self.allow_interspersed_args = False
'parse_args(args : [string] = sys.argv[1:], values : Values = None) -> (values : Values, args : [string]) Parse the command-line options found in \'args\' (default: sys.argv[1:]). Any errors result in a call to \'error()\', which by default prints the usage message to stderr and calls sys.exit() with an error message. On success returns a pair (values, args) where \'values\' is a Values instance (with all your option values) and \'args\' is the list of arguments left over after parsing options.'
def parse_args(self, args=None, values=None):
rargs = self._get_args(args) if (values is None): values = self.get_default_values() self.rargs = rargs self.largs = largs = [] self.values = values try: stop = self._process_args(largs, rargs, values) except (BadOptionError, OptionValueError) as err: self.error(str(err)) args = (largs + rargs) return self.check_values(values, args)
'check_values(values : Values, args : [string]) -> (values : Values, args : [string]) Check that the supplied option values and leftover arguments are valid. Returns the option values and leftover arguments (possibly adjusted, possibly completely new -- whatever you like). Default implementation just returns the passed-in values; subclasses may override as desired.'
def check_values(self, values, args):
return (values, args)
'_process_args(largs : [string], rargs : [string], values : Values) Process command-line arguments and populate \'values\', consuming options and arguments from \'rargs\'. If \'allow_interspersed_args\' is false, stop at the first non-option argument. If true, accumulate any interspersed non-option arguments in \'largs\'.'
def _process_args(self, largs, rargs, values):
while rargs: arg = rargs[0] if (arg == '--'): del rargs[0] return elif (arg[0:2] == '--'): self._process_long_opt(rargs, values) elif ((arg[:1] == '-') and (len(arg) > 1)): self._process_short_opts(rargs, values) elif self.allow_interspersed_args: largs.append(arg) del rargs[0] else: return
'_match_long_opt(opt : string) -> string Determine which long option string \'opt\' matches, ie. which one it is an unambiguous abbreviation for. Raises BadOptionError if \'opt\' doesn\'t unambiguously match any long option string.'
def _match_long_opt(self, opt):
return _match_abbrev(opt, self._long_opt)
'error(msg : string) Print a usage message incorporating \'msg\' to stderr and exit. If you override this in a subclass, it should not return -- it should either exit or raise an exception.'
def error(self, msg):
self.print_usage(sys.stderr) self.exit(2, ('%s: error: %s\n' % (self.get_prog_name(), msg)))
'print_usage(file : file = stdout) Print the usage message for the current program (self.usage) to \'file\' (default stdout). Any occurrence of the string "%prog" in self.usage is replaced with the name of the current program (basename of sys.argv[0]). Does nothing if self.usage is empty or not defined.'
def print_usage(self, file=None):
if self.usage: print >>file, self.get_usage()
'print_version(file : file = stdout) Print the version message for this program (self.version) to \'file\' (default stdout). As with print_usage(), any occurrence of "%prog" in self.version is replaced by the current program\'s name. Does nothing if self.version is empty or undefined.'
def print_version(self, file=None):
if self.version: print >>file, self.get_version()
'print_help(file : file = stdout) Print an extended help message, listing all options and any help text provided with them, to \'file\' (default stdout).'
def print_help(self, file=None):
if (file is None): file = sys.stdout encoding = self._get_encoding(file) file.write(self.format_help().encode(encoding, 'replace'))
'Return an iterator for one week of weekday numbers starting with the configured first one.'
def iterweekdays(self):
for i in range(self.firstweekday, (self.firstweekday + 7)): (yield (i % 7))
'Return an iterator for one month. The iterator will yield datetime.date values and will always iterate through complete weeks, so it will yield dates outside the specified month.'
def itermonthdates(self, year, month):
date = datetime.date(year, month, 1) days = ((date.weekday() - self.firstweekday) % 7) date -= datetime.timedelta(days=days) oneday = datetime.timedelta(days=1) while True: (yield date) try: date += oneday except OverflowError: break if ((date.month != month) and (date.weekday() == self.firstweekday)): break
'Like itermonthdates(), but will yield (day number, weekday number) tuples. For days outside the specified month the day number is 0.'
def itermonthdays2(self, year, month):
for date in self.itermonthdates(year, month): if (date.month != month): (yield (0, date.weekday())) else: (yield (date.day, date.weekday()))
'Like itermonthdates(), but will yield day numbers. For days outside the specified month the day number is 0.'
def itermonthdays(self, year, month):
for date in self.itermonthdates(year, month): if (date.month != month): (yield 0) else: (yield date.day)
'Return a matrix (list of lists) representing a month\'s calendar. Each row represents a week; week entries are datetime.date values.'
def monthdatescalendar(self, year, month):
dates = list(self.itermonthdates(year, month)) return [dates[i:(i + 7)] for i in range(0, len(dates), 7)]
'Return a matrix representing a month\'s calendar. Each row represents a week; week entries are (day number, weekday number) tuples. Day numbers outside this month are zero.'
def monthdays2calendar(self, year, month):
days = list(self.itermonthdays2(year, month)) return [days[i:(i + 7)] for i in range(0, len(days), 7)]
'Return a matrix representing a month\'s calendar. Each row represents a week; days outside this month are zero.'
def monthdayscalendar(self, year, month):
days = list(self.itermonthdays(year, month)) return [days[i:(i + 7)] for i in range(0, len(days), 7)]
'Return the data for the specified year ready for formatting. The return value is a list of month rows. Each month row contains up to width months. Each month contains between 4 and 6 weeks and each week contains 1-7 days. Days are datetime.date objects.'
def yeardatescalendar(self, year, width=3):
months = [self.monthdatescalendar(year, i) for i in range(January, (January + 12))] return [months[i:(i + width)] for i in range(0, len(months), width)]
'Return the data for the specified year ready for formatting (similar to yeardatescalendar()). Entries in the week lists are (day number, weekday number) tuples. Day numbers outside this month are zero.'
def yeardays2calendar(self, year, width=3):
months = [self.monthdays2calendar(year, i) for i in range(January, (January + 12))] return [months[i:(i + width)] for i in range(0, len(months), width)]
'Return the data for the specified year ready for formatting (similar to yeardatescalendar()). Entries in the week lists are day numbers. Day numbers outside this month are zero.'
def yeardayscalendar(self, year, width=3):
months = [self.monthdayscalendar(year, i) for i in range(January, (January + 12))] return [months[i:(i + width)] for i in range(0, len(months), width)]
'Print a single week (no newline).'
def prweek(self, theweek, width):
print self.formatweek(theweek, width),
'Returns a formatted day.'
def formatday(self, day, weekday, width):
if (day == 0): s = '' else: s = ('%2i' % day) return s.center(width)
'Returns a single week in a string (no newline).'
def formatweek(self, theweek, width):
return ' '.join((self.formatday(d, wd, width) for (d, wd) in theweek))
'Returns a formatted week day name.'
def formatweekday(self, day, width):
if (width >= 9): names = day_name else: names = day_abbr return names[day][:width].center(width)
'Return a header for a week.'
def formatweekheader(self, width):
return ' '.join((self.formatweekday(i, width) for i in self.iterweekdays()))
'Return a formatted month name.'
def formatmonthname(self, theyear, themonth, width, withyear=True):
s = month_name[themonth] if withyear: s = ('%s %r' % (s, theyear)) return s.center(width)
'Print a month\'s calendar.'
def prmonth(self, theyear, themonth, w=0, l=0):
print self.formatmonth(theyear, themonth, w, l),
'Return a month\'s calendar string (multi-line).'
def formatmonth(self, theyear, themonth, w=0, l=0):
w = max(2, w) l = max(1, l) s = self.formatmonthname(theyear, themonth, ((7 * (w + 1)) - 1)) s = s.rstrip() s += ('\n' * l) s += self.formatweekheader(w).rstrip() s += ('\n' * l) for week in self.monthdays2calendar(theyear, themonth): s += self.formatweek(week, w).rstrip() s += ('\n' * l) return s
'Returns a year\'s calendar as a multi-line string.'
def formatyear(self, theyear, w=2, l=1, c=6, m=3):
w = max(2, w) l = max(1, l) c = max(2, c) colwidth = (((w + 1) * 7) - 1) v = [] a = v.append a(repr(theyear).center(((colwidth * m) + (c * (m - 1)))).rstrip()) a(('\n' * l)) header = self.formatweekheader(w) for (i, row) in enumerate(self.yeardays2calendar(theyear, m)): months = range(((m * i) + 1), min(((m * (i + 1)) + 1), 13)) a(('\n' * l)) names = (self.formatmonthname(theyear, k, colwidth, False) for k in months) a(formatstring(names, colwidth, c).rstrip()) a(('\n' * l)) headers = (header for k in months) a(formatstring(headers, colwidth, c).rstrip()) a(('\n' * l)) height = max((len(cal) for cal in row)) for j in range(height): weeks = [] for cal in row: if (j >= len(cal)): weeks.append('') else: weeks.append(self.formatweek(cal[j], w)) a(formatstring(weeks, colwidth, c).rstrip()) a(('\n' * l)) return ''.join(v)
'Print a year\'s calendar.'
def pryear(self, theyear, w=0, l=0, c=6, m=3):
print self.formatyear(theyear, w, l, c, m)
'Return a day as a table cell.'
def formatday(self, day, weekday):
if (day == 0): return '<td class="noday">&nbsp;</td>' else: return ('<td class="%s">%d</td>' % (self.cssclasses[weekday], day))
'Return a complete week as a table row.'
def formatweek(self, theweek):
s = ''.join((self.formatday(d, wd) for (d, wd) in theweek)) return ('<tr>%s</tr>' % s)
'Return a weekday name as a table header.'
def formatweekday(self, day):
return ('<th class="%s">%s</th>' % (self.cssclasses[day], day_abbr[day]))
'Return a header for a week as a table row.'
def formatweekheader(self):
s = ''.join((self.formatweekday(i) for i in self.iterweekdays())) return ('<tr>%s</tr>' % s)
'Return a month name as a table row.'
def formatmonthname(self, theyear, themonth, withyear=True):
if withyear: s = ('%s %s' % (month_name[themonth], theyear)) else: s = ('%s' % month_name[themonth]) return ('<tr><th colspan="7" class="month">%s</th></tr>' % s)
'Return a formatted month as a table.'
def formatmonth(self, theyear, themonth, withyear=True):
v = [] a = v.append a('<table border="0" cellpadding="0" cellspacing="0" class="month">') a('\n') a(self.formatmonthname(theyear, themonth, withyear=withyear)) a('\n') a(self.formatweekheader()) a('\n') for week in self.monthdays2calendar(theyear, themonth): a(self.formatweek(week)) a('\n') a('</table>') a('\n') return ''.join(v)
'Return a formatted year as a table of tables.'
def formatyear(self, theyear, width=3):
v = [] a = v.append width = max(width, 1) a('<table border="0" cellpadding="0" cellspacing="0" class="year">') a('\n') a(('<tr><th colspan="%d" class="year">%s</th></tr>' % (width, theyear))) for i in range(January, (January + 12), width): months = range(i, min((i + width), 13)) a('<tr>') for m in months: a('<td>') a(self.formatmonth(theyear, m, withyear=False)) a('</td>') a('</tr>') a('</table>') return ''.join(v)
'Return a formatted year as a complete HTML page.'
def formatyearpage(self, theyear, width=3, css='calendar.css', encoding=None):
if (encoding is None): encoding = sys.getdefaultencoding() v = [] a = v.append a(('<?xml version="1.0" encoding="%s"?>\n' % encoding)) a('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n') a('<html>\n') a('<head>\n') a(('<meta http-equiv="Content-Type" content="text/html; charset=%s" />\n' % encoding)) if (css is not None): a(('<link rel="stylesheet" type="text/css" href="%s" />\n' % css)) a(('<title>Calendar for %d</title>\n' % theyear)) a('</head>\n') a('<body>\n') a(self.formatyear(theyear, width)) a('</body>\n') a('</html>\n') return ''.join(v).encode(encoding, 'xmlcharrefreplace')
'Return cookies as a string of "\n"-separated "Set-Cookie3" headers. ignore_discard and ignore_expires: see docstring for FileCookieJar.save'
def as_lwp_str(self, ignore_discard=True, ignore_expires=True):
now = time.time() r = [] for cookie in self: if ((not ignore_discard) and cookie.discard): continue if ((not ignore_expires) and cookie.is_expired(now)): continue r.append(('Set-Cookie3: %s' % lwp_cookie_str(cookie))) return '\n'.join((r + ['']))
'Visit a node.'
def visit(self, node):
method = ('visit_' + node.__class__.__name__) visitor = getattr(self, method, self.generic_visit) return visitor(node)
'Called if no explicit visitor function exists for a node.'
def generic_visit(self, node):
for (field, value) in iter_fields(node): if isinstance(value, list): for item in value: if isinstance(item, AST): self.visit(item) elif isinstance(value, AST): self.visit(value)
'Internal method. Returns a characteristic path of the pattern tree. This method must be run for all leaves until the linear subpatterns are merged into a single'
def leaf_to_root(self):
node = self subp = [] while node: if (node.type == TYPE_ALTERNATIVES): node.alternatives.append(subp) if (len(node.alternatives) == len(node.children)): subp = [tuple(node.alternatives)] node.alternatives = [] node = node.parent continue else: node = node.parent subp = None break if (node.type == TYPE_GROUP): node.group.append(subp) if (len(node.group) == len(node.children)): subp = get_characteristic_subpattern(node.group) node.group = [] node = node.parent continue else: node = node.parent subp = None break if ((node.type == token_labels.NAME) and node.name): subp.append(node.name) else: subp.append(node.type) node = node.parent return subp
'Drives the leaf_to_root method. The reason that leaf_to_root must be run multiple times is because we need to reject \'group\' matches; for example the alternative form (a | b c) creates a group [b c] that needs to be matched. Since matching multiple linear patterns overcomes the automaton\'s capabilities, leaf_to_root merges each group into a single choice based on \'characteristic\'ity, i.e. (a|b c) -> (a|b) if b more characteristic than c Returns: The most \'characteristic\'(as defined by get_characteristic_subpattern) path for the compiled pattern tree.'
def get_linear_subpattern(self):
for l in self.leaves(): subp = l.leaf_to_root() if subp: return subp
'Generator that returns the leaves of the tree'
def leaves(self):
for child in self.children: for x in child.leaves(): (yield x) if (not self.children): (yield self)
'Initializer. Takes an optional alternative filename for the pattern grammar.'
def __init__(self, grammar_file=_PATTERN_GRAMMAR_FILE):
self.grammar = driver.load_grammar(grammar_file) self.syms = pygram.Symbols(self.grammar) self.pygrammar = pygram.python_grammar self.pysyms = pygram.python_symbols self.driver = driver.Driver(self.grammar, convert=pattern_convert)
'Compiles a pattern string to a nested pytree.*Pattern object.'
def compile_pattern(self, input, debug=False, with_tree=False):
tokens = tokenize_wrapper(input) try: root = self.driver.parse_tokens(tokens, debug=debug) except parse.ParseError as e: raise PatternSyntaxError(str(e)) if with_tree: return (self.compile_node(root), root) else: return self.compile_node(root)
'Compiles a node, recursively. This is one big switch on the node type.'
def compile_node(self, node):
if (node.type == self.syms.Matcher): node = node.children[0] if (node.type == self.syms.Alternatives): alts = [self.compile_node(ch) for ch in node.children[::2]] if (len(alts) == 1): return alts[0] p = pytree.WildcardPattern([[a] for a in alts], min=1, max=1) return p.optimize() if (node.type == self.syms.Alternative): units = [self.compile_node(ch) for ch in node.children] if (len(units) == 1): return units[0] p = pytree.WildcardPattern([units], min=1, max=1) return p.optimize() if (node.type == self.syms.NegatedUnit): pattern = self.compile_basic(node.children[1:]) p = pytree.NegatedPattern(pattern) return p.optimize() assert (node.type == self.syms.Unit) name = None nodes = node.children if ((len(nodes) >= 3) and (nodes[1].type == token.EQUAL)): name = nodes[0].value nodes = nodes[2:] repeat = None if ((len(nodes) >= 2) and (nodes[(-1)].type == self.syms.Repeater)): repeat = nodes[(-1)] nodes = nodes[:(-1)] pattern = self.compile_basic(nodes, repeat) if (repeat is not None): assert (repeat.type == self.syms.Repeater) children = repeat.children child = children[0] if (child.type == token.STAR): min = 0 max = pytree.HUGE elif (child.type == token.PLUS): min = 1 max = pytree.HUGE elif (child.type == token.LBRACE): assert (children[(-1)].type == token.RBRACE) assert (len(children) in (3, 5)) min = max = self.get_int(children[1]) if (len(children) == 5): max = self.get_int(children[3]) else: assert False if ((min != 1) or (max != 1)): pattern = pattern.optimize() pattern = pytree.WildcardPattern([[pattern]], min=min, max=max) if (name is not None): pattern.name = name return pattern.optimize()
'Constructor. The grammar argument is a grammar.Grammar instance; see the grammar module for more information. The parser is not ready yet for parsing; you must call the setup() method to get it started. The optional convert argument is a function mapping concrete syntax tree nodes to abstract syntax tree nodes. If not given, no conversion is done and the syntax tree produced is the concrete syntax tree. If given, it must be a function of two arguments, the first being the grammar (a grammar.Grammar instance), and the second being the concrete syntax tree node to be converted. The syntax tree is converted from the bottom up. A concrete syntax tree node is a (type, value, context, nodes) tuple, where type is the node type (a token or symbol number), value is None for symbols and a string for tokens, context is None or an opaque value used for error reporting (typically a (lineno, offset) pair), and nodes is a list of children for symbols, and None for tokens. An abstract syntax tree node may be anything; this is entirely up to the converter function.'
def __init__(self, grammar, convert=None):
self.grammar = grammar self.convert = (convert or (lambda grammar, node: node))
'Prepare for parsing. This *must* be called before starting to parse. The optional argument is an alternative start symbol; it defaults to the grammar\'s start symbol. You can use a Parser instance to parse any number of programs; each time you call setup() the parser is reset to an initial state determined by the (implicit or explicit) start symbol.'
def setup(self, start=None):
if (start is None): start = self.grammar.start newnode = (start, None, None, []) stackentry = (self.grammar.dfas[start], 0, newnode) self.stack = [stackentry] self.rootnode = None self.used_names = set()
'Add a token; return True iff this is the end of the program.'
def addtoken(self, type, value, context):
ilabel = self.classify(type, value, context) while True: (dfa, state, node) = self.stack[(-1)] (states, first) = dfa arcs = states[state] for (i, newstate) in arcs: (t, v) = self.grammar.labels[i] if (ilabel == i): assert (t < 256) self.shift(type, value, newstate, context) state = newstate while (states[state] == [(0, state)]): self.pop() if (not self.stack): return True (dfa, state, node) = self.stack[(-1)] (states, first) = dfa return False elif (t >= 256): itsdfa = self.grammar.dfas[t] (itsstates, itsfirst) = itsdfa if (ilabel in itsfirst): self.push(t, self.grammar.dfas[t], newstate, context) break else: if ((0, state) in arcs): self.pop() if (not self.stack): raise ParseError('too much input', type, value, context) else: raise ParseError('bad input', type, value, context)