desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Return first release in which this feature was recognized. This is a 5-tuple, of the same form as sys.version_info.'
def getOptionalRelease(self):
return self.optional
'Return release in which this feature will become mandatory. This is a 5-tuple, of the same form as sys.version_info, or, if the feature was dropped, is None.'
def getMandatoryRelease(self):
return self.mandatory
'Return a distinct copy of the current font'
def copy(self):
return Font(self._tk, **self.actual())
'Return actual font attributes'
def actual(self, option=None, displayof=None):
args = () if displayof: args = ('-displayof', displayof) if option: args = (args + (('-' + option),)) return self._call('font', 'actual', self.name, *args) else: return self._mkdict(self._split(self._call('font', 'actual', self.name, *args)))
'Get font attribute'
def cget(self, option):
return self._call('font', 'config', self.name, ('-' + option))
'Modify font attributes'
def config(self, **options):
if options: self._call('font', 'config', self.name, *self._set(options)) else: return self._mkdict(self._split(self._call('font', 'config', self.name)))
'Return text width'
def measure(self, text, displayof=None):
args = (text,) if displayof: args = ('-displayof', displayof, text) return int(self._call('font', 'measure', self.name, *args))
'Return font metrics. For best performance, create a dummy widget using this font before calling this method.'
def metrics(self, *options, **kw):
args = () displayof = kw.pop('displayof', None) if displayof: args = ('-displayof', displayof) if options: args = (args + self._get(options)) return int(self._call('font', 'metrics', self.name, *args)) else: res = self._split(self._call('font', 'metrics', self.name, *...
'Tix maintains a list of directories under which the tix_getimage and tix_getbitmap commands will search for image files. The standard bitmap directory is $TIX_LIBRARY/bitmaps. The addbitmapdir command adds directory into this list. By using this command, the image files of an applications can also be located u...
def tix_addbitmapdir(self, directory):
return self.tk.call('tix', 'addbitmapdir', directory)
'Returns the current value of the configuration option given by option. Option may be any of the options described in the CONFIGURATION OPTIONS section.'
def tix_cget(self, option):
return self.tk.call('tix', 'cget', option)
'Query or modify the configuration options of the Tix application context. If no option is specified, returns a dictionary all of the available options. If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the...
def tix_configure(self, cnf=None, **kw):
if kw: cnf = _cnfmerge((cnf, kw)) elif cnf: cnf = _cnfmerge(cnf) if (cnf is None): return self._getconfigure('tix', 'configure') if isinstance(cnf, str): return self._getconfigure1('tix', 'configure', ('-' + cnf)) return self.tk.call((('tix', 'configure') + self._opti...
'Returns the file selection dialog that may be shared among different calls from this application. This command will create a file selection dialog widget when it is called the first time. This dialog will be returned by all subsequent calls to tix_filedialog. An optional dlgclass parameter can be passed to specified ...
def tix_filedialog(self, dlgclass=None):
if (dlgclass is not None): return self.tk.call('tix', 'filedialog', dlgclass) else: return self.tk.call('tix', 'filedialog')
'Locates a bitmap file of the name name.xpm or name in one of the bitmap directories (see the tix_addbitmapdir command above). By using tix_getbitmap, you can avoid hard coding the pathnames of the bitmap files in your application. When successful, it returns the complete pathname of the bitmap file, prefixed with the...
def tix_getbitmap(self, name):
return self.tk.call('tix', 'getbitmap', name)
'Locates an image file of the name name.xpm, name.xbm or name.ppm in one of the bitmap directories (see the addbitmapdir command above). If more than one file with the same name (but different extensions) exist, then the image type is chosen according to the depth of the X display: xbm images are chosen on monochrome d...
def tix_getimage(self, name):
return self.tk.call('tix', 'getimage', name)
'Gets the options maintained by the Tix scheme mechanism. Available options include: active_bg active_fg bg bold_font dark1_bg dark1_fg dark2_bg dark2_fg disabled_fg fg fixed_font font inactive_bg inactive_fg input1_bg input2_bg italic_font light...
def tix_option_get(self, name):
return self.tk.call('tix', 'option', 'get', name)
'Resets the scheme and fontset of the Tix application to newScheme and newFontSet, respectively. This affects only those widgets created after this call. Therefore, it is best to call the resetoptions command before the creation of any widgets in a Tix application. The optional parameter newScmPrio can be given to res...
def tix_resetoptions(self, newScheme, newFontSet, newScmPrio=None):
if (newScmPrio is not None): return self.tk.call('tix', 'resetoptions', newScheme, newFontSet, newScmPrio) else: return self.tk.call('tix', 'resetoptions', newScheme, newFontSet)
'Set a variable without calling its action routine'
def set_silent(self, value):
self.tk.call('tixSetSilent', self._w, value)
'Return the named subwidget (which must have been created by the sub-class).'
def subwidget(self, name):
n = self._subwidget_name(name) if (not n): raise TclError(((('Subwidget ' + name) + ' not child of ') + self._name)) n = n[(len(self._w) + 1):] return self._nametowidget(n)
'Return all subwidgets.'
def subwidgets_all(self):
names = self._subwidget_names() if (not names): return [] retlist = [] for name in names: name = name[(len(self._w) + 1):] try: retlist.append(self._nametowidget(name)) except: pass return retlist
'Get a subwidget name (returns a String, not a Widget !)'
def _subwidget_name(self, name):
try: return self.tk.call(self._w, 'subwidget', name) except TclError: return None
'Return the name of all subwidgets.'
def _subwidget_names(self):
try: x = self.tk.call(self._w, 'subwidgets', '-all') return self.tk.splitlist(x) except TclError: return None
'Set configuration options for all subwidgets (and self).'
def config_all(self, option, value):
if (option == ''): return elif (not isinstance(option, str)): option = repr(option) if (not isinstance(value, str)): value = repr(value) names = self._subwidget_names() for name in names: self.tk.call(name, 'configure', ('-' + option), value)
'Bind balloon widget to another. One balloon widget may be bound to several widgets at the same time'
def bind_widget(self, widget, cnf={}, **kw):
self.tk.call(self._w, 'bind', widget._w, *self._options(cnf, kw))
'Add a button with given name to box.'
def add(self, name, cnf={}, **kw):
btn = self.tk.call(self._w, 'add', name, *self._options(cnf, kw)) self.subwidget_list[name] = _dummyButton(self, name) return btn
'This command calls the setmode method for all the entries in this Tree widget: if an entry has no child entries, its mode is set to none. Otherwise, if the entry has any hidden child entries, its mode is set to open; otherwise its mode is set to close.'
def autosetmode(self):
self.tk.call(self._w, 'autosetmode')
'Close the entry given by entryPath if its mode is close.'
def close(self, entrypath):
self.tk.call(self._w, 'close', entrypath)
'Returns the current mode of the entry given by entryPath.'
def getmode(self, entrypath):
return self.tk.call(self._w, 'getmode', entrypath)
'Open the entry given by entryPath if its mode is open.'
def open(self, entrypath):
self.tk.call(self._w, 'open', entrypath)
'This command is used to indicate whether the entry given by entryPath has children entries and whether the children are visible. mode must be one of open, close or none. If mode is set to open, a (+) indicator is drawn next the entry. If mode is set to close, a (-) indicator is drawn next the entry. If mode is set to ...
def setmode(self, entrypath, mode='none'):
self.tk.call(self._w, 'setmode', entrypath, mode)
'This command calls the setmode method for all the entries in this Tree widget: if an entry has no child entries, its mode is set to none. Otherwise, if the entry has any hidden child entries, its mode is set to open; otherwise its mode is set to close.'
def autosetmode(self):
self.tk.call(self._w, 'autosetmode')
'Close the entry given by entryPath if its mode is close.'
def close(self, entrypath):
self.tk.call(self._w, 'close', entrypath)
'Returns the current mode of the entry given by entryPath.'
def getmode(self, entrypath):
return self.tk.call(self._w, 'getmode', entrypath)
'Open the entry given by entryPath if its mode is open.'
def open(self, entrypath):
self.tk.call(self._w, 'open', entrypath)
'Returns a list of items whose status matches status. If status is not specified, the list of items in the "on" status will be returned. Mode can be on, off, default'
def getselection(self, mode='on'):
c = self.tk.split(self.tk.call(self._w, 'getselection', mode)) return self.tk.splitlist(c)
'Returns the current status of entryPath.'
def getstatus(self, entrypath):
return self.tk.call(self._w, 'getstatus', entrypath)
'Sets the status of entryPath to be status. A bitmap will be displayed next to the entry its status is on, off or default.'
def setstatus(self, entrypath, mode='on'):
self.tk.call(self._w, 'setstatus', entrypath, mode)
'Removes the selection anchor.'
def anchor_clear(self):
self.tk.call(self, 'anchor', 'clear')
'Get the (x,y) coordinate of the current anchor cell'
def anchor_get(self):
return self._getints(self.tk.call(self, 'anchor', 'get'))
'Set the selection anchor to the cell at (x, y).'
def anchor_set(self, x, y):
self.tk.call(self, 'anchor', 'set', x, y)
'Delete rows between from_ and to inclusive. If to is not provided, delete only row at from_'
def delete_row(self, from_, to=None):
if (to is None): self.tk.call(self, 'delete', 'row', from_) else: self.tk.call(self, 'delete', 'row', from_, to)
'Delete columns between from_ and to inclusive. If to is not provided, delete only column at from_'
def delete_column(self, from_, to=None):
if (to is None): self.tk.call(self, 'delete', 'column', from_) else: self.tk.call(self, 'delete', 'column', from_, to)
'If any cell is being edited, de-highlight the cell and applies the changes.'
def edit_apply(self):
self.tk.call(self, 'edit', 'apply')
'Highlights the cell at (x, y) for editing, if the -editnotify command returns True for this cell.'
def edit_set(self, x, y):
self.tk.call(self, 'edit', 'set', x, y)
'Get the option value for cell at (x,y)'
def entrycget(self, x, y, option):
if (option and (option[0] != '-')): option = ('-' + option) return self.tk.call(self, 'entrycget', x, y, option)
'Return True if display item exists at (x,y)'
def info_exists(self, x, y):
return self._getboolean(self.tk.call(self, 'info', 'exists', x, y))
'Moves the range of columns from position FROM through TO by the distance indicated by OFFSET. For example, move_column(2, 4, 1) moves the columns 2,3,4 to columns 3,4,5.'
def move_column(self, from_, to, offset):
self.tk.call(self, 'move', 'column', from_, to, offset)
'Moves the range of rows from position FROM through TO by the distance indicated by OFFSET. For example, move_row(2, 4, 1) moves the rows 2,3,4 to rows 3,4,5.'
def move_row(self, from_, to, offset):
self.tk.call(self, 'move', 'row', from_, to, offset)
'Return coordinate of cell nearest pixel coordinate (x,y)'
def nearest(self, x, y):
return self._getints(self.tk.call(self, 'nearest', x, y))
'Queries or sets the size of the column given by INDEX. INDEX may be any non-negative integer that gives the position of a given column. INDEX can also be the string "default"; in this case, this command queries or sets the default size of all columns. When no option-value pair is given, this command returns a tuple c...
def size_column(self, index, **kw):
return self.tk.split(self.tk.call(self._w, 'size', 'column', index, *self._options({}, kw)))
'Queries or sets the size of the row given by INDEX. INDEX may be any non-negative integer that gives the position of a given row . INDEX can also be the string "default"; in this case, this command queries or sets the default size of all rows. When no option-value pair is given, this command returns a list con- tainin...
def size_row(self, index, **kw):
return self.tk.split(self.tk.call(self, 'size', 'row', index, *self._options({}, kw)))
'Clears the cell at (x, y) by removing its display item.'
def unset(self, x, y):
self.tk.call(self._w, 'unset', x, y)
'Initialize a dialog. Arguments: parent -- a parent window (the application window) title -- the dialog title'
def __init__(self, parent, title=None):
Toplevel.__init__(self, parent) self.withdraw() if parent.winfo_viewable(): self.transient(parent) if title: self.title(title) self.parent = parent self.result = None body = Frame(self) self.initial_focus = self.body(body) body.pack(padx=5, pady=5) self.buttonbox(...
'Destroy the window'
def destroy(self):
self.initial_focus = None Toplevel.destroy(self)
'create dialog body. return widget that should have initial focus. This method should be overridden, and is called by the __init__ method.'
def body(self, master):
pass
'add standard button box. override if you do not want the standard buttons'
def buttonbox(self):
box = Frame(self) w = Button(box, text='OK', width=10, command=self.ok, default=ACTIVE) w.pack(side=LEFT, padx=5, pady=5) w = Button(box, text='Cancel', width=10, command=self.cancel) w.pack(side=LEFT, padx=5, pady=5) self.bind('<Return>', self.ok) self.bind('<Escape>', self.cancel) box....
'validate the data This method is called automatically to validate the data before the dialog is destroyed. By default, it always validates OK.'
def validate(self):
return 1
'process the data This method is called automatically to process the data, *after* the dialog is destroyed. By default, it does nothing.'
def apply(self):
pass
'Indicate that a formerly enqueued task is complete. Used by Queue consumer threads. For each get() used to fetch a task, a subsequent call to task_done() tells the queue that the processing on the task is complete. If a join() is currently blocking, it will resume when all items have been processed (meaning that a ta...
def task_done(self):
with self.all_tasks_done: unfinished = (self.unfinished_tasks - 1) if (unfinished <= 0): if (unfinished < 0): raise ValueError('task_done() called too many times') self.all_tasks_done.notify_all() self.unfinished_tasks = unfinished
'Blocks until all items in the Queue have been gotten and processed. The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer thread calls task_done() to indicate the item was retrieved and all work on it is complete. When the count of unfinished tasks drops ...
def join(self):
with self.all_tasks_done: while self.unfinished_tasks: self.all_tasks_done.wait()
'Return the approximate size of the queue (not reliable!).'
def qsize(self):
with self.mutex: return self._qsize()
'Return True if the queue is empty, False otherwise (not reliable!). This method is likely to be removed at some point. Use qsize() == 0 as a direct substitute, but be aware that either approach risks a race condition where a queue can grow before the result of empty() or qsize() can be used. To create code that needs...
def empty(self):
with self.mutex: return (not self._qsize())
'Return True if the queue is full, False otherwise (not reliable!). This method is likely to be removed at some point. Use qsize() >= n as a direct substitute, but be aware that either approach risks a race condition where a queue can shrink before the result of full() or qsize() can be used.'
def full(self):
with self.mutex: return (0 < self.maxsize <= self._qsize())
'Put an item into the queue. If optional args \'block\' is true and \'timeout\' is None (the default), block if necessary until a free slot is available. If \'timeout\' is a non-negative number, it blocks at most \'timeout\' seconds and raises the Full exception if no free slot was available within that time. Otherwise...
def put(self, item, block=True, timeout=None):
with self.not_full: if (self.maxsize > 0): if (not block): if (self._qsize() >= self.maxsize): raise Full elif (timeout is None): while (self._qsize() >= self.maxsize): self.not_full.wait() elif (time...
'Remove and return an item from the queue. If optional args \'block\' is true and \'timeout\' is None (the default), block if necessary until an item is available. If \'timeout\' is a non-negative number, it blocks at most \'timeout\' seconds and raises the Empty exception if no item was available within that time. Oth...
def get(self, block=True, timeout=None):
with self.not_empty: if (not block): if (not self._qsize()): raise Empty elif (timeout is None): while (not self._qsize()): self.not_empty.wait() elif (timeout < 0): raise ValueError("'timeout' must be a non-nega...
'Put an item into the queue without blocking. Only enqueue the item if a free slot is immediately available. Otherwise raise the Full exception.'
def put_nowait(self, item):
return self.put(item, block=False)
'Remove and return an item from the queue without blocking. Only get an item if one is immediately available. Otherwise raise the Empty exception.'
def get_nowait(self):
return self.get(block=False)
'Create a new directory in the Directory table. There is a current component at each point in time for the directory, which is either explicitly created through start_component, or implicitly when files are added for the first time. Files are added into the current component, and into the cab file. To create a director...
def __init__(self, db, cab, basedir, physical, _logical, default, componentflags=None):
index = 1 _logical = make_id(_logical) logical = _logical while (logical in _directories): logical = ('%s%d' % (_logical, index)) index += 1 _directories.add(logical) self.db = db self.cab = cab self.basedir = basedir self.physical = physical self.logical = logica...
'Add an entry to the Component table, and make this component the current for this directory. If no component name is given, the directory name is used. If no feature is given, the current feature is used. If no flags are given, the directory\'s default flags are used. If no keyfile is given, the KeyPath is left null i...
def start_component(self, component=None, feature=None, flags=None, keyfile=None, uuid=None):
if (flags is None): flags = self.componentflags if (uuid is None): uuid = gen_uuid() else: uuid = uuid.upper() if (component is None): component = self.logical self.component = component if Win64: flags |= 256 if keyfile: keyid = self.cab.gen_i...
'Add a file to the current component of the directory, starting a new one if there is no current component. By default, the file name in the source and the file table will be identical. If the src file is specified, it is interpreted relative to the current directory. Optionally, a version and a language can be specifi...
def add_file(self, file, src=None, version=None, language=None):
if (not self.component): self.start_component(self.logical, current_feature, 0) if (not src): src = file file = os.path.basename(file) absolute = os.path.join(self.absolute, src) assert (not re.search('[\\?|><:/*]"', file)) if (file in self.keyfiles): logical = self.k...
'Add a list of files to the current component as specified in the glob pattern. Individual files can be excluded in the exclude list.'
def glob(self, pattern, exclude=None):
files = glob.glob1(self.absolute, pattern) for f in files: if (exclude and (f in exclude)): continue self.add_file(f) return files
'Remove .pyc/.pyo files on uninstall'
def remove_pyc(self):
add_data(self.db, 'RemoveFile', [((self.component + 'c'), self.component, '*.pyc', self.logical, 2), ((self.component + 'o'), self.component, '*.pyo', self.logical, 2)])
'Return current line number and offset.'
def getpos(self):
return (self.lineno, self.offset)
'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)
'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) ...
'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 no...
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 (imp...
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) ...
'Turn a token into a label. (Internal)'
def classify(self, type, value, context):
if (type == token.NAME): self.used_names.add(value) ilabel = self.grammar.keywords.get(value) if (ilabel is not None): return ilabel ilabel = self.grammar.tokens.get(type) if (ilabel is None): raise ParseError('bad token', type, value, context) return ilabe...
'Shift a token. (Internal)'
def shift(self, type, value, newstate, context):
(dfa, state, node) = self.stack[(-1)] newnode = (type, value, context, None) newnode = self.convert(self.grammar, newnode) if (newnode is not None): node[(-1)].append(newnode) self.stack[(-1)] = (dfa, newstate, node)
'Push a nonterminal. (Internal)'
def push(self, type, newdfa, newstate, context):
(dfa, state, node) = self.stack[(-1)] newnode = (type, None, context, []) self.stack[(-1)] = (dfa, newstate, node) self.stack.append((newdfa, 0, newnode))
'Pop a nonterminal. (Internal)'
def pop(self):
(popdfa, popstate, popnode) = self.stack.pop() newnode = self.convert(self.grammar, popnode) if (newnode is not None): if self.stack: (dfa, state, node) = self.stack[(-1)] node[(-1)].append(newnode) else: self.rootnode = newnode self.rootnode.u...
'Dump the grammar tables to a pickle file.'
def dump(self, filename):
with open(filename, 'wb') as f: pickle.dump(self.__dict__, f, 2)
'Load the grammar tables from a pickle file.'
def load(self, filename):
with open(filename, 'rb') as f: d = pickle.load(f) self.__dict__.update(d)
'Copy the grammar.'
def copy(self):
new = self.__class__() for dict_attr in ('symbol2number', 'number2symbol', 'dfas', 'keywords', 'tokens', 'symbol2label'): setattr(new, dict_attr, getattr(self, dict_attr).copy()) new.labels = self.labels[:] new.states = self.states[:] new.start = self.start return new
'Dump the grammar tables to standard output, for debugging.'
def report(self):
from pprint import pprint print 's2n' pprint(self.symbol2number) print 'n2s' pprint(self.number2symbol) print 'states' pprint(self.states) print 'dfas' pprint(self.dfas) print 'labels' pprint(self.labels) print ('start', self.start)
'Parse a series of tokens and return the syntax tree.'
def parse_tokens(self, tokens, debug=False):
p = parse.Parser(self.grammar, self.convert) p.setup() lineno = 1 column = 0 type = value = start = end = line_text = None prefix = '' for quintuple in tokens: (type, value, start, end, line_text) = quintuple if (start != (lineno, column)): assert ((lineno, column...
'Parse a stream and return the syntax tree.'
def parse_stream_raw(self, stream, debug=False):
tokens = tokenize.generate_tokens(stream.readline) return self.parse_tokens(tokens, debug)
'Parse a stream and return the syntax tree.'
def parse_stream(self, stream, debug=False):
return self.parse_stream_raw(stream, debug)
'Parse a file and return the syntax tree.'
def parse_file(self, filename, encoding=None, debug=False):
stream = codecs.open(filename, 'r', encoding) try: return self.parse_stream(stream, debug) finally: stream.close()
'Parse a string and return the syntax tree.'
def parse_string(self, text, debug=False):
tokens = tokenize.generate_tokens(io.StringIO(text).readline) return self.parse_tokens(tokens, debug)
'Load the grammar tables from the text files written by pgen.'
def run(self, graminit_h, graminit_c):
self.parse_graminit_h(graminit_h) self.parse_graminit_c(graminit_c) self.finish_off()
'Parse the .h file written by pgen. (Internal) This file is a sequence of #define statements defining the nonterminals of the grammar as numbers. We build two tables mapping the numbers to names and back.'
def parse_graminit_h(self, filename):
try: f = open(filename) except OSError as err: print ("Can't open %s: %s" % (filename, err)) return False self.symbol2number = {} self.number2symbol = {} lineno = 0 for line in f: lineno += 1 mo = re.match('^#define\\s+(\\w+)\\s+(\\d+)$', line) ...
'Parse the .c file written by pgen. (Internal) The file looks as follows. The first two lines are always this: #include "pgenheaders.h" #include "grammar.h" After that come four blocks: 1) one or more state definitions 2) a table defining dfas 3) a table defining labels 4) a struct defining the grammar A state defini...
def parse_graminit_c(self, filename):
try: f = open(filename) except OSError as err: print ("Can't open %s: %s" % (filename, err)) return False lineno = 0 (lineno, line) = ((lineno + 1), next(f)) assert (line == '#include "pgenheaders.h"\n'), (lineno, line) (lineno, line) = ((lineno + 1), next(f))...
'Create additional useful structures. (Internal).'
def finish_off(self):
self.keywords = {} self.tokens = {} for (ilabel, (type, value)) in enumerate(self.labels): if ((type == token.NAME) and (value is not None)): self.keywords[value] = ilabel elif (value is None): self.tokens[type] = ilabel
'Help the next test'
def _Call(self, name, args=None, prefix=None):
children = [] if isinstance(args, list): for arg in args: children.append(arg) children.append(Comma()) children.pop() return Call(Name(name), children, prefix)
'Setup a test source tree and output destination tree.'
def setup_test_source_trees(self):
self.temp_dir = tempfile.mkdtemp() self.py2_src_dir = os.path.join(self.temp_dir, 'python2_project') self.py3_dest_dir = os.path.join(self.temp_dir, 'python3_project') os.mkdir(self.py2_src_dir) os.mkdir(self.py3_dest_dir) self.setup_files = [] open(os.path.join(self.py2_src_dir, '__init__.p...
'2to3 a single directory with a new output dir and suffix.'
def test_filename_changing_on_output_single_dir(self):
self.setup_test_source_trees() out = io.StringIO() err = io.StringIO() suffix = 'TEST' ret = self.run_2to3_capture(['-n', '--add-suffix', suffix, '--write-unchanged-files', '--no-diffs', '--output-dir', self.py3_dest_dir, self.py2_src_dir], io.StringIO(''), out, err) self.assertEqual(ret, 0) ...