index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
28,299 | sqlobject.main | __repr__ | null | def __repr__(self):
if not hasattr(self, 'id'):
# Object initialization not finished. No attributes can be read.
return '<%s (not initialized)>' % self.__class__.__name__
return '<%s %r %s>' \
% (self.__class__.__name__,
self.id,
' '.join(
['%s=%s' % (name, repr(value))
for name, value in self._reprItems()]))
| (self) |
28,300 | sqlobject.main | __setstate__ | null | def __setstate__(self, d):
self.__init__(_SO_fetch_no_create=1)
self._SO_validatorState = sqlbuilder.SQLObjectState(self)
self._SO_writeLock = threading.Lock()
self._SO_createValues = {}
self.__dict__.update(d)
cls = self.__class__
cache = self._connection.cache
if cache.tryGet(self.id, cls) is not None:
raise ValueError(
"Cannot unpickle %s row with id=%s - "
"a different instance with the id already exists "
"in the cache" % (cls.__name__, self.id))
cache.created(self.id, cls, self)
| (self, d) |
28,301 | sqlobject.main | __sqlrepr__ | null | def __sqlrepr__(self, db):
return str(self.id)
| (self, db) |
28,302 | sqlobject.main | _create | null | def _create(self, id, **kw):
self.sqlmeta._creating = True
self._SO_createValues = {}
self._SO_validatorState = sqlbuilder.SQLObjectState(self)
# First we do a little fix-up on the keywords we were
# passed:
for column in self.sqlmeta.columnList:
# Then we check if the column wasn't passed in, and
# if not we try to get the default.
if column.name not in kw and column.foreignName not in kw:
default = column.default
# If we don't get it, it's an error:
# If we specified an SQL DEFAULT, then we should use that
if default is NoDefault:
if column.defaultSQL is None:
raise TypeError(
"%s() did not get expected keyword argument "
"'%s'" % (self.__class__.__name__, column.name))
else:
# There is defaultSQL for the column -
# do not put the column to kw
# so that the backend creates the value.
continue
# Otherwise we put it in as though they did pass
# that keyword:
kw[column.name] = default
self.set(**kw)
# Then we finalize the process:
self._SO_finishCreate(id)
| (self, id, **kw) |
28,303 | sqlobject.main | _init | null | def _init(self, id, connection=None, selectResults=None):
assert id is not None
# This function gets called only when the object is
# created, unlike __init__ which would be called
# anytime the object was returned from cache.
self.id = id
self._SO_writeLock = threading.Lock()
# If no connection was given, we'll inherit the class
# instance variable which should have a _connection
# attribute.
if (connection is not None) and \
(getattr(self, '_connection', None) is not connection):
self._connection = connection
# Sometimes we need to know if this instance is
# global or tied to a particular connection.
# This flag tells us that:
self.sqlmeta._perConnection = True
if not selectResults:
dbNames = [col.dbName for col in self.sqlmeta.columnList]
selectResults = self._connection._SO_selectOne(self, dbNames)
if not selectResults:
raise SQLObjectNotFound(
"The object %s by the ID %s does not exist" % (
self.__class__.__name__, self.id))
self._SO_selectInit(selectResults)
self._SO_createValues = {}
self.sqlmeta.dirty = False
| (self, id, connection=None, selectResults=None) |
28,304 | sqlobject.main | _reprItems | null | def _reprItems(self):
items = []
for _col in self.sqlmeta.columnList:
value = getattr(self, _col.name)
r = repr(value)
if len(r) > 20:
value = r[:17] + "..." + r[-1]
items.append((_col.name, value))
return items
| (self) |
28,305 | sqlobject.main | destroySelf | null | def destroySelf(self):
post_funcs = []
self.sqlmeta.send(events.RowDestroySignal, self, post_funcs)
# Kills this object. Kills it dead!
klass = self.__class__
# Free related joins on the base class
for join in klass.sqlmeta.joins:
if isinstance(join, joins.SORelatedJoin):
q = "DELETE FROM %s WHERE %s=%d" % (join.intermediateTable,
join.joinColumn, self.id)
self._connection.query(q)
depends = self._SO_depends()
for k in depends:
# Free related joins
for join in k.sqlmeta.joins:
if isinstance(join, joins.SORelatedJoin) and \
join.otherClassName == klass.__name__:
q = "DELETE FROM %s WHERE %s=%d" % (join.intermediateTable,
join.otherColumn,
self.id)
self._connection.query(q)
cols = findDependantColumns(klass.__name__, k)
# Don't confuse the rest of the process
if len(cols) == 0:
continue
query = []
restrict = False
for _col in cols:
query.append(getattr(k.q, _col.name) == self.id)
if _col.cascade is False:
# Found a restriction
restrict = True
query = sqlbuilder.OR(*query)
results = k.select(query, connection=self._connection)
if restrict and results.count():
# Restrictions only apply if there are
# matching records on the related table
raise SQLObjectIntegrityError(
"Tried to delete %s::%s but "
"table %s has a restriction against it" %
(klass.__name__, self.id, k.__name__))
setnull = {}
for _col in cols:
if _col.cascade == 'null':
setnull[_col.name] = None
if setnull:
for row in results:
clear = {}
for name in setnull:
if getattr(row, name) == self.id:
clear[name] = None
row.set(**clear)
delete = False
for _col in cols:
if _col.cascade is True:
delete = True
assert delete or setnull or restrict, (
"Class %s depends on %s accoriding to "
"findDependantColumns, but this seems inaccurate"
% (k, klass))
if delete:
for row in results:
row.destroySelf()
self.sqlmeta._obsolete = True
self._connection._SO_delete(self)
self._connection.cache.expire(self.id, self.__class__)
for func in post_funcs:
func(self)
post_funcs = []
self.sqlmeta.send(events.RowDestroyedSignal, self, post_funcs)
for func in post_funcs:
func(self)
| (self) |
28,306 | sqlobject.main | expire | null | def expire(self):
if self.sqlmeta.expired:
return
self._SO_writeLock.acquire()
try:
if self.sqlmeta.expired:
return
for column in self.sqlmeta.columnList:
delattr(self, instanceName(column.name))
self.sqlmeta.expired = True
self._connection.cache.expire(self.id, self.__class__)
self._SO_createValues = {}
finally:
self._SO_writeLock.release()
| (self) |
28,307 | sqlobject.main | set | null | def set(self, _suppress_set_sig=False, **kw):
if not self.sqlmeta._creating and \
not getattr(self.sqlmeta, "row_update_sig_suppress", False) \
and not _suppress_set_sig:
self.sqlmeta.send(events.RowUpdateSignal, self, kw)
# set() is used to update multiple values at once,
# potentially with one SQL statement if possible.
# Filter out items that don't map to column names.
# Those will be set directly on the object using
# setattr(obj, name, value).
def is_column(_c):
return _c in self.sqlmeta._plainSetters
def f_is_column(item):
return is_column(item[0])
def f_not_column(item):
return not is_column(item[0])
items = kw.items()
extra = dict(filter(f_not_column, items))
kw = dict(filter(f_is_column, items))
# _creating is special, see _SO_setValue
if self.sqlmeta._creating or self.sqlmeta.lazyUpdate:
for name, value in kw.items():
from_python = getattr(self, '_SO_from_python_%s' % name, None)
if from_python:
kw[name] = dbValue = from_python(value,
self._SO_validatorState)
else:
dbValue = value
to_python = getattr(self, '_SO_to_python_%s' % name, None)
if to_python:
value = to_python(dbValue, self._SO_validatorState)
setattr(self, instanceName(name), value)
self._SO_createValues.update(kw)
for name, value in extra.items():
try:
getattr(self.__class__, name)
except AttributeError:
if name not in self.sqlmeta.columns:
raise TypeError(
"%s.set() got an unexpected keyword argument "
"%s" % (self.__class__.__name__, name))
try:
setattr(self, name, value)
except AttributeError as e:
raise AttributeError('%s (with attribute %r)' % (e, name))
self.sqlmeta.dirty = True
return
self._SO_writeLock.acquire()
try:
# We have to go through and see if the setters are
# "plain", that is, if the user has changed their
# definition in any way (put in something that
# normalizes the value or checks for consistency,
# for instance). If so then we have to use plain
# old setattr() to change the value, since we can't
# read the user's mind. We'll combine everything
# else into a single UPDATE, if necessary.
toUpdate = {}
for name, value in kw.items():
from_python = getattr(self, '_SO_from_python_%s' % name, None)
if from_python:
dbValue = from_python(value, self._SO_validatorState)
else:
dbValue = value
to_python = getattr(self, '_SO_to_python_%s' % name, None)
if to_python:
value = to_python(dbValue, self._SO_validatorState)
if self.sqlmeta.cacheValues:
setattr(self, instanceName(name), value)
toUpdate[name] = dbValue
for name, value in extra.items():
try:
getattr(self.__class__, name)
except AttributeError:
if name not in self.sqlmeta.columns:
raise TypeError(
"%s.set() got an unexpected keyword argument "
"%s" % (self.__class__.__name__, name))
try:
setattr(self, name, value)
except AttributeError as e:
raise AttributeError('%s (with attribute %r)' % (e, name))
if toUpdate:
toUpdate = sorted(
toUpdate.items(),
key=lambda c: self.sqlmeta.columns[c[0]].creationOrder)
args = [(self.sqlmeta.columns[name].dbName, value)
for name, value in toUpdate]
self._connection._SO_update(self, args)
finally:
self._SO_writeLock.release()
post_funcs = []
self.sqlmeta.send(events.RowUpdatedSignal, self, post_funcs)
for func in post_funcs:
func(self)
| (self, _suppress_set_sig=False, **kw) |
28,308 | sqlobject.main | sync | null | def sync(self):
if self.sqlmeta.lazyUpdate and self._SO_createValues:
self.syncUpdate()
self._SO_writeLock.acquire()
try:
dbNames = [col.dbName for col in self.sqlmeta.columnList]
selectResults = self._connection._SO_selectOne(self, dbNames)
if not selectResults:
raise SQLObjectNotFound(
"The object %s by the ID %s has been deleted" % (
self.__class__.__name__, self.id))
self._SO_selectInit(selectResults)
self.sqlmeta.expired = False
finally:
self._SO_writeLock.release()
| (self) |
28,309 | sqlobject.main | syncUpdate | null | def syncUpdate(self):
if not self._SO_createValues:
return
self._SO_writeLock.acquire()
try:
if self.sqlmeta.columns:
columns = self.sqlmeta.columns
values = [(columns[v[0]].dbName, v[1])
for v in sorted(
self._SO_createValues.items(),
key=lambda c: columns[c[0]].creationOrder)]
self._connection._SO_update(self, values)
self.sqlmeta.dirty = False
self._SO_createValues = {}
finally:
self._SO_writeLock.release()
post_funcs = []
self.sqlmeta.send(events.RowUpdatedSignal, self, post_funcs)
for func in post_funcs:
func(self)
| (self) |
28,310 | sqlobject.main | tablesUsedImmediate | null | def tablesUsedImmediate(self):
return [self.__class__.q]
| (self) |
28,311 | sqlobject.main | SQLObjectIntegrityError | null | class SQLObjectIntegrityError(Exception):
pass
| null |
28,312 | sqlobject.main | SQLObjectNotFound | null | class SQLObjectNotFound(LookupError):
pass
| null |
28,313 | sqlobject.joins | SQLRelatedJoin | null | class SQLRelatedJoin(RelatedJoin):
baseClass = SOSQLRelatedJoin
| (otherClass=None, **kw) |
28,318 | sqlobject.col | SetCol | null | class SetCol(Col):
baseClass = SOSetCol
| (name=None, **kw) |
28,325 | sqlobject.joins | SingleJoin | null | class SingleJoin(Join):
baseClass = SOSingleJoin
| (otherClass=None, **kw) |
28,330 | sqlobject.col | SmallIntCol | null | class SmallIntCol(Col):
baseClass = SOSmallIntCol
| (name=None, **kw) |
28,337 | sqlobject.col | StringCol | null | class StringCol(Col):
baseClass = SOStringCol
| (name=None, **kw) |
28,344 | sqlobject.styles | Style |
The base Style class, and also the simplest implementation. No
translation occurs -- column names and attribute names match,
as do class names and table names (when using auto class or
schema generation).
| class Style(object):
"""
The base Style class, and also the simplest implementation. No
translation occurs -- column names and attribute names match,
as do class names and table names (when using auto class or
schema generation).
"""
def __init__(self, pythonAttrToDBColumn=None,
dbColumnToPythonAttr=None,
pythonClassToDBTable=None,
dbTableToPythonClass=None,
idForTable=None,
longID=False):
if pythonAttrToDBColumn:
self.pythonAttrToDBColumn = \
lambda a, s=self: pythonAttrToDBColumn(s, a)
if dbColumnToPythonAttr:
self.dbColumnToPythonAttr = \
lambda a, s=self: dbColumnToPythonAttr(s, a)
if pythonClassToDBTable:
self.pythonClassToDBTable = \
lambda a, s=self: pythonClassToDBTable(s, a)
if dbTableToPythonClass:
self.dbTableToPythonClass = \
lambda a, s=self: dbTableToPythonClass(s, a)
if idForTable:
self.idForTable = lambda a, s=self: idForTable(s, a)
self.longID = longID
def pythonAttrToDBColumn(self, attr):
return attr
def dbColumnToPythonAttr(self, col):
return col
def pythonClassToDBTable(self, className):
return className
def dbTableToPythonClass(self, table):
return table
def idForTable(self, table):
if self.longID:
return self.tableReference(table)
else:
return 'id'
def pythonClassToAttr(self, className):
return lowerword(className)
def instanceAttrToIDAttr(self, attr):
return attr + "ID"
def instanceIDAttrToAttr(self, attr):
return attr[:-2]
def tableReference(self, table):
return table + "_id"
| (pythonAttrToDBColumn=None, dbColumnToPythonAttr=None, pythonClassToDBTable=None, dbTableToPythonClass=None, idForTable=None, longID=False) |
28,346 | sqlobject.styles | dbColumnToPythonAttr | null | def dbColumnToPythonAttr(self, col):
return col
| (self, col) |
28,347 | sqlobject.styles | dbTableToPythonClass | null | def dbTableToPythonClass(self, table):
return table
| (self, table) |
28,351 | sqlobject.styles | pythonAttrToDBColumn | null | def pythonAttrToDBColumn(self, attr):
return attr
| (self, attr) |
28,355 | sqlobject.col | TimeCol | null | class TimeCol(Col):
baseClass = SOTimeCol
| (name=None, **kw) |
28,362 | sqlobject.col | TimedeltaCol | null | class TimedeltaCol(Col):
baseClass = SOTimedeltaCol
| (name=None, **kw) |
28,369 | sqlobject.col | TimestampCol | null | class TimestampCol(Col):
baseClass = SOTimestampCol
| (name=None, **kw) |
28,376 | sqlobject.col | TinyIntCol | null | class TinyIntCol(Col):
baseClass = SOTinyIntCol
| (name=None, **kw) |
28,383 | sqlobject.col | UnicodeCol | null | class UnicodeCol(Col):
baseClass = SOUnicodeCol
| (name=None, **kw) |
28,390 | sqlobject.col | UuidCol | null | class UuidCol(Col):
baseClass = SOUuidCol
| (name=None, **kw) |
28,410 | sqlobject.main | getID | null | def getID(obj, refColumn=None):
if isinstance(obj, SQLObject):
return getattr(obj, refColumn or 'id')
elif isinstance(obj, int):
return obj
elif isinstance(obj, long):
return int(obj)
elif isinstance(obj, str):
try:
return int(obj)
except ValueError:
return obj
elif obj is None:
return None
| (obj, refColumn=None) |
28,411 | sqlobject.main | getObject | null | def getObject(obj, klass):
if isinstance(obj, int):
return klass(obj)
elif isinstance(obj, long):
return klass(int(obj))
elif isinstance(obj, str):
return klass(int(obj))
elif obj is None:
return None
else:
return obj
| (obj, klass) |
28,421 | sqlobject.main | sqlmeta |
This object is the object we use to keep track of all sorts of
information. Subclasses are made for each SQLObject subclass
(dynamically if necessary), and instances are created to go
alongside every SQLObject instance.
| class sqlmeta(with_metaclass(declarative.DeclarativeMeta, object)):
"""
This object is the object we use to keep track of all sorts of
information. Subclasses are made for each SQLObject subclass
(dynamically if necessary), and instances are created to go
alongside every SQLObject instance.
"""
table = None
idName = None
idSize = None # Allowed values are 'TINY/SMALL/MEDIUM/BIG/None'
idSequence = None
# This function is used to coerce IDs into the proper format,
# so you should replace it with str, or another function, if you
# aren't using integer IDs
idType = int
style = None
lazyUpdate = False
defaultOrder = None
cacheValues = True
registry = None
fromDatabase = False
# Default is false, but we set it to true for the *instance*
# when necessary: (bad clever? maybe)
expired = False
# This is a mapping from column names to SOCol (or subclass)
# instances:
columns = {}
columnList = []
# This is a mapping from column names to Col (or subclass)
# instances; these objects don't have the logic that the SOCol
# objects do, and are not attached to this class closely.
columnDefinitions = {}
# These are lists of the join and index objects:
indexes = []
indexDefinitions = []
joins = []
joinDefinitions = []
# These attributes shouldn't be shared with superclasses:
_unshared_attributes = ['table', 'columns', 'childName']
# These are internal bookkeeping attributes; the class-level
# definition is a default for the instances, instances will
# reset these values.
# When an object is being created, it has an instance
# variable _creating, which is true. This way all the
# setters can be captured until the object is complete,
# and then the row is inserted into the database. Once
# that happens, _creating is deleted from the instance,
# and only the class variable (which is always false) is
# left.
_creating = False
_obsolete = False
# Sometimes an intance is attached to a connection, not
# globally available. In that case, self.sqlmeta._perConnection
# will be true. It's false by default:
_perConnection = False
# Inheritance definitions:
parentClass = None # A reference to the parent class
childClasses = {} # References to child classes, keyed by childName
childName = None # Class name for inheritance child object creation
# Does the row require syncing?
dirty = False
# Default encoding for UnicodeCol's
dbEncoding = None
def __classinit__(cls, new_attrs):
for attr in cls._unshared_attributes:
if attr not in new_attrs:
setattr(cls, attr, None)
declarative.setup_attributes(cls, new_attrs)
def __init__(self, instance):
self.instance = weakref.proxy(instance)
@classmethod
def send(cls, signal, *args, **kw):
events.send(signal, cls.soClass, *args, **kw)
@classmethod
def setClass(cls, soClass):
if cls.idType not in (int, str):
raise TypeError('sqlmeta.idType must be int or str, not %r'
% cls.idType)
if cls.idSize not in ('TINY', 'SMALL', 'MEDIUM', 'BIG', None):
raise ValueError(
"sqlmeta.idType must be 'TINY', 'SMALL', 'MEDIUM', 'BIG' "
"or None, not %r" % cls.idSize)
cls.soClass = soClass
if not cls.style:
cls.style = styles.defaultStyle
try:
if cls.soClass._connection and cls.soClass._connection.style:
cls.style = cls.soClass._connection.style
except AttributeError:
pass
if cls.table is None:
cls.table = cls.style.pythonClassToDBTable(cls.soClass.__name__)
if cls.idName is None:
cls.idName = cls.style.idForTable(cls.table)
# plainSetters are columns that haven't been overridden by the
# user, so we can contact the database directly to set them.
# Note that these can't set these in the SQLObject class
# itself, because they specific to this subclass of SQLObject,
# and cannot be shared among classes.
cls._plainSetters = {}
cls._plainGetters = {}
cls._plainForeignSetters = {}
cls._plainForeignGetters = {}
cls._plainJoinGetters = {}
cls._plainJoinAdders = {}
cls._plainJoinRemovers = {}
# This is a dictionary of columnName: columnObject
# None of these objects can be shared with superclasses
cls.columns = {}
cls.columnList = []
# These, however, can be shared:
cls.columnDefinitions = cls.columnDefinitions.copy()
cls.indexes = []
cls.indexDefinitions = cls.indexDefinitions[:]
cls.joins = []
cls.joinDefinitions = cls.joinDefinitions[:]
############################################################
# Adding special values, like columns and indexes
############################################################
########################################
# Column handling
########################################
@classmethod
def addColumn(cls, columnDef, changeSchema=False, connection=None):
post_funcs = []
cls.send(events.AddColumnSignal, cls.soClass, connection,
columnDef.name, columnDef, changeSchema, post_funcs)
sqlmeta = cls
soClass = cls.soClass
del cls
column = columnDef.withClass(soClass)
name = column.name
assert name != 'id', (
"The 'id' column is implicit, and should not be defined as "
"a column")
assert name not in sqlmeta.columns, (
"The class %s.%s already has a column %r (%r), you cannot "
"add the column %r"
% (soClass.__module__, soClass.__name__, name,
sqlmeta.columnDefinitions[name], columnDef))
# Collect columns from the parent classes to test
# if the column is not in a parent class
parent_columns = []
for base in soClass.__bases__:
if hasattr(base, "sqlmeta"):
parent_columns.extend(base.sqlmeta.columns.keys())
if hasattr(soClass, name):
assert (name in parent_columns) or (name == "childName"), (
"The class %s.%s already has a variable or method %r, "
"you cannot add the column %r" % (
soClass.__module__, soClass.__name__, name, name))
sqlmeta.columnDefinitions[name] = columnDef
sqlmeta.columns[name] = column
# A stable-ordered version of the list...
sqlmeta.columnList.append(column)
###################################################
# Create the getter function(s). We'll start by
# creating functions like _SO_get_columnName,
# then if there's no function named _get_columnName
# we'll alias that to _SO_get_columnName. This
# allows a sort of super call, even though there's
# no superclass that defines the database access.
if sqlmeta.cacheValues:
# We create a method here, which is just a function
# that takes "self" as the first argument.
getter = eval(
'lambda self: self._SO_loadValue(%s)' %
repr(instanceName(name)))
else:
# If we aren't caching values, we just call the
# function _SO_getValue, which fetches from the
# database.
getter = eval('lambda self: self._SO_getValue(%s)' % repr(name))
setattr(soClass, rawGetterName(name), getter)
# Here if the _get_columnName method isn't in the
# definition, we add it with the default
# _SO_get_columnName definition.
if not hasattr(soClass, getterName(name)) or (name == 'childName'):
setattr(soClass, getterName(name), getter)
sqlmeta._plainGetters[name] = 1
#################################################
# Create the setter function(s)
# Much like creating the getters, we will create
# _SO_set_columnName methods, and then alias them
# to _set_columnName if the user hasn't defined
# those methods themself.
# @@: This is lame; immutable right now makes it unsettable,
# making the table read-only
if not column.immutable:
# We start by just using the _SO_setValue method
setter = eval(
'lambda self, val: self._SO_setValue'
'(%s, val, self.%s, self.%s)' % (
repr(name),
'_SO_from_python_%s' % name, '_SO_to_python_%s' % name))
setattr(soClass, '_SO_from_python_%s' % name, column.from_python)
setattr(soClass, '_SO_to_python_%s' % name, column.to_python)
setattr(soClass, rawSetterName(name), setter)
# Then do the aliasing
if not hasattr(soClass, setterName(name)) or (name == 'childName'):
setattr(soClass, setterName(name), setter)
# We keep track of setters that haven't been
# overridden, because we can combine these
# set columns into one SQL UPDATE query.
sqlmeta._plainSetters[name] = 1
##################################################
# Here we check if the column is a foreign key, in
# which case we need to make another method that
# fetches the key and constructs the sister
# SQLObject instance.
if column.foreignKey:
# We go through the standard _SO_get_columnName deal
# we're giving the object, not the ID of the
# object this time:
origName = column.origName
if sqlmeta.cacheValues:
# self._SO_class_className is a reference
# to the class in question.
getter = eval(
'lambda self: self._SO_foreignKey'
'(self._SO_loadValue(%r), self._SO_class_%s, %s)' %
(instanceName(name), column.foreignKey,
column.refColumn and repr(column.refColumn)))
else:
# Same non-caching version as above.
getter = eval(
'lambda self: self._SO_foreignKey'
'(self._SO_getValue(%s), self._SO_class_%s, %s)' %
(repr(name), column.foreignKey,
column.refColumn and repr(column.refColumn)))
setattr(soClass, rawGetterName(origName), getter)
# And we set the _get_columnName version
if not hasattr(soClass, getterName(origName)):
setattr(soClass, getterName(origName), getter)
sqlmeta._plainForeignGetters[origName] = 1
if not column.immutable:
# The setter just gets the ID of the object,
# and then sets the real column.
setter = eval(
'lambda self, val: '
'setattr(self, %s, self._SO_getID(val, %s))' %
(repr(name), column.refColumn and repr(column.refColumn)))
setattr(soClass, rawSetterName(origName), setter)
if not hasattr(soClass, setterName(origName)):
setattr(soClass, setterName(origName), setter)
sqlmeta._plainForeignSetters[origName] = 1
classregistry.registry(sqlmeta.registry).addClassCallback(
column.foreignKey,
lambda foreign, me, attr: setattr(me, attr, foreign),
soClass, '_SO_class_%s' % column.foreignKey)
if column.alternateMethodName:
func = eval(
'lambda cls, val, connection=None: '
'cls._SO_fetchAlternateID(%s, %s, val, connection=connection)'
% (repr(column.name), repr(column.dbName)))
setattr(soClass, column.alternateMethodName, classmethod(func))
if changeSchema:
conn = connection or soClass._connection
conn.addColumn(sqlmeta.table, column)
if soClass._SO_finishedClassCreation:
makeProperties(soClass)
for func in post_funcs:
func(soClass, column)
@classmethod
def addColumnsFromDatabase(sqlmeta, connection=None):
soClass = sqlmeta.soClass
conn = connection or soClass._connection
for columnDef in conn.columnsFromSchema(sqlmeta.table, soClass):
if columnDef.name not in sqlmeta.columnDefinitions:
if isinstance(columnDef.name, unicode_type) and PY2:
columnDef.name = columnDef.name.encode('ascii')
sqlmeta.addColumn(columnDef)
@classmethod
def delColumn(cls, column, changeSchema=False, connection=None):
sqlmeta = cls
soClass = sqlmeta.soClass
if isinstance(column, str):
if column in sqlmeta.columns:
column = sqlmeta.columns[column]
elif column + 'ID' in sqlmeta.columns:
column = sqlmeta.columns[column + 'ID']
else:
raise ValueError('Unknown column ' + column)
if isinstance(column, col.Col):
for c in sqlmeta.columns.values():
if column is c.columnDef:
column = c
break
else:
raise IndexError(
"Column with definition %r not found" % column)
post_funcs = []
cls.send(events.DeleteColumnSignal, cls.soClass, connection,
column.name, column, post_funcs)
name = column.name
del sqlmeta.columns[name]
del sqlmeta.columnDefinitions[name]
sqlmeta.columnList.remove(column)
delattr(soClass, rawGetterName(name))
if name in sqlmeta._plainGetters:
delattr(soClass, getterName(name))
delattr(soClass, rawSetterName(name))
if name in sqlmeta._plainSetters:
delattr(soClass, setterName(name))
if column.foreignKey:
delattr(soClass,
rawGetterName(soClass.sqlmeta.style.
instanceIDAttrToAttr(name)))
if name in sqlmeta._plainForeignGetters:
delattr(soClass, getterName(name))
delattr(soClass,
rawSetterName(soClass.sqlmeta.style.
instanceIDAttrToAttr(name)))
if name in sqlmeta._plainForeignSetters:
delattr(soClass, setterName(name))
if column.alternateMethodName:
delattr(soClass, column.alternateMethodName)
if changeSchema:
conn = connection or soClass._connection
conn.delColumn(sqlmeta, column)
if soClass._SO_finishedClassCreation:
unmakeProperties(soClass)
makeProperties(soClass)
for func in post_funcs:
func(soClass, column)
########################################
# Join handling
########################################
@classmethod
def addJoin(cls, joinDef):
sqlmeta = cls
soClass = cls.soClass
# The name of the method we'll create. If it's
# automatically generated, it's generated by the
# join class.
join = joinDef.withClass(soClass)
meth = join.joinMethodName
sqlmeta.joins.append(join)
index = len(sqlmeta.joins) - 1
if joinDef not in sqlmeta.joinDefinitions:
sqlmeta.joinDefinitions.append(joinDef)
# The function fetches the join by index, and
# then lets the join object do the rest of the
# work:
func = eval(
'lambda self: self.sqlmeta.joins[%i].performJoin(self)' % index)
# And we do the standard _SO_get_... _get_... deal
setattr(soClass, rawGetterName(meth), func)
if not hasattr(soClass, getterName(meth)):
setattr(soClass, getterName(meth), func)
sqlmeta._plainJoinGetters[meth] = 1
# Some joins allow you to remove objects from the
# join.
if hasattr(join, 'remove'):
# Again, we let it do the remove, and we do the
# standard naming trick.
func = eval(
'lambda self, obj: self.sqlmeta.joins[%i].remove(self, obj)' %
index)
setattr(soClass, '_SO_remove' + join.addRemoveName, func)
if not hasattr(soClass, 'remove' + join.addRemoveName):
setattr(soClass, 'remove' + join.addRemoveName, func)
sqlmeta._plainJoinRemovers[meth] = 1
# Some joins allow you to add objects.
if hasattr(join, 'add'):
# And again...
func = eval(
'lambda self, obj: self.sqlmeta.joins[%i].add(self, obj)' %
index)
setattr(soClass, '_SO_add' + join.addRemoveName, func)
if not hasattr(soClass, 'add' + join.addRemoveName):
setattr(soClass, 'add' + join.addRemoveName, func)
sqlmeta._plainJoinAdders[meth] = 1
if soClass._SO_finishedClassCreation:
makeProperties(soClass)
@classmethod
def delJoin(sqlmeta, joinDef):
soClass = sqlmeta.soClass
for join in sqlmeta.joins:
# previously deleted joins will be None, so it must
# be skipped or it'll error out on the next line.
if join is None:
continue
if joinDef is join.joinDef:
break
else:
raise IndexError(
"Join %r not found in class %r (from %r)"
% (joinDef, soClass, sqlmeta.joins))
meth = join.joinMethodName
sqlmeta.joinDefinitions.remove(joinDef)
for i in range(len(sqlmeta.joins)):
if sqlmeta.joins[i] is join:
# Have to leave None, because we refer to joins
# by index.
sqlmeta.joins[i] = None
delattr(soClass, rawGetterName(meth))
if meth in sqlmeta._plainJoinGetters:
delattr(soClass, getterName(meth))
if hasattr(join, 'remove'):
delattr(soClass, '_SO_remove' + join.addRemovePrefix)
if meth in sqlmeta._plainJoinRemovers:
delattr(soClass, 'remove' + join.addRemovePrefix)
if hasattr(join, 'add'):
delattr(soClass, '_SO_add' + join.addRemovePrefix)
if meth in sqlmeta._plainJoinAdders:
delattr(soClass, 'add' + join.addRemovePrefix)
if soClass._SO_finishedClassCreation:
unmakeProperties(soClass)
makeProperties(soClass)
########################################
# Indexes
########################################
@classmethod
def addIndex(cls, indexDef):
cls.indexDefinitions.append(indexDef)
index = indexDef.withClass(cls.soClass)
cls.indexes.append(index)
setattr(cls.soClass, index.name, index)
########################################
# Utility methods
########################################
@classmethod
def getColumns(sqlmeta):
return sqlmeta.columns.copy()
def asDict(self):
"""
Return the object as a dictionary of columns to values.
"""
result = {}
for key in self.getColumns():
result[key] = getattr(self.instance, key)
result['id'] = self.instance.id
return result
@classmethod
def expireAll(sqlmeta, connection=None):
"""
Expire all instances of this class.
"""
soClass = sqlmeta.soClass
connection = connection or soClass._connection
cache_set = connection.cache
cache_set.weakrefAll(soClass)
for item in cache_set.getAll(soClass):
item.expire()
| (instance) |
28,422 | sqlobject.main | __classinit__ | null | def __classinit__(cls, new_attrs):
for attr in cls._unshared_attributes:
if attr not in new_attrs:
setattr(cls, attr, None)
declarative.setup_attributes(cls, new_attrs)
| (cls, new_attrs) |
28,423 | sqlobject.main | __init__ | null | def __init__(self, instance):
self.instance = weakref.proxy(instance)
| (self, instance) |
28,424 | sqlobject.main | asDict |
Return the object as a dictionary of columns to values.
| def asDict(self):
"""
Return the object as a dictionary of columns to values.
"""
result = {}
for key in self.getColumns():
result[key] = getattr(self.instance, key)
result['id'] = self.instance.id
return result
| (self) |
28,428 | sqlobject.col | use_microseconds | null | def use_microseconds(use=True):
if use:
SODateTimeCol.datetimeFormat = '%Y-%m-%d %H:%M:%S.%f'
SOTimeCol.timeFormat = '%H:%M:%S.%f'
dt_types = [(datetime.datetime, converters.DateTimeConverterMS),
(datetime.time, converters.TimeConverterMS)]
else:
SODateTimeCol.datetimeFormat = '%Y-%m-%d %H:%M:%S'
SOTimeCol.timeFormat = '%H:%M:%S'
dt_types = [(datetime.datetime, converters.DateTimeConverter),
(datetime.time, converters.TimeConverter)]
for dt_type, converter in dt_types:
converters.registerConverter(dt_type, converter)
| (use=True) |
28,430 | func2argparse | LoadFromFile | null | class LoadFromFile(argparse.Action):
def __init__(self, unmatched_args="error", *args, **kwargs):
super().__init__(*args, **kwargs)
if unmatched_args not in ("error", "warning"):
raise RuntimeError("unmatched_args can only be set to error or warning")
self.unmatched_args = unmatched_args
def _error_unfound(self, key, namespace):
if key not in namespace:
if self.unmatched_args == "error":
raise ValueError(f"Unknown argument in config file: {key}")
elif self.unmatched_args == "warning":
print(f"WARNING: Unknown argument in config file: {key}")
# parser.add_argument('--file', type=open, action=LoadFromFile)
def __call__(self, parser, namespace, values, option_string=None):
import yaml
import json
if values.name.endswith("yaml") or values.name.endswith("yml"):
with values as f:
config = yaml.load(f, Loader=yaml.FullLoader)
for key in config.keys():
self._error_unfound(key, namespace)
namespace.__dict__.update(config)
elif values.name.endswith("json"):
with values as f:
config = json.load(f)
if "execid" in config and "params" in config:
# Special case for PlayMolecule
config = config["params"]
for prm in config:
key = prm["name"]
self._error_unfound(key, namespace)
namespace.__dict__[key] = prm["value"]
else:
# General use case similar to yaml above
for key in config.keys():
self._error_unfound(key, namespace)
namespace.__dict__.update(config)
else:
raise ValueError("Configuration file must end with yaml or yml")
| (unmatched_args='error', *args, **kwargs) |
28,431 | func2argparse | __call__ | null | def __call__(self, parser, namespace, values, option_string=None):
import yaml
import json
if values.name.endswith("yaml") or values.name.endswith("yml"):
with values as f:
config = yaml.load(f, Loader=yaml.FullLoader)
for key in config.keys():
self._error_unfound(key, namespace)
namespace.__dict__.update(config)
elif values.name.endswith("json"):
with values as f:
config = json.load(f)
if "execid" in config and "params" in config:
# Special case for PlayMolecule
config = config["params"]
for prm in config:
key = prm["name"]
self._error_unfound(key, namespace)
namespace.__dict__[key] = prm["value"]
else:
# General use case similar to yaml above
for key in config.keys():
self._error_unfound(key, namespace)
namespace.__dict__.update(config)
else:
raise ValueError("Configuration file must end with yaml or yml")
| (self, parser, namespace, values, option_string=None) |
28,432 | func2argparse | __init__ | null | def __init__(self, unmatched_args="error", *args, **kwargs):
super().__init__(*args, **kwargs)
if unmatched_args not in ("error", "warning"):
raise RuntimeError("unmatched_args can only be set to error or warning")
self.unmatched_args = unmatched_args
| (self, unmatched_args='error', *args, **kwargs) |
28,434 | func2argparse | _error_unfound | null | def _error_unfound(self, key, namespace):
if key not in namespace:
if self.unmatched_args == "error":
raise ValueError(f"Unknown argument in config file: {key}")
elif self.unmatched_args == "warning":
print(f"WARNING: Unknown argument in config file: {key}")
| (self, key, namespace) |
28,439 | func2argparse | _get_name_abbreviations | null | def _get_name_abbreviations(argnames):
abbrevs = {"help": "h"}
def get_abbr(name):
pieces = name.split("_")
for i in range(len(pieces)):
yield "".join([p[0] for p in pieces[: i + 1]])
# Last attempt
name = name.replace("_", "")
for i in range(1, len(name) + 1):
yield name[:i]
for argname in argnames:
if argname[0] == "_":
continue # Don't add underscore arguments to argparser
for abb in get_abbr(argname):
if abb not in abbrevs.values():
abbrevs[argname] = abb
break
return abbrevs
| (argnames) |
28,440 | func2argparse | _parse_docs | null | def _parse_docs(doc):
import re
from ast import literal_eval
reg1 = re.compile(r"^(\S+)\s*:")
reg2 = re.compile(r"choices=([\(\[].*[\)\]])")
reg3 = re.compile(r"gui_options=(.*)")
reg4 = re.compile(r"nargs=(\d+)")
lines = doc.splitlines()
name = lines[0].strip().split()[0]
description = []
for line in lines[1:]:
if line.strip().startswith("Parameters"):
break
if len(line.strip()):
description.append(line.strip())
description = " ".join(description)
argdocs = OrderedDict()
currvar = None
paramsection = False
for i in range(len(lines)):
line = lines[i].strip()
if paramsection:
if reg1.match(line):
currvar = reg1.findall(line)[0]
argdocs[currvar] = {"doc": "", "choices": None}
choices = reg2.findall(line)
if len(choices):
argdocs[currvar]["choices"] = literal_eval(choices[0])
gui_options = reg3.findall(line)
if len(gui_options):
argdocs[currvar]["gui_options"] = literal_eval(gui_options[0])
nargs = reg4.findall(line)
if len(nargs):
argdocs[currvar]["nargs"] = int(nargs[0])
elif currvar is not None:
# Everything after the initial variable line counts as help
argdocs[currvar]["doc"] += line + " "
if line.startswith("Parameters"):
paramsection = True
if paramsection and line == "":
paramsection = False
return argdocs, description, name
| (doc) |
28,443 | func2argparse | func_to_argparser | null | def func_to_argparser(
func, exit_on_error=True, allow_conf_yaml=False, unmatched_args="error"
):
import inspect
from typing import get_origin, get_args
sig = inspect.signature(func)
doc = func.__doc__
if doc is None:
raise RuntimeError("Could not find documentation in the function...")
argdocs, description, name = _parse_docs(doc)
try:
parser = argparse.ArgumentParser(
name,
description=description,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
exit_on_error=exit_on_error,
)
except Exception:
parser = argparse.ArgumentParser(
name,
description=description,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
if allow_conf_yaml:
parser.add_argument(
"--conf",
help="Configuration YAML file to set all parameters",
type=open,
action=lambda *x, **y: LoadFromFile(*x, **y, unmatched_args=unmatched_args),
)
# Calculate abbreviations
abbrevs = _get_name_abbreviations(sig.parameters)
for argname in sig.parameters:
if argname[0] == "_" or argname in ("args", "kwargs"):
continue # Don't add underscore arguments to argparser or args, kwargs
params = sig.parameters[argname]
if argname not in argdocs:
raise RuntimeError(
f"Could not find help for argument {argname} in the docstring of the function. Please document it."
)
argtype = params.annotation
nargs = None
# This is needed for compound types like: list[str]
if get_origin(params.annotation) is not None:
origtype = get_origin(params.annotation)
argtype = get_args(params.annotation)[0]
if origtype in (list, tuple):
nargs = "+"
default = None
if params.default != inspect._empty:
default = params.default
# Don't allow empty list defaults., convert to None
if type(default) in (list, tuple) and len(default) == 0:
raise RuntimeError(
f"Please don't use empty tuples/lists as default arguments (e.g. {argname}=()). Use =None instead"
)
if type(argtype) == tuple:
raise RuntimeError(
f"Failed to get type annotation for argument '{argname}'"
)
if argtype == bool:
if nargs is None:
if default:
raise RuntimeError(
"func2argparse does not allow boolean flags with default value True"
)
parser.add_argument(
f"--{argname.replace('_', '-')}",
f"-{abbrevs[argname]}",
help=argdocs[argname]["doc"].strip(),
action="store_true",
)
else:
parser.add_argument(
f"--{argname.replace('_', '-')}",
f"-{abbrevs[argname]}",
help=argdocs[argname]["doc"].strip(),
default=default,
type=str_to_bool,
required=params.default == inspect._empty,
nargs=nargs,
)
else:
help = argdocs[argname]["doc"].strip()
choices = argdocs[argname]["choices"]
parser.add_argument(
f"--{argname.replace('_', '-')}",
f"-{abbrevs[argname]}",
help=help,
default=default,
type=argtype,
choices=choices,
required=params.default == inspect._empty,
nargs=nargs,
)
return parser
| (func, exit_on_error=True, allow_conf_yaml=False, unmatched_args='error') |
28,444 | func2argparse | func_to_manifest | null | def func_to_manifest(func, file=None, pm_mode=True):
import json
import os
import inspect
from typing import get_origin, get_args
# Read existing manifest if it exists
manifest = OrderedDict()
if file is not None:
manifestf = os.path.join(os.path.dirname(file), "manifest.json")
if os.path.exists(manifestf):
with open(manifestf, "r") as f:
manifest = json.load(f)
manifestf = os.path.join(os.path.dirname(file), "manifest.yaml")
if os.path.exists(manifestf):
import yaml
with open(manifestf, "r") as f:
manifest = yaml.load(f, Loader=yaml.FullLoader)
# Get function signature and documentation
sig = inspect.signature(func)
doc = func.__doc__
if doc is None:
raise RuntimeError("Could not find documentation in the function...")
argdocs, description, name = _parse_docs(doc)
if "name" not in manifest:
manifest["name"] = name
if "version" not in manifest:
manifest["version"] = "1"
manifest["description"] = description
# Don't add underscore arguments to argparser or args, kwargs
sigargs = []
for argn in sig.parameters:
if not (argn.startswith("_") or argn in ("args", "kwargs")):
sigargs.append(argn)
for argn in sigargs:
if argn not in argdocs:
raise RuntimeError(
f"Could not find help for argument {argn} in the docstring of the function. Please document it."
)
for argn in argdocs:
if argn not in sigargs:
raise RuntimeError(
f"Found docs for argument {argn} in the docstring which is not in the function signature. Please remove it."
)
for argn1, argn2 in zip(sigargs, argdocs):
if argn1 != argn2:
raise RuntimeError(
f"Argument order mismatch between function signature and documentation (need to have same order). {argn1} != {argn2}"
)
arguments = []
for argname in sigargs:
params = sig.parameters[argname]
argtype = params.annotation
nargs = None
# This is needed for compound types like: list[str]
if get_origin(params.annotation) is not None:
origtype = get_origin(params.annotation)
argtype = get_args(params.annotation)[0]
if origtype in (list, tuple):
nargs = "+"
# Override the nargs if specified in the docstring
if "nargs" in argdocs[argname]:
nargs = argdocs[argname]["nargs"]
default = None
if params.default != inspect._empty:
default = params.default
# Don't allow empty list defaults., convert to None
if type(default) in (list, tuple) and len(default) == 0:
raise RuntimeError(
f"Please don't use empty tuples/lists as default arguments (e.g. {argname}=()). Use =None instead"
)
if type(argtype) == tuple:
raise RuntimeError(
f"Failed to get type annotation for argument '{argname}'"
)
if argtype == bool and default:
raise RuntimeError(
"func2argparse does not allow boolean flags with default value True"
)
argument = OrderedDict()
argument["mandatory"] = params.default == inspect._empty
argument["description"] = argdocs[argname]["doc"].strip()
argument["type"] = argtype.__name__
argument["name"] = argname
argument["tag"] = f"--{argname.replace('_', '-')}"
argument["value"] = default
argument["nargs"] = nargs
argument["choices"] = argdocs[argname]["choices"]
if "gui_options" in argdocs[argname]:
argument["gui_options"] = argdocs[argname]["gui_options"]
arguments.append(argument)
manifest["params"] = arguments
# TODO: Deprecate these
if pm_mode:
if "specs" not in manifest:
if (
"resources" in manifest
and "ngpu" in manifest["resources"]
and manifest["resources"]["ngpu"] > 0
):
manifest["specs"] = '{"app": "play1GPU"}'
else:
manifest["specs"] = '{"app": "play0GPU"}'
if "api_version" not in manifest:
manifest["api_version"] = "v1"
if "container" not in manifest:
manifest["container"] = f"{manifest['name']}_v{manifest['version']}"
if "periodicity" not in manifest:
manifest["periodicity"] = 0
return manifest
| (func, file=None, pm_mode=True) |
28,445 | func2argparse | get_manifest | null | def get_manifest(file, parser, pm_mode=True, cwl=False):
import json
import os
if cwl:
return get_manifest_cwl(file, parser)
manifest = OrderedDict()
manifestf = os.path.join(os.path.dirname(file), "manifest.json")
if os.path.exists(manifestf):
with open(manifestf, "r") as f:
manifest = json.load(f)
parserargs = []
parseractions = parser._actions
for action in parseractions:
# skip the hidden arguments, the excluded args and the help argument
if action.help == "==SUPPRESS==" or action.dest in ("help",):
continue
actiondict = OrderedDict()
actiondict["mandatory"] = action.required
actiondict["type"] = action.type.__name__ if action.type is not None else "bool"
actiondict["name"] = action.dest
actiondict["value"] = action.default
actiondict["tag"] = action.option_strings[0]
actiondict["description"] = action.help
actiondict["nargs"] = action.nargs if action.nargs != 0 else None
actiondict["choices"] = action.choices
actiondict["metavar"] = action.metavar
parserargs.append(actiondict)
if "name" not in manifest:
manifest["name"] = parser.prog
if "version" not in manifest:
manifest["version"] = "1"
manifest["description"] = parser.description
manifest["params"] = parserargs
# TODO: Deprecate these
if pm_mode:
if "specs" not in manifest:
if (
"resources" in manifest
and "ngpu" in manifest["resources"]
and manifest["resources"]["ngpu"] > 0
):
manifest["specs"] = '{"app": "play1GPU"}'
else:
manifest["specs"] = '{"app": "play0GPU"}'
if "api_version" not in manifest:
manifest["api_version"] = "v1"
if "container" not in manifest:
manifest["container"] = f"{manifest['name']}_v{manifest['version']}"
if "periodicity" not in manifest:
manifest["periodicity"] = 0
return manifest
| (file, parser, pm_mode=True, cwl=False) |
28,446 | func2argparse | get_manifest_cwl | null | def get_manifest_cwl(file, parser):
import json
import yaml
import os
map_argtypes = {
"str": "string",
"bool": "boolean",
"float": "float",
"int": "int",
"Path": "File",
}
manifest = {"label": parser.prog, "doc": parser.description}
manifest.update({"cwlVersion": "v1.2", "class": "CommandLineTool", "inputs": {}})
manifestf = os.path.join(os.path.dirname(file), "manifest.cwl")
if os.path.exists(manifestf):
with open(manifestf, "r") as f:
manifest.update(yaml.load(f, Loader=yaml.FullLoader))
else:
manifestf = os.path.join(os.path.dirname(file), "manifest.json")
if os.path.exists(manifestf):
with open(manifestf, "r") as f:
manifest.update(json.load(f))
parseractions = parser._actions
for i, action in enumerate(parseractions):
# skip the hidden arguments, the excluded args and the help argument
if action.help == "==SUPPRESS==" or action.dest in ("help",):
continue
argtype = action.type.__name__ if action.type is not None else "bool"
argtype = map_argtypes[argtype]
if action.choices is not None:
enum_name = f"{action.dest.replace('-', '_')}_enum"
if "requirements" not in manifest:
manifest["requirements"] = {}
if "SchemaDefRequirement" not in manifest["requirements"]:
manifest["requirements"]["SchemaDefRequirement"] = {}
if "types" not in manifest["requirements"]["SchemaDefRequirement"]:
manifest["requirements"]["SchemaDefRequirement"]["types"] = []
manifest["requirements"]["SchemaDefRequirement"]["types"].append(
{"type": "enum", "name": enum_name, "symbols": action.choices}
)
argtype = enum_name
if action.nargs:
argtype += "[]"
if not action.required:
argtype += "?"
manifest["inputs"][action.dest] = {
"type": argtype,
"doc": action.help,
"inputBinding": {
"position": i,
"prefix": action.option_strings[0],
},
}
if action.default is not None:
manifest["inputs"][action.dest]["default"] = action.default
return manifest
| (file, parser) |
28,447 | func2argparse | manifest_to_argparser | null | def manifest_to_argparser(
manifest, exit_on_error=True, allow_conf_yaml=False, unmatched_args="error"
):
from pathlib import Path
try:
parser = argparse.ArgumentParser(
manifest["name"],
description=manifest["description"],
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
exit_on_error=exit_on_error,
)
except Exception:
parser = argparse.ArgumentParser(
manifest["name"],
description=manifest["description"],
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
if allow_conf_yaml:
parser.add_argument(
"--conf",
help="Configuration YAML file to set all parameters",
type=open,
action=lambda *x, **y: LoadFromFile(*x, **y, unmatched_args=unmatched_args),
)
# Calculate abbreviations
abbrevs = _get_name_abbreviations([x["name"] for x in manifest["params"]])
type_map = {
"Path": Path,
"bool": bool,
"int": int,
"float": float,
"str": str,
"dict": dict,
}
for param in manifest["params"]:
argname = param["name"]
if param["type"] == "bool":
if param["nargs"] is None:
parser.add_argument(
f"--{argname.replace('_', '-')}",
f"-{abbrevs[argname]}",
help=param["description"],
action="store_true",
)
else:
parser.add_argument(
f"--{argname.replace('_', '-')}",
f"-{abbrevs[argname]}",
help=param["description"],
default=param["value"],
type=str_to_bool,
required=param["mandatory"],
nargs=param["nargs"],
)
else:
if param["type"] in type_map:
param_type = type_map[param["type"]]
else:
print(
f"Warning: Argument {argname} of type {param['type']} could not be mapped to a Python base type and thus will not be type-checked."
)
param_type = None
parser.add_argument(
f"--{argname.replace('_', '-')}",
f"-{abbrevs[argname]}",
help=param["description"],
default=param["value"],
type=param_type,
choices=param["choices"],
required=param["mandatory"],
nargs=param["nargs"],
)
return parser
| (manifest, exit_on_error=True, allow_conf_yaml=False, unmatched_args='error') |
28,448 | func2argparse | str_to_bool | null | def str_to_bool(value):
if isinstance(value, bool):
return value
if value.lower() == "false":
return False
if value.lower() == "true":
return True
raise RuntimeError(f"Invalid boolean value {value}")
| (value) |
28,449 | func2argparse | write_argparser_json | null | def write_argparser_json(outfile, parser):
import json
manifest = get_manifest(outfile, parser, pm_mode=True)
with open(outfile, "w") as f:
json.dump(manifest, f, indent=4)
| (outfile, parser) |
28,457 | matplotlib_venn._venn2 | venn2 | Plots a 2-set area-weighted Venn diagram.
The subsets parameter can be one of the following:
- A list (or a tuple) containing two set objects.
- A dict, providing sizes of three diagram regions.
The regions are identified via two-letter binary codes ('10', '01', and '11'), hence a valid set could look like:
{'10': 10, '01': 20, '11': 40}. Unmentioned codes are considered to map to 0.
- A list (or a tuple) with three numbers, denoting the sizes of the regions in the following order:
(10, 01, 11)
``set_labels`` parameter is a list of two strings - set labels. Set it to None to disable set labels.
The ``set_colors`` parameter should be a list of two elements, specifying the "base colors" of the two circles.
The color of circle intersection will be computed based on those.
The ``normalize_to`` parameter specifies the total (on-axes) area of the circles to be drawn. Sometimes tuning it (together
with the overall fiture size) may be useful to fit the text labels better.
The return value is a ``VennDiagram`` object, that keeps references to the ``Text`` and ``Patch`` objects used on the plot
and lets you know the centers and radii of the circles, if you need it.
The ``ax`` parameter specifies the axes on which the plot will be drawn (None means current axes).
The ``subset_label_formatter`` parameter is a function that can be passed to format the labels
that describe the size of each subset.
>>> from matplotlib_venn import *
>>> v = venn2(subsets={'10': 1, '01': 1, '11': 1}, set_labels = ('A', 'B'))
>>> c = venn2_circles(subsets=(1, 1, 1), linestyle='dashed')
>>> v.get_patch_by_id('10').set_alpha(1.0)
>>> v.get_patch_by_id('10').set_color('white')
>>> v.get_label_by_id('10').set_text('Unknown')
>>> v.get_label_by_id('A').set_text('Set A')
You can provide sets themselves rather than subset sizes:
>>> v = venn2(subsets=[set([1,2]), set([2,3,4,5])], set_labels = ('A', 'B'))
>>> c = venn2_circles(subsets=[set([1,2]), set([2,3,4,5])], linestyle='dashed')
>>> print("%0.2f" % (v.get_circle_radius(1)/v.get_circle_radius(0)))
1.41
| def venn2(subsets, set_labels=('A', 'B'), set_colors=('r', 'g'), alpha=0.4, normalize_to=1.0, ax=None, subset_label_formatter=None):
'''Plots a 2-set area-weighted Venn diagram.
The subsets parameter can be one of the following:
- A list (or a tuple) containing two set objects.
- A dict, providing sizes of three diagram regions.
The regions are identified via two-letter binary codes ('10', '01', and '11'), hence a valid set could look like:
{'10': 10, '01': 20, '11': 40}. Unmentioned codes are considered to map to 0.
- A list (or a tuple) with three numbers, denoting the sizes of the regions in the following order:
(10, 01, 11)
``set_labels`` parameter is a list of two strings - set labels. Set it to None to disable set labels.
The ``set_colors`` parameter should be a list of two elements, specifying the "base colors" of the two circles.
The color of circle intersection will be computed based on those.
The ``normalize_to`` parameter specifies the total (on-axes) area of the circles to be drawn. Sometimes tuning it (together
with the overall fiture size) may be useful to fit the text labels better.
The return value is a ``VennDiagram`` object, that keeps references to the ``Text`` and ``Patch`` objects used on the plot
and lets you know the centers and radii of the circles, if you need it.
The ``ax`` parameter specifies the axes on which the plot will be drawn (None means current axes).
The ``subset_label_formatter`` parameter is a function that can be passed to format the labels
that describe the size of each subset.
>>> from matplotlib_venn import *
>>> v = venn2(subsets={'10': 1, '01': 1, '11': 1}, set_labels = ('A', 'B'))
>>> c = venn2_circles(subsets=(1, 1, 1), linestyle='dashed')
>>> v.get_patch_by_id('10').set_alpha(1.0)
>>> v.get_patch_by_id('10').set_color('white')
>>> v.get_label_by_id('10').set_text('Unknown')
>>> v.get_label_by_id('A').set_text('Set A')
You can provide sets themselves rather than subset sizes:
>>> v = venn2(subsets=[set([1,2]), set([2,3,4,5])], set_labels = ('A', 'B'))
>>> c = venn2_circles(subsets=[set([1,2]), set([2,3,4,5])], linestyle='dashed')
>>> print("%0.2f" % (v.get_circle_radius(1)/v.get_circle_radius(0)))
1.41
'''
if isinstance(subsets, dict):
subsets = [subsets.get(t, 0) for t in ['10', '01', '11']]
elif len(subsets) == 2:
subsets = compute_venn2_subsets(*subsets)
if subset_label_formatter is None:
subset_label_formatter = str
areas = compute_venn2_areas(subsets, normalize_to)
centers, radii = solve_venn2_circles(areas)
regions = compute_venn2_regions(centers, radii)
colors = compute_venn2_colors(set_colors)
if ax is None:
ax = gca()
prepare_venn_axes(ax, centers, radii)
# Create and add patches and subset labels
patches = [r.make_patch() for r in regions]
for (p, c) in zip(patches, colors):
if p is not None:
p.set_facecolor(c)
p.set_edgecolor('none')
p.set_alpha(alpha)
ax.add_patch(p)
label_positions = [r.label_position() for r in regions]
subset_labels = [ax.text(lbl[0], lbl[1], subset_label_formatter(s), va='center', ha='center') if lbl is not None else None for (lbl, s) in zip(label_positions, subsets)]
# Position set labels
if set_labels is not None:
padding = np.mean([r * 0.1 for r in radii])
label_positions = [centers[0] + np.array([0.0, - radii[0] - padding]),
centers[1] + np.array([0.0, - radii[1] - padding])]
labels = [ax.text(pos[0], pos[1], txt, size='large', ha='right', va='top') for (pos, txt) in zip(label_positions, set_labels)]
labels[1].set_ha('left')
else:
labels = None
return VennDiagram(patches, subset_labels, labels, centers, radii)
| (subsets, set_labels=('A', 'B'), set_colors=('r', 'g'), alpha=0.4, normalize_to=1.0, ax=None, subset_label_formatter=None) |
28,458 | matplotlib_venn._venn2 | venn2_circles |
Plots only the two circles for the corresponding Venn diagram.
Useful for debugging or enhancing the basic venn diagram.
parameters ``subsets``, ``normalize_to`` and ``ax`` are the same as in venn2()
``kwargs`` are passed as-is to matplotlib.patches.Circle.
returns a list of three Circle patches.
>>> c = venn2_circles((1, 2, 3))
>>> c = venn2_circles({'10': 1, '01': 2, '11': 3}) # Same effect
>>> c = venn2_circles([set([1,2,3,4]), set([2,3,4,5,6])]) # Also same effect
| def venn2_circles(subsets, normalize_to=1.0, alpha=1.0, color='black', linestyle='solid', linewidth=2.0, ax=None, **kwargs):
'''
Plots only the two circles for the corresponding Venn diagram.
Useful for debugging or enhancing the basic venn diagram.
parameters ``subsets``, ``normalize_to`` and ``ax`` are the same as in venn2()
``kwargs`` are passed as-is to matplotlib.patches.Circle.
returns a list of three Circle patches.
>>> c = venn2_circles((1, 2, 3))
>>> c = venn2_circles({'10': 1, '01': 2, '11': 3}) # Same effect
>>> c = venn2_circles([set([1,2,3,4]), set([2,3,4,5,6])]) # Also same effect
'''
if isinstance(subsets, dict):
subsets = [subsets.get(t, 0) for t in ['10', '01', '11']]
elif len(subsets) == 2:
subsets = compute_venn2_subsets(*subsets)
areas = compute_venn2_areas(subsets, normalize_to)
centers, radii = solve_venn2_circles(areas)
if ax is None:
ax = gca()
prepare_venn_axes(ax, centers, radii)
result = []
for (c, r) in zip(centers, radii):
circle = Circle(c, r, alpha=alpha, edgecolor=color, facecolor='none', linestyle=linestyle, linewidth=linewidth, **kwargs)
ax.add_patch(circle)
result.append(circle)
return result
| (subsets, normalize_to=1.0, alpha=1.0, color='black', linestyle='solid', linewidth=2.0, ax=None, **kwargs) |
28,459 | matplotlib_venn._util | venn2_unweighted |
The version of venn2 without area-weighting.
It is implemented as a wrapper around venn2. Namely, venn2 is invoked as usual, but with all subset areas
set to 1. The subset labels are then replaced in the resulting diagram with the provided subset sizes.
The parameters are all the same as that of venn2.
In addition there is a subset_areas parameter, which specifies the actual subset areas.
(it is (1, 1, 1) by default. You are free to change it, within reason).
| def venn2_unweighted(subsets, set_labels=('A', 'B'), set_colors=('r', 'g'), alpha=0.4, normalize_to=1.0, subset_areas=(1, 1, 1), ax=None, subset_label_formatter=None):
'''
The version of venn2 without area-weighting.
It is implemented as a wrapper around venn2. Namely, venn2 is invoked as usual, but with all subset areas
set to 1. The subset labels are then replaced in the resulting diagram with the provided subset sizes.
The parameters are all the same as that of venn2.
In addition there is a subset_areas parameter, which specifies the actual subset areas.
(it is (1, 1, 1) by default. You are free to change it, within reason).
'''
v = venn2(subset_areas, set_labels, set_colors, alpha, normalize_to, ax)
# Now rename the labels
if subset_label_formatter is None:
subset_label_formatter = str
subset_ids = ['10', '01', '11']
if isinstance(subsets, dict):
subsets = [subsets.get(t, 0) for t in subset_ids]
elif len(subsets) == 2:
subsets = compute_venn2_subsets(*subsets)
for n, id in enumerate(subset_ids):
lbl = v.get_label_by_id(id)
if lbl is not None:
lbl.set_text(subset_label_formatter(subsets[n]))
return v
| (subsets, set_labels=('A', 'B'), set_colors=('r', 'g'), alpha=0.4, normalize_to=1.0, subset_areas=(1, 1, 1), ax=None, subset_label_formatter=None) |
28,460 | matplotlib_venn._venn3 | venn3 | Plots a 3-set area-weighted Venn diagram.
The subsets parameter can be one of the following:
- A list (or a tuple), containing three set objects.
- A dict, providing sizes of seven diagram regions.
The regions are identified via three-letter binary codes ('100', '010', etc), hence a valid set could look like:
{'001': 10, '010': 20, '110':30, ...}. Unmentioned codes are considered to map to 0.
- A list (or a tuple) with 7 numbers, denoting the sizes of the regions in the following order:
(100, 010, 110, 001, 101, 011, 111).
``set_labels`` parameter is a list of three strings - set labels. Set it to None to disable set labels.
The ``set_colors`` parameter should be a list of three elements, specifying the "base colors" of the three circles.
The colors of circle intersections will be computed based on those.
The ``normalize_to`` parameter specifies the total (on-axes) area of the circles to be drawn. Sometimes tuning it (together
with the overall fiture size) may be useful to fit the text labels better.
The return value is a ``VennDiagram`` object, that keeps references to the ``Text`` and ``Patch`` objects used on the plot
and lets you know the centers and radii of the circles, if you need it.
The ``ax`` parameter specifies the axes on which the plot will be drawn (None means current axes).
The ``subset_label_formatter`` parameter is a function that can be passed to format the labels
that describe the size of each subset.
Note: if some of the circles happen to have zero area, you will probably not get a nice picture.
>>> import matplotlib # (The first two lines prevent the doctest from falling when TCL not installed. Not really necessary in most cases)
>>> matplotlib.use('Agg')
>>> from matplotlib_venn import *
>>> v = venn3(subsets=(1, 1, 1, 1, 1, 1, 1), set_labels = ('A', 'B', 'C'))
>>> c = venn3_circles(subsets=(1, 1, 1, 1, 1, 1, 1), linestyle='dashed')
>>> v.get_patch_by_id('100').set_alpha(1.0)
>>> v.get_patch_by_id('100').set_color('white')
>>> v.get_label_by_id('100').set_text('Unknown')
>>> v.get_label_by_id('C').set_text('Set C')
You can provide sets themselves rather than subset sizes:
>>> v = venn3(subsets=[set([1,2]), set([2,3,4,5]), set([4,5,6,7,8,9,10,11])])
>>> print("%0.2f %0.2f %0.2f" % (v.get_circle_radius(0), v.get_circle_radius(1)/v.get_circle_radius(0), v.get_circle_radius(2)/v.get_circle_radius(0)))
0.24 1.41 2.00
>>> c = venn3_circles(subsets=[set([1,2]), set([2,3,4,5]), set([4,5,6,7,8,9,10,11])])
| def venn3(subsets, set_labels=('A', 'B', 'C'), set_colors=('r', 'g', 'b'), alpha=0.4, normalize_to=1.0, ax=None, subset_label_formatter=None):
'''Plots a 3-set area-weighted Venn diagram.
The subsets parameter can be one of the following:
- A list (or a tuple), containing three set objects.
- A dict, providing sizes of seven diagram regions.
The regions are identified via three-letter binary codes ('100', '010', etc), hence a valid set could look like:
{'001': 10, '010': 20, '110':30, ...}. Unmentioned codes are considered to map to 0.
- A list (or a tuple) with 7 numbers, denoting the sizes of the regions in the following order:
(100, 010, 110, 001, 101, 011, 111).
``set_labels`` parameter is a list of three strings - set labels. Set it to None to disable set labels.
The ``set_colors`` parameter should be a list of three elements, specifying the "base colors" of the three circles.
The colors of circle intersections will be computed based on those.
The ``normalize_to`` parameter specifies the total (on-axes) area of the circles to be drawn. Sometimes tuning it (together
with the overall fiture size) may be useful to fit the text labels better.
The return value is a ``VennDiagram`` object, that keeps references to the ``Text`` and ``Patch`` objects used on the plot
and lets you know the centers and radii of the circles, if you need it.
The ``ax`` parameter specifies the axes on which the plot will be drawn (None means current axes).
The ``subset_label_formatter`` parameter is a function that can be passed to format the labels
that describe the size of each subset.
Note: if some of the circles happen to have zero area, you will probably not get a nice picture.
>>> import matplotlib # (The first two lines prevent the doctest from falling when TCL not installed. Not really necessary in most cases)
>>> matplotlib.use('Agg')
>>> from matplotlib_venn import *
>>> v = venn3(subsets=(1, 1, 1, 1, 1, 1, 1), set_labels = ('A', 'B', 'C'))
>>> c = venn3_circles(subsets=(1, 1, 1, 1, 1, 1, 1), linestyle='dashed')
>>> v.get_patch_by_id('100').set_alpha(1.0)
>>> v.get_patch_by_id('100').set_color('white')
>>> v.get_label_by_id('100').set_text('Unknown')
>>> v.get_label_by_id('C').set_text('Set C')
You can provide sets themselves rather than subset sizes:
>>> v = venn3(subsets=[set([1,2]), set([2,3,4,5]), set([4,5,6,7,8,9,10,11])])
>>> print("%0.2f %0.2f %0.2f" % (v.get_circle_radius(0), v.get_circle_radius(1)/v.get_circle_radius(0), v.get_circle_radius(2)/v.get_circle_radius(0)))
0.24 1.41 2.00
>>> c = venn3_circles(subsets=[set([1,2]), set([2,3,4,5]), set([4,5,6,7,8,9,10,11])])
'''
# Prepare parameters
if isinstance(subsets, dict):
subsets = [subsets.get(t, 0) for t in ['100', '010', '110', '001', '101', '011', '111']]
elif len(subsets) == 3:
subsets = compute_venn3_subsets(*subsets)
if subset_label_formatter is None:
subset_label_formatter = str
areas = compute_venn3_areas(subsets, normalize_to)
centers, radii = solve_venn3_circles(areas)
regions = compute_venn3_regions(centers, radii)
colors = compute_venn3_colors(set_colors)
# Remove regions that are too small from the diagram
MIN_REGION_SIZE = 1e-4
for i in range(len(regions)):
if regions[i].size() < MIN_REGION_SIZE and subsets[i] == 0:
regions[i] = VennEmptyRegion()
# There is a rare case (Issue #12) when the middle region is visually empty
# (the positioning of the circles does not let them intersect), yet the corresponding value is not 0.
# we address it separately here by positioning the label of that empty region in a custom way
if isinstance(regions[6], VennEmptyRegion) and subsets[6] > 0:
intersections = [circle_circle_intersection(centers[i], radii[i], centers[j], radii[j]) for (i, j) in [(0, 1), (1, 2), (2, 0)]]
middle_pos = np.mean([i[0] for i in intersections], 0)
regions[6] = VennEmptyRegion(middle_pos)
if ax is None:
ax = gca()
prepare_venn_axes(ax, centers, radii)
# Create and add patches and text
patches = [r.make_patch() for r in regions]
for (p, c) in zip(patches, colors):
if p is not None:
p.set_facecolor(c)
p.set_edgecolor('none')
p.set_alpha(alpha)
ax.add_patch(p)
label_positions = [r.label_position() for r in regions]
subset_labels = [ax.text(lbl[0], lbl[1], subset_label_formatter(s), va='center', ha='center') if lbl is not None else None for (lbl, s) in zip(label_positions, subsets)]
# Position labels
if set_labels is not None:
# There are two situations, when set C is not on the same line with sets A and B, and when the three are on the same line.
if abs(centers[2][1] - centers[0][1]) > tol:
# Three circles NOT on the same line
label_positions = [centers[0] + np.array([-radii[0] / 2, radii[0]]),
centers[1] + np.array([radii[1] / 2, radii[1]]),
centers[2] + np.array([0.0, -radii[2] * 1.1])]
labels = [ax.text(pos[0], pos[1], txt, size='large') for (pos, txt) in zip(label_positions, set_labels)]
labels[0].set_horizontalalignment('right')
labels[1].set_horizontalalignment('left')
labels[2].set_verticalalignment('top')
labels[2].set_horizontalalignment('center')
else:
padding = np.mean([r * 0.1 for r in radii])
# Three circles on the same line
label_positions = [centers[0] + np.array([0.0, - radii[0] - padding]),
centers[1] + np.array([0.0, - radii[1] - padding]),
centers[2] + np.array([0.0, - radii[2] - padding])]
labels = [ax.text(pos[0], pos[1], txt, size='large', ha='center', va='top') for (pos, txt) in zip(label_positions, set_labels)]
else:
labels = None
return VennDiagram(patches, subset_labels, labels, centers, radii)
| (subsets, set_labels=('A', 'B', 'C'), set_colors=('r', 'g', 'b'), alpha=0.4, normalize_to=1.0, ax=None, subset_label_formatter=None) |
28,461 | matplotlib_venn._venn3 | venn3_circles |
Plots only the three circles for the corresponding Venn diagram.
Useful for debugging or enhancing the basic venn diagram.
parameters ``subsets``, ``normalize_to`` and ``ax`` are the same as in venn3()
kwargs are passed as-is to matplotlib.patches.Circle.
returns a list of three Circle patches.
>>> plot = venn3_circles({'001': 10, '100': 20, '010': 21, '110': 13, '011': 14})
>>> plot = venn3_circles([set(['A','B','C']), set(['A','D','E','F']), set(['D','G','H'])])
| def venn3_circles(subsets, normalize_to=1.0, alpha=1.0, color='black', linestyle='solid', linewidth=2.0, ax=None, **kwargs):
'''
Plots only the three circles for the corresponding Venn diagram.
Useful for debugging or enhancing the basic venn diagram.
parameters ``subsets``, ``normalize_to`` and ``ax`` are the same as in venn3()
kwargs are passed as-is to matplotlib.patches.Circle.
returns a list of three Circle patches.
>>> plot = venn3_circles({'001': 10, '100': 20, '010': 21, '110': 13, '011': 14})
>>> plot = venn3_circles([set(['A','B','C']), set(['A','D','E','F']), set(['D','G','H'])])
'''
# Prepare parameters
if isinstance(subsets, dict):
subsets = [subsets.get(t, 0) for t in ['100', '010', '110', '001', '101', '011', '111']]
elif len(subsets) == 3:
subsets = compute_venn3_subsets(*subsets)
areas = compute_venn3_areas(subsets, normalize_to)
centers, radii = solve_venn3_circles(areas)
if ax is None:
ax = gca()
prepare_venn_axes(ax, centers, radii)
result = []
for (c, r) in zip(centers, radii):
circle = Circle(c, r, alpha=alpha, edgecolor=color, facecolor='none', linestyle=linestyle, linewidth=linewidth, **kwargs)
ax.add_patch(circle)
result.append(circle)
return result
| (subsets, normalize_to=1.0, alpha=1.0, color='black', linestyle='solid', linewidth=2.0, ax=None, **kwargs) |
28,462 | matplotlib_venn._util | venn3_unweighted |
The version of venn3 without area-weighting.
It is implemented as a wrapper around venn3. Namely, venn3 is invoked as usual, but with all subset areas
set to 1. The subset labels are then replaced in the resulting diagram with the provided subset sizes.
The parameters are all the same as that of venn2.
In addition there is a subset_areas parameter, which specifies the actual subset areas.
(it is (1, 1, 1, 1, 1, 1, 1) by default. You are free to change it, within reason).
| def venn3_unweighted(subsets, set_labels=('A', 'B', 'C'), set_colors=('r', 'g', 'b'), alpha=0.4, normalize_to=1.0, subset_areas=(1, 1, 1, 1, 1, 1, 1), ax=None, subset_label_formatter=None):
'''
The version of venn3 without area-weighting.
It is implemented as a wrapper around venn3. Namely, venn3 is invoked as usual, but with all subset areas
set to 1. The subset labels are then replaced in the resulting diagram with the provided subset sizes.
The parameters are all the same as that of venn2.
In addition there is a subset_areas parameter, which specifies the actual subset areas.
(it is (1, 1, 1, 1, 1, 1, 1) by default. You are free to change it, within reason).
'''
v = venn3(subset_areas, set_labels, set_colors, alpha, normalize_to, ax)
# Now rename the labels
if subset_label_formatter is None:
subset_label_formatter = str
subset_ids = ['100', '010', '110', '001', '101', '011', '111']
if isinstance(subsets, dict):
subsets = [subsets.get(t, 0) for t in subset_ids]
elif len(subsets) == 3:
subsets = compute_venn3_subsets(*subsets)
for n, id in enumerate(subset_ids):
lbl = v.get_label_by_id(id)
if lbl is not None:
lbl.set_text(subset_label_formatter(subsets[n]))
return v
| (subsets, set_labels=('A', 'B', 'C'), set_colors=('r', 'g', 'b'), alpha=0.4, normalize_to=1.0, subset_areas=(1, 1, 1, 1, 1, 1, 1), ax=None, subset_label_formatter=None) |
28,463 | ometa.runtime | EOFError |
Raised when the end of input is encountered.
| class EOFError(ParseError):
"""
Raised when the end of input is encountered.
"""
def __init__(self, input, position):
ParseError.__init__(self, input, position, eof())
| (input, position) |
28,464 | ometa.runtime | __eq__ | null | def __eq__(self, other):
if other.__class__ == self.__class__:
return (self.position, self.error) == (other.position, other.error)
| (self, other) |
28,465 | ometa.runtime | __init__ | null | def __init__(self, input, position):
ParseError.__init__(self, input, position, eof())
| (self, input, position) |
28,466 | ometa.runtime | __str__ | null | def __str__(self):
return self.formatError()
| (self) |
28,467 | ometa.runtime | formatError |
Return a pretty string containing error info about string
parsing failure.
| def formatError(self):
"""
Return a pretty string containing error info about string
parsing failure.
"""
#de-twineifying
lines = str(self.input).split('\n')
counter = 0
lineNo = 1
columnNo = 0
for line in lines:
newCounter = counter + len(line)
if newCounter > self.position:
columnNo = self.position - counter
break
else:
counter += len(line) + 1
lineNo += 1
reason = self.formatReason()
return ('\n' + line + '\n' + (' ' * columnNo + '^') +
"\nParse error at line %s, column %s: %s. trail: [%s]\n"
% (lineNo, columnNo, reason, ' '.join(self.trail)))
| (self) |
28,468 | ometa.runtime | formatReason | null | def formatReason(self):
if not self.error:
return "Syntax error"
if len(self.error) == 1:
if self.error[0][0] == 'message':
return self.error[0][1]
if self.error[0][2] == None:
return 'expected a %s' % (self.error[0][1])
else:
typ = self.error[0][1]
if typ is None:
if isinstance(self.input, basestring):
typ = 'character'
else:
typ = 'object'
return 'expected the %s %r' % (typ, self.error[0][2])
else:
bits = []
for s in self.error:
if s[0] == 'message':
desc = s[1]
elif s[2] is None:
desc = "a " + s[1]
else:
desc = repr(s[2])
if s[1] is not None:
desc = "%s %s" % (s[1], desc)
bits.append(desc)
bits.sort()
return "expected one of %s, or %s" % (', '.join(bits[:-1]),
bits[-1])
| (self) |
28,469 | ometa.runtime | mergeWith |
Merges in another error's error and trail.
| def mergeWith(self, other):
"""
Merges in another error's error and trail.
"""
self.error = list(set(self.error + other.error))
self.args = (self.position, self.error)
self.trail = other.trail or self.trail or []
| (self, other) |
28,470 | ometa.runtime | withMessage | null | def withMessage(self, msg):
return ParseError(self.input, self.position, msg, self.trail)
| (self, msg) |
28,471 | ometa._generated.parsley | parsley | null | def createParserClass(GrammarBase, ruleGlobals):
if ruleGlobals is None:
ruleGlobals = {}
class parsley(GrammarBase):
def rule_comment(self):
_locals = {'self': self}
self.locals['comment'] = _locals
self._trace(" '#'", (9, 13), self.input.position)
_G_exactly_1, lastError = self.exactly('#')
self.considerError(lastError, 'comment')
def _G_many_2():
def _G_not_3():
self._trace("'\\n'", (16, 20), self.input.position)
_G_exactly_4, lastError = self.exactly('\n')
self.considerError(lastError, None)
return (_G_exactly_4, self.currentError)
_G_not_5, lastError = self._not(_G_not_3)
self.considerError(lastError, None)
self._trace(' anything', (20, 29), self.input.position)
_G_apply_6, lastError = self._apply(self.rule_anything, "anything", [])
self.considerError(lastError, None)
return (_G_apply_6, self.currentError)
_G_many_7, lastError = self.many(_G_many_2)
self.considerError(lastError, 'comment')
return (_G_many_7, self.currentError)
def rule_hspace(self):
_locals = {'self': self}
self.locals['hspace'] = _locals
def _G_or_8():
self._trace(" ' '", (40, 44), self.input.position)
_G_exactly_9, lastError = self.exactly(' ')
self.considerError(lastError, None)
return (_G_exactly_9, self.currentError)
def _G_or_10():
self._trace(" '\\t'", (46, 51), self.input.position)
_G_exactly_11, lastError = self.exactly('\t')
self.considerError(lastError, None)
return (_G_exactly_11, self.currentError)
def _G_or_12():
self._trace(' comment', (53, 61), self.input.position)
_G_apply_13, lastError = self._apply(self.rule_comment, "comment", [])
self.considerError(lastError, None)
return (_G_apply_13, self.currentError)
_G_or_14, lastError = self._or([_G_or_8, _G_or_10, _G_or_12])
self.considerError(lastError, 'hspace')
return (_G_or_14, self.currentError)
def rule_vspace(self):
_locals = {'self': self}
self.locals['vspace'] = _locals
def _G_or_15():
self._trace(" '\\r\\n'", (70, 78), self.input.position)
_G_exactly_16, lastError = self.exactly('\r\n')
self.considerError(lastError, None)
return (_G_exactly_16, self.currentError)
def _G_or_17():
self._trace(" '\\r'", (80, 85), self.input.position)
_G_exactly_18, lastError = self.exactly('\r')
self.considerError(lastError, None)
return (_G_exactly_18, self.currentError)
def _G_or_19():
self._trace(" '\\n'", (87, 92), self.input.position)
_G_exactly_20, lastError = self.exactly('\n')
self.considerError(lastError, None)
return (_G_exactly_20, self.currentError)
_G_or_21, lastError = self._or([_G_or_15, _G_or_17, _G_or_19])
self.considerError(lastError, 'vspace')
return (_G_or_21, self.currentError)
def rule_ws(self):
_locals = {'self': self}
self.locals['ws'] = _locals
def _G_many_22():
def _G_or_23():
self._trace('hspace', (99, 105), self.input.position)
_G_apply_24, lastError = self._apply(self.rule_hspace, "hspace", [])
self.considerError(lastError, None)
return (_G_apply_24, self.currentError)
def _G_or_25():
self._trace(' vspace', (107, 114), self.input.position)
_G_apply_26, lastError = self._apply(self.rule_vspace, "vspace", [])
self.considerError(lastError, None)
return (_G_apply_26, self.currentError)
def _G_or_27():
self._trace(' comment', (116, 124), self.input.position)
_G_apply_28, lastError = self._apply(self.rule_comment, "comment", [])
self.considerError(lastError, None)
return (_G_apply_28, self.currentError)
_G_or_29, lastError = self._or([_G_or_23, _G_or_25, _G_or_27])
self.considerError(lastError, None)
return (_G_or_29, self.currentError)
_G_many_30, lastError = self.many(_G_many_22)
self.considerError(lastError, 'ws')
return (_G_many_30, self.currentError)
def rule_emptyline(self):
_locals = {'self': self}
self.locals['emptyline'] = _locals
def _G_many_31():
self._trace(' hspace', (139, 146), self.input.position)
_G_apply_32, lastError = self._apply(self.rule_hspace, "hspace", [])
self.considerError(lastError, None)
return (_G_apply_32, self.currentError)
_G_many_33, lastError = self.many(_G_many_31)
self.considerError(lastError, 'emptyline')
self._trace(' vspace', (147, 154), self.input.position)
_G_apply_34, lastError = self._apply(self.rule_vspace, "vspace", [])
self.considerError(lastError, 'emptyline')
return (_G_apply_34, self.currentError)
def rule_indentation(self):
_locals = {'self': self}
self.locals['indentation'] = _locals
def _G_many_35():
self._trace(' emptyline', (168, 178), self.input.position)
_G_apply_36, lastError = self._apply(self.rule_emptyline, "emptyline", [])
self.considerError(lastError, None)
return (_G_apply_36, self.currentError)
_G_many_37, lastError = self.many(_G_many_35)
self.considerError(lastError, 'indentation')
def _G_many1_38():
self._trace(' hspace', (179, 186), self.input.position)
_G_apply_39, lastError = self._apply(self.rule_hspace, "hspace", [])
self.considerError(lastError, None)
return (_G_apply_39, self.currentError)
_G_many1_40, lastError = self.many(_G_many1_38, _G_many1_38())
self.considerError(lastError, 'indentation')
return (_G_many1_40, self.currentError)
def rule_noindentation(self):
_locals = {'self': self}
self.locals['noindentation'] = _locals
def _G_many_41():
self._trace(' emptyline', (203, 213), self.input.position)
_G_apply_42, lastError = self._apply(self.rule_emptyline, "emptyline", [])
self.considerError(lastError, None)
return (_G_apply_42, self.currentError)
_G_many_43, lastError = self.many(_G_many_41)
self.considerError(lastError, 'noindentation')
def _G_lookahead_44():
def _G_not_45():
self._trace('hspace', (218, 224), self.input.position)
_G_apply_46, lastError = self._apply(self.rule_hspace, "hspace", [])
self.considerError(lastError, None)
return (_G_apply_46, self.currentError)
_G_not_47, lastError = self._not(_G_not_45)
self.considerError(lastError, None)
return (_G_not_47, self.currentError)
_G_lookahead_48, lastError = self.lookahead(_G_lookahead_44)
self.considerError(lastError, 'noindentation')
return (_G_lookahead_48, self.currentError)
def rule_number(self):
_locals = {'self': self}
self.locals['number'] = _locals
self._trace(' ws', (234, 237), self.input.position)
_G_apply_49, lastError = self._apply(self.rule_ws, "ws", [])
self.considerError(lastError, 'number')
def _G_or_50():
self._trace("'-'", (254, 257), self.input.position)
_G_exactly_51, lastError = self.exactly('-')
self.considerError(lastError, None)
self._trace(' barenumber', (257, 268), self.input.position)
_G_apply_52, lastError = self._apply(self.rule_barenumber, "barenumber", [])
self.considerError(lastError, None)
_locals['x'] = _G_apply_52
_G_python_53, lastError = eval('t.Exactly(-x, span=self.getSpan())', self.globals, _locals), None
self.considerError(lastError, None)
return (_G_python_53, self.currentError)
def _G_or_54():
self._trace('barenumber', (331, 341), self.input.position)
_G_apply_55, lastError = self._apply(self.rule_barenumber, "barenumber", [])
self.considerError(lastError, None)
_locals['x'] = _G_apply_55
_G_python_56, lastError = eval('t.Exactly(x, span=self.getSpan())', self.globals, _locals), None
self.considerError(lastError, None)
return (_G_python_56, self.currentError)
_G_or_57, lastError = self._or([_G_or_50, _G_or_54])
self.considerError(lastError, 'number')
return (_G_or_57, self.currentError)
def rule_barenumber(self):
_locals = {'self': self}
self.locals['barenumber'] = _locals
def _G_or_58():
self._trace(" '0'", (394, 398), self.input.position)
_G_exactly_59, lastError = self.exactly('0')
self.considerError(lastError, None)
def _G_or_60():
def _G_or_61():
self._trace("'x'", (401, 404), self.input.position)
_G_exactly_62, lastError = self.exactly('x')
self.considerError(lastError, None)
return (_G_exactly_62, self.currentError)
def _G_or_63():
self._trace("'X'", (405, 408), self.input.position)
_G_exactly_64, lastError = self.exactly('X')
self.considerError(lastError, None)
return (_G_exactly_64, self.currentError)
_G_or_65, lastError = self._or([_G_or_61, _G_or_63])
self.considerError(lastError, None)
def _G_consumedby_66():
def _G_many1_67():
self._trace('hexdigit', (411, 419), self.input.position)
_G_apply_68, lastError = self._apply(self.rule_hexdigit, "hexdigit", [])
self.considerError(lastError, None)
return (_G_apply_68, self.currentError)
_G_many1_69, lastError = self.many(_G_many1_67, _G_many1_67())
self.considerError(lastError, None)
return (_G_many1_69, self.currentError)
_G_consumedby_70, lastError = self.consumedby(_G_consumedby_66)
self.considerError(lastError, None)
_locals['hs'] = _G_consumedby_70
_G_python_71, lastError = eval('int(hs, 16)', self.globals, _locals), None
self.considerError(lastError, None)
return (_G_python_71, self.currentError)
def _G_or_72():
def _G_consumedby_73():
def _G_many1_74():
self._trace('octaldigit', (462, 472), self.input.position)
_G_apply_75, lastError = self._apply(self.rule_octaldigit, "octaldigit", [])
self.considerError(lastError, None)
return (_G_apply_75, self.currentError)
_G_many1_76, lastError = self.many(_G_many1_74, _G_many1_74())
self.considerError(lastError, None)
return (_G_many1_76, self.currentError)
_G_consumedby_77, lastError = self.consumedby(_G_consumedby_73)
self.considerError(lastError, None)
_locals['ds'] = _G_consumedby_77
_G_python_78, lastError = eval('int(ds, 8)', self.globals, _locals), None
self.considerError(lastError, None)
return (_G_python_78, self.currentError)
_G_or_79, lastError = self._or([_G_or_60, _G_or_72])
self.considerError(lastError, None)
return (_G_or_79, self.currentError)
def _G_or_80():
def _G_consumedby_81():
def _G_many1_82():
self._trace('digit', (510, 515), self.input.position)
_G_apply_83, lastError = self._apply(self.rule_digit, "digit", [])
self.considerError(lastError, None)
return (_G_apply_83, self.currentError)
_G_many1_84, lastError = self.many(_G_many1_82, _G_many1_82())
self.considerError(lastError, None)
return (_G_many1_84, self.currentError)
_G_consumedby_85, lastError = self.consumedby(_G_consumedby_81)
self.considerError(lastError, None)
_locals['ds'] = _G_consumedby_85
_G_python_86, lastError = eval('int(ds)', self.globals, _locals), None
self.considerError(lastError, None)
return (_G_python_86, self.currentError)
_G_or_87, lastError = self._or([_G_or_58, _G_or_80])
self.considerError(lastError, 'barenumber')
return (_G_or_87, self.currentError)
def rule_octaldigit(self):
_locals = {'self': self}
self.locals['octaldigit'] = _locals
_G_apply_88, lastError = self._apply(self.rule_anything, "anything", [])
self.considerError(lastError, 'octaldigit')
_locals['x'] = _G_apply_88
def _G_pred_89():
_G_python_90, lastError = eval("x in '01234567'", self.globals, _locals), None
self.considerError(lastError, None)
return (_G_python_90, self.currentError)
_G_pred_91, lastError = self.pred(_G_pred_89)
self.considerError(lastError, 'octaldigit')
_G_python_92, lastError = eval('x', self.globals, _locals), None
self.considerError(lastError, 'octaldigit')
return (_G_python_92, self.currentError)
def rule_hexdigit(self):
_locals = {'self': self}
self.locals['hexdigit'] = _locals
_G_apply_93, lastError = self._apply(self.rule_anything, "anything", [])
self.considerError(lastError, 'hexdigit')
_locals['x'] = _G_apply_93
def _G_pred_94():
_G_python_95, lastError = eval("x in '0123456789ABCDEFabcdef'", self.globals, _locals), None
self.considerError(lastError, None)
return (_G_python_95, self.currentError)
_G_pred_96, lastError = self.pred(_G_pred_94)
self.considerError(lastError, 'hexdigit')
_G_python_97, lastError = eval('x', self.globals, _locals), None
self.considerError(lastError, 'hexdigit')
return (_G_python_97, self.currentError)
def rule_escapedChar(self):
_locals = {'self': self}
self.locals['escapedChar'] = _locals
self._trace(" '\\\\'", (639, 644), self.input.position)
_G_exactly_98, lastError = self.exactly('\\')
self.considerError(lastError, 'escapedChar')
def _G_or_99():
self._trace("'n'", (646, 649), self.input.position)
_G_exactly_100, lastError = self.exactly('n')
self.considerError(lastError, None)
_G_python_101, lastError = ("\n"), None
self.considerError(lastError, None)
return (_G_python_101, self.currentError)
def _G_or_102():
self._trace("'r'", (680, 683), self.input.position)
_G_exactly_103, lastError = self.exactly('r')
self.considerError(lastError, None)
_G_python_104, lastError = ("\r"), None
self.considerError(lastError, None)
return (_G_python_104, self.currentError)
def _G_or_105():
self._trace("'t'", (714, 717), self.input.position)
_G_exactly_106, lastError = self.exactly('t')
self.considerError(lastError, None)
_G_python_107, lastError = ("\t"), None
self.considerError(lastError, None)
return (_G_python_107, self.currentError)
def _G_or_108():
self._trace("'b'", (748, 751), self.input.position)
_G_exactly_109, lastError = self.exactly('b')
self.considerError(lastError, None)
_G_python_110, lastError = ("\b"), None
self.considerError(lastError, None)
return (_G_python_110, self.currentError)
def _G_or_111():
self._trace("'f'", (782, 785), self.input.position)
_G_exactly_112, lastError = self.exactly('f')
self.considerError(lastError, None)
_G_python_113, lastError = ("\f"), None
self.considerError(lastError, None)
return (_G_python_113, self.currentError)
def _G_or_114():
self._trace('\'"\'', (816, 819), self.input.position)
_G_exactly_115, lastError = self.exactly('"')
self.considerError(lastError, None)
_G_python_116, lastError = ('"'), None
self.considerError(lastError, None)
return (_G_python_116, self.currentError)
def _G_or_117():
self._trace("'\\''", (849, 853), self.input.position)
_G_exactly_118, lastError = self.exactly("'")
self.considerError(lastError, None)
_G_python_119, lastError = ("'"), None
self.considerError(lastError, None)
return (_G_python_119, self.currentError)
def _G_or_120():
self._trace("'x'", (883, 886), self.input.position)
_G_exactly_121, lastError = self.exactly('x')
self.considerError(lastError, None)
def _G_consumedby_122():
self._trace('hexdigit', (888, 896), self.input.position)
_G_apply_123, lastError = self._apply(self.rule_hexdigit, "hexdigit", [])
self.considerError(lastError, None)
self._trace(' hexdigit', (896, 905), self.input.position)
_G_apply_124, lastError = self._apply(self.rule_hexdigit, "hexdigit", [])
self.considerError(lastError, None)
return (_G_apply_124, self.currentError)
_G_consumedby_125, lastError = self.consumedby(_G_consumedby_122)
self.considerError(lastError, None)
_locals['d'] = _G_consumedby_125
_G_python_126, lastError = eval('chr(int(d, 16))', self.globals, _locals), None
self.considerError(lastError, None)
return (_G_python_126, self.currentError)
def _G_or_127():
self._trace("'\\\\'", (950, 954), self.input.position)
_G_exactly_128, lastError = self.exactly('\\')
self.considerError(lastError, None)
_G_python_129, lastError = ("\\"), None
self.considerError(lastError, None)
return (_G_python_129, self.currentError)
_G_or_130, lastError = self._or([_G_or_99, _G_or_102, _G_or_105, _G_or_108, _G_or_111, _G_or_114, _G_or_117, _G_or_120, _G_or_127])
self.considerError(lastError, 'escapedChar')
return (_G_or_130, self.currentError)
def rule_character(self):
_locals = {'self': self}
self.locals['character'] = _locals
self._trace(' ws', (976, 979), self.input.position)
_G_apply_131, lastError = self._apply(self.rule_ws, "ws", [])
self.considerError(lastError, 'character')
self._trace(" '\\''", (979, 984), self.input.position)
_G_exactly_132, lastError = self.exactly("'")
self.considerError(lastError, 'character')
def _G_many1_133():
def _G_not_134():
self._trace("'\\''", (987, 991), self.input.position)
_G_exactly_135, lastError = self.exactly("'")
self.considerError(lastError, None)
return (_G_exactly_135, self.currentError)
_G_not_136, lastError = self._not(_G_not_134)
self.considerError(lastError, None)
def _G_or_137():
self._trace('escapedChar', (993, 1004), self.input.position)
_G_apply_138, lastError = self._apply(self.rule_escapedChar, "escapedChar", [])
self.considerError(lastError, None)
return (_G_apply_138, self.currentError)
def _G_or_139():
self._trace(' anything', (1006, 1015), self.input.position)
_G_apply_140, lastError = self._apply(self.rule_anything, "anything", [])
self.considerError(lastError, None)
return (_G_apply_140, self.currentError)
_G_or_141, lastError = self._or([_G_or_137, _G_or_139])
self.considerError(lastError, None)
return (_G_or_141, self.currentError)
_G_many1_142, lastError = self.many(_G_many1_133, _G_many1_133())
self.considerError(lastError, 'character')
_locals['c'] = _G_many1_142
self._trace('\n ws', (1020, 1035), self.input.position)
_G_apply_143, lastError = self._apply(self.rule_ws, "ws", [])
self.considerError(lastError, 'character')
self._trace(" '\\''", (1035, 1040), self.input.position)
_G_exactly_144, lastError = self.exactly("'")
self.considerError(lastError, 'character')
_G_python_145, lastError = eval("t.Exactly(''.join(c), span=self.getSpan())", self.globals, _locals), None
self.considerError(lastError, 'character')
return (_G_python_145, self.currentError)
def rule_string(self):
_locals = {'self': self}
self.locals['string'] = _locals
self._trace(' ws', (1096, 1099), self.input.position)
_G_apply_146, lastError = self._apply(self.rule_ws, "ws", [])
self.considerError(lastError, 'string')
self._trace(' \'"\'', (1099, 1103), self.input.position)
_G_exactly_147, lastError = self.exactly('"')
self.considerError(lastError, 'string')
def _G_many_148():
def _G_or_149():
self._trace('escapedChar', (1105, 1116), self.input.position)
_G_apply_150, lastError = self._apply(self.rule_escapedChar, "escapedChar", [])
self.considerError(lastError, None)
return (_G_apply_150, self.currentError)
def _G_or_151():
def _G_not_152():
self._trace('\'"\'', (1121, 1124), self.input.position)
_G_exactly_153, lastError = self.exactly('"')
self.considerError(lastError, None)
return (_G_exactly_153, self.currentError)
_G_not_154, lastError = self._not(_G_not_152)
self.considerError(lastError, None)
self._trace(' anything', (1125, 1134), self.input.position)
_G_apply_155, lastError = self._apply(self.rule_anything, "anything", [])
self.considerError(lastError, None)
return (_G_apply_155, self.currentError)
_G_or_156, lastError = self._or([_G_or_149, _G_or_151])
self.considerError(lastError, None)
return (_G_or_156, self.currentError)
_G_many_157, lastError = self.many(_G_many_148)
self.considerError(lastError, 'string')
_locals['c'] = _G_many_157
self._trace('\n ws', (1138, 1150), self.input.position)
_G_apply_158, lastError = self._apply(self.rule_ws, "ws", [])
self.considerError(lastError, 'string')
self._trace(' \'"\'', (1150, 1154), self.input.position)
_G_exactly_159, lastError = self.exactly('"')
self.considerError(lastError, 'string')
_G_python_160, lastError = eval("t.Token(''.join(c), span=self.getSpan())", self.globals, _locals), None
self.considerError(lastError, 'string')
return (_G_python_160, self.currentError)
def rule_name(self):
_locals = {'self': self}
self.locals['name'] = _locals
def _G_consumedby_161():
self._trace('letter', (1208, 1214), self.input.position)
_G_apply_162, lastError = self._apply(self.rule_letter, "letter", [])
self.considerError(lastError, None)
def _G_many_163():
def _G_or_164():
self._trace("'_'", (1216, 1219), self.input.position)
_G_exactly_165, lastError = self.exactly('_')
self.considerError(lastError, None)
return (_G_exactly_165, self.currentError)
def _G_or_166():
self._trace('letterOrDigit', (1221, 1234), self.input.position)
_G_apply_167, lastError = self._apply(self.rule_letterOrDigit, "letterOrDigit", [])
self.considerError(lastError, None)
return (_G_apply_167, self.currentError)
_G_or_168, lastError = self._or([_G_or_164, _G_or_166])
self.considerError(lastError, None)
return (_G_or_168, self.currentError)
_G_many_169, lastError = self.many(_G_many_163)
self.considerError(lastError, None)
return (_G_many_169, self.currentError)
_G_consumedby_170, lastError = self.consumedby(_G_consumedby_161)
self.considerError(lastError, 'name')
return (_G_consumedby_170, self.currentError)
def rule_args(self):
_locals = {'self': self}
self.locals['args'] = _locals
def _G_or_171():
self._trace("'('", (1247, 1250), self.input.position)
_G_exactly_172, lastError = self.exactly('(')
self.considerError(lastError, None)
_G_python_173, lastError = eval("self.applicationArgs(finalChar=')')", self.globals, _locals), None
self.considerError(lastError, None)
_locals['args'] = _G_python_173
self._trace(" ')'", (1294, 1298), self.input.position)
_G_exactly_174, lastError = self.exactly(')')
self.considerError(lastError, None)
_G_python_175, lastError = eval('args', self.globals, _locals), None
self.considerError(lastError, None)
return (_G_python_175, self.currentError)
def _G_or_176():
_G_python_177, lastError = ([]), None
self.considerError(lastError, None)
return (_G_python_177, self.currentError)
_G_or_178, lastError = self._or([_G_or_171, _G_or_176])
self.considerError(lastError, 'args')
return (_G_or_178, self.currentError)
def rule_application(self):
_locals = {'self': self}
self.locals['application'] = _locals
def _G_optional_179():
self._trace(' indentation', (1352, 1364), self.input.position)
_G_apply_180, lastError = self._apply(self.rule_indentation, "indentation", [])
self.considerError(lastError, None)
return (_G_apply_180, self.currentError)
def _G_optional_181():
return (None, self.input.nullError())
_G_or_182, lastError = self._or([_G_optional_179, _G_optional_181])
self.considerError(lastError, 'application')
self._trace(' name', (1365, 1370), self.input.position)
_G_apply_183, lastError = self._apply(self.rule_name, "name", [])
self.considerError(lastError, 'application')
_locals['name'] = _G_apply_183
self._trace(' args', (1375, 1380), self.input.position)
_G_apply_184, lastError = self._apply(self.rule_args, "args", [])
self.considerError(lastError, 'application')
_locals['args'] = _G_apply_184
_G_python_185, lastError = eval('t.Apply(name, self.rulename, args, span=self.getSpan())', self.globals, _locals), None
self.considerError(lastError, 'application')
return (_G_python_185, self.currentError)
def rule_foreignApply(self):
_locals = {'self': self}
self.locals['foreignApply'] = _locals
def _G_optional_186():
self._trace(' indentation', (1476, 1488), self.input.position)
_G_apply_187, lastError = self._apply(self.rule_indentation, "indentation", [])
self.considerError(lastError, None)
return (_G_apply_187, self.currentError)
def _G_optional_188():
return (None, self.input.nullError())
_G_or_189, lastError = self._or([_G_optional_186, _G_optional_188])
self.considerError(lastError, 'foreignApply')
self._trace(' name', (1489, 1494), self.input.position)
_G_apply_190, lastError = self._apply(self.rule_name, "name", [])
self.considerError(lastError, 'foreignApply')
_locals['grammar_name'] = _G_apply_190
self._trace(" '.'", (1507, 1511), self.input.position)
_G_exactly_191, lastError = self.exactly('.')
self.considerError(lastError, 'foreignApply')
self._trace(' name', (1511, 1516), self.input.position)
_G_apply_192, lastError = self._apply(self.rule_name, "name", [])
self.considerError(lastError, 'foreignApply')
_locals['rule_name'] = _G_apply_192
self._trace(' args', (1526, 1531), self.input.position)
_G_apply_193, lastError = self._apply(self.rule_args, "args", [])
self.considerError(lastError, 'foreignApply')
_locals['args'] = _G_apply_193
_G_python_194, lastError = eval('t.ForeignApply(grammar_name, rule_name, self.rulename, args, span=self.getSpan())', self.globals, _locals), None
self.considerError(lastError, 'foreignApply')
return (_G_python_194, self.currentError)
def rule_traceable(self):
_locals = {'self': self}
self.locals['traceable'] = _locals
_G_python_195, lastError = eval('self.startSpan()', self.globals, _locals), None
self.considerError(lastError, 'traceable')
def _G_or_196():
self._trace(' foreignApply', (1682, 1696), self.input.position)
_G_apply_197, lastError = self._apply(self.rule_foreignApply, "foreignApply", [])
self.considerError(lastError, None)
return (_G_apply_197, self.currentError)
def _G_or_198():
self._trace(' application', (1708, 1720), self.input.position)
_G_apply_199, lastError = self._apply(self.rule_application, "application", [])
self.considerError(lastError, None)
return (_G_apply_199, self.currentError)
def _G_or_200():
self._trace(' ruleValue', (1732, 1742), self.input.position)
_G_apply_201, lastError = self._apply(self.rule_ruleValue, "ruleValue", [])
self.considerError(lastError, None)
return (_G_apply_201, self.currentError)
def _G_or_202():
self._trace(' semanticPredicate', (1754, 1772), self.input.position)
_G_apply_203, lastError = self._apply(self.rule_semanticPredicate, "semanticPredicate", [])
self.considerError(lastError, None)
return (_G_apply_203, self.currentError)
def _G_or_204():
self._trace(' semanticAction', (1784, 1799), self.input.position)
_G_apply_205, lastError = self._apply(self.rule_semanticAction, "semanticAction", [])
self.considerError(lastError, None)
return (_G_apply_205, self.currentError)
def _G_or_206():
self._trace(' number', (1811, 1818), self.input.position)
_G_apply_207, lastError = self._apply(self.rule_number, "number", [])
self.considerError(lastError, None)
_locals['n'] = _G_apply_207
_G_python_208, lastError = eval('self.isTree()', self.globals, _locals), None
self.considerError(lastError, None)
_G_python_209, lastError = eval('n', self.globals, _locals), None
self.considerError(lastError, None)
return (_G_python_209, self.currentError)
def _G_or_210():
self._trace(' character', (1854, 1864), self.input.position)
_G_apply_211, lastError = self._apply(self.rule_character, "character", [])
self.considerError(lastError, None)
return (_G_apply_211, self.currentError)
def _G_or_212():
self._trace(' string', (1876, 1883), self.input.position)
_G_apply_213, lastError = self._apply(self.rule_string, "string", [])
self.considerError(lastError, None)
return (_G_apply_213, self.currentError)
_G_or_214, lastError = self._or([_G_or_196, _G_or_198, _G_or_200, _G_or_202, _G_or_204, _G_or_206, _G_or_210, _G_or_212])
self.considerError(lastError, 'traceable')
return (_G_or_214, self.currentError)
def rule_expr1(self):
_locals = {'self': self}
self.locals['expr1'] = _locals
def _G_or_215():
self._trace(' traceable', (1893, 1903), self.input.position)
_G_apply_216, lastError = self._apply(self.rule_traceable, "traceable", [])
self.considerError(lastError, None)
return (_G_apply_216, self.currentError)
def _G_or_217():
self._trace(' ws', (1911, 1914), self.input.position)
_G_apply_218, lastError = self._apply(self.rule_ws, "ws", [])
self.considerError(lastError, None)
self._trace(" '('", (1914, 1918), self.input.position)
_G_exactly_219, lastError = self.exactly('(')
self.considerError(lastError, None)
self._trace(' expr', (1918, 1923), self.input.position)
_G_apply_220, lastError = self._apply(self.rule_expr, "expr", [])
self.considerError(lastError, None)
_locals['e'] = _G_apply_220
self._trace(' ws', (1925, 1928), self.input.position)
_G_apply_221, lastError = self._apply(self.rule_ws, "ws", [])
self.considerError(lastError, None)
self._trace(" ')'", (1928, 1932), self.input.position)
_G_exactly_222, lastError = self.exactly(')')
self.considerError(lastError, None)
_G_python_223, lastError = eval('e', self.globals, _locals), None
self.considerError(lastError, None)
return (_G_python_223, self.currentError)
def _G_or_224():
self._trace(' ws', (1945, 1948), self.input.position)
_G_apply_225, lastError = self._apply(self.rule_ws, "ws", [])
self.considerError(lastError, None)
self._trace(" '<'", (1948, 1952), self.input.position)
_G_exactly_226, lastError = self.exactly('<')
self.considerError(lastError, None)
self._trace(' expr', (1952, 1957), self.input.position)
_G_apply_227, lastError = self._apply(self.rule_expr, "expr", [])
self.considerError(lastError, None)
_locals['e'] = _G_apply_227
self._trace(' ws', (1959, 1962), self.input.position)
_G_apply_228, lastError = self._apply(self.rule_ws, "ws", [])
self.considerError(lastError, None)
self._trace(" '>'", (1962, 1966), self.input.position)
_G_exactly_229, lastError = self.exactly('>')
self.considerError(lastError, None)
_G_python_230, lastError = eval('t.ConsumedBy(e)', self.globals, _locals), None
self.considerError(lastError, None)
return (_G_python_230, self.currentError)
def _G_or_231():
self._trace(' ws', (2002, 2005), self.input.position)
_G_apply_232, lastError = self._apply(self.rule_ws, "ws", [])
self.considerError(lastError, None)
self._trace(" '['", (2005, 2009), self.input.position)
_G_exactly_233, lastError = self.exactly('[')
self.considerError(lastError, None)
def _G_optional_234():
self._trace(' expr', (2009, 2014), self.input.position)
_G_apply_235, lastError = self._apply(self.rule_expr, "expr", [])
self.considerError(lastError, None)
return (_G_apply_235, self.currentError)
def _G_optional_236():
return (None, self.input.nullError())
_G_or_237, lastError = self._or([_G_optional_234, _G_optional_236])
self.considerError(lastError, None)
_locals['e'] = _G_or_237
self._trace(' ws', (2017, 2020), self.input.position)
_G_apply_238, lastError = self._apply(self.rule_ws, "ws", [])
self.considerError(lastError, None)
self._trace(" ']'", (2020, 2024), self.input.position)
_G_exactly_239, lastError = self.exactly(']')
self.considerError(lastError, None)
_G_python_240, lastError = eval('self.isTree()', self.globals, _locals), None
self.considerError(lastError, None)
_G_python_241, lastError = eval('t.List(e) if e else t.List()', self.globals, _locals), None
self.considerError(lastError, None)
return (_G_python_241, self.currentError)
_G_or_242, lastError = self._or([_G_or_215, _G_or_217, _G_or_224, _G_or_231])
self.considerError(lastError, 'expr1')
return (_G_or_242, self.currentError)
def rule_expr2(self):
_locals = {'self': self}
self.locals['expr2'] = _locals
def _G_or_243():
self._trace('ws', (2093, 2095), self.input.position)
_G_apply_244, lastError = self._apply(self.rule_ws, "ws", [])
self.considerError(lastError, None)
self._trace(" '~'", (2095, 2099), self.input.position)
_G_exactly_245, lastError = self.exactly('~')
self.considerError(lastError, None)
def _G_or_246():
self._trace("'~'", (2101, 2104), self.input.position)
_G_exactly_247, lastError = self.exactly('~')
self.considerError(lastError, None)
self._trace(' expr2', (2104, 2110), self.input.position)
_G_apply_248, lastError = self._apply(self.rule_expr2, "expr2", [])
self.considerError(lastError, None)
_locals['e'] = _G_apply_248
_G_python_249, lastError = eval('t.Lookahead(e)', self.globals, _locals), None
self.considerError(lastError, None)
return (_G_python_249, self.currentError)
def _G_or_250():
self._trace(' expr2', (2148, 2157), self.input.position)
_G_apply_251, lastError = self._apply(self.rule_expr2, "expr2", [])
self.considerError(lastError, None)
_locals['e'] = _G_apply_251
_G_python_252, lastError = eval('t.Not(e)', self.globals, _locals), None
self.considerError(lastError, None)
return (_G_python_252, self.currentError)
_G_or_253, lastError = self._or([_G_or_246, _G_or_250])
self.considerError(lastError, None)
return (_G_or_253, self.currentError)
def _G_or_254():
self._trace('expr1', (2199, 2204), self.input.position)
_G_apply_255, lastError = self._apply(self.rule_expr1, "expr1", [])
self.considerError(lastError, None)
return (_G_apply_255, self.currentError)
_G_or_256, lastError = self._or([_G_or_243, _G_or_254])
self.considerError(lastError, 'expr2')
return (_G_or_256, self.currentError)
def rule_repeatTimes(self):
_locals = {'self': self}
self.locals['repeatTimes'] = _locals
def _G_or_257():
self._trace('barenumber', (2222, 2232), self.input.position)
_G_apply_258, lastError = self._apply(self.rule_barenumber, "barenumber", [])
self.considerError(lastError, None)
_locals['x'] = _G_apply_258
_G_python_259, lastError = eval('int(x)', self.globals, _locals), None
self.considerError(lastError, None)
return (_G_python_259, self.currentError)
def _G_or_260():
self._trace(' name', (2247, 2252), self.input.position)
_G_apply_261, lastError = self._apply(self.rule_name, "name", [])
self.considerError(lastError, None)
return (_G_apply_261, self.currentError)
_G_or_262, lastError = self._or([_G_or_257, _G_or_260])
self.considerError(lastError, 'repeatTimes')
return (_G_or_262, self.currentError)
def rule_expr3(self):
_locals = {'self': self}
self.locals['expr3'] = _locals
def _G_or_263():
self._trace('expr2', (2263, 2268), self.input.position)
_G_apply_264, lastError = self._apply(self.rule_expr2, "expr2", [])
self.considerError(lastError, None)
_locals['e'] = _G_apply_264
def _G_or_265():
self._trace("'*'", (2294, 2297), self.input.position)
_G_exactly_266, lastError = self.exactly('*')
self.considerError(lastError, None)
_G_python_267, lastError = eval('t.Many(e)', self.globals, _locals), None
self.considerError(lastError, None)
return (_G_python_267, self.currentError)
def _G_or_268():
self._trace("'+'", (2334, 2337), self.input.position)
_G_exactly_269, lastError = self.exactly('+')
self.considerError(lastError, None)
_G_python_270, lastError = eval('t.Many1(e)', self.globals, _locals), None
self.considerError(lastError, None)
return (_G_python_270, self.currentError)
def _G_or_271():
self._trace("'?'", (2375, 2378), self.input.position)
_G_exactly_272, lastError = self.exactly('?')
self.considerError(lastError, None)
_G_python_273, lastError = eval('t.Optional(e)', self.globals, _locals), None
self.considerError(lastError, None)
return (_G_python_273, self.currentError)
def _G_or_274():
self._trace('customLabel', (2419, 2430), self.input.position)
_G_apply_275, lastError = self._apply(self.rule_customLabel, "customLabel", [])
self.considerError(lastError, None)
_locals['l'] = _G_apply_275
_G_python_276, lastError = eval('t.Label(e, l)', self.globals, _locals), None
self.considerError(lastError, None)
return (_G_python_276, self.currentError)
def _G_or_277():
self._trace("'{'", (2473, 2476), self.input.position)
_G_exactly_278, lastError = self.exactly('{')
self.considerError(lastError, None)
self._trace(' ws', (2476, 2479), self.input.position)
_G_apply_279, lastError = self._apply(self.rule_ws, "ws", [])
self.considerError(lastError, None)
self._trace(' repeatTimes', (2479, 2491), self.input.position)
_G_apply_280, lastError = self._apply(self.rule_repeatTimes, "repeatTimes", [])
self.considerError(lastError, None)
_locals['start'] = _G_apply_280
self._trace(' ws', (2497, 2500), self.input.position)
_G_apply_281, lastError = self._apply(self.rule_ws, "ws", [])
self.considerError(lastError, None)
def _G_or_282():
self._trace("','", (2526, 2529), self.input.position)
_G_exactly_283, lastError = self.exactly(',')
self.considerError(lastError, None)
self._trace(' ws', (2529, 2532), self.input.position)
_G_apply_284, lastError = self._apply(self.rule_ws, "ws", [])
self.considerError(lastError, None)
self._trace(' repeatTimes', (2532, 2544), self.input.position)
_G_apply_285, lastError = self._apply(self.rule_repeatTimes, "repeatTimes", [])
self.considerError(lastError, None)
_locals['end'] = _G_apply_285
self._trace(' ws', (2548, 2551), self.input.position)
_G_apply_286, lastError = self._apply(self.rule_ws, "ws", [])
self.considerError(lastError, None)
self._trace(" '}'", (2551, 2555), self.input.position)
_G_exactly_287, lastError = self.exactly('}')
self.considerError(lastError, None)
_G_python_288, lastError = eval('t.Repeat(start, end, e)', self.globals, _locals), None
self.considerError(lastError, None)
return (_G_python_288, self.currentError)
def _G_or_289():
self._trace(' ws', (2637, 2640), self.input.position)
_G_apply_290, lastError = self._apply(self.rule_ws, "ws", [])
self.considerError(lastError, None)
self._trace(" '}'", (2640, 2644), self.input.position)
_G_exactly_291, lastError = self.exactly('}')
self.considerError(lastError, None)
_G_python_292, lastError = eval('t.Repeat(start, start, e)', self.globals, _locals), None
self.considerError(lastError, None)
return (_G_python_292, self.currentError)
_G_or_293, lastError = self._or([_G_or_282, _G_or_289])
self.considerError(lastError, None)
return (_G_or_293, self.currentError)
def _G_or_294():
_G_python_295, lastError = eval('e', self.globals, _locals), None
self.considerError(lastError, None)
return (_G_python_295, self.currentError)
_G_or_296, lastError = self._or([_G_or_265, _G_or_268, _G_or_271, _G_or_274, _G_or_277, _G_or_294])
self.considerError(lastError, None)
_locals['r'] = _G_or_296
def _G_or_297():
self._trace("':'", (2748, 2751), self.input.position)
_G_exactly_298, lastError = self.exactly(':')
self.considerError(lastError, None)
self._trace(' name', (2751, 2756), self.input.position)
_G_apply_299, lastError = self._apply(self.rule_name, "name", [])
self.considerError(lastError, None)
_locals['n'] = _G_apply_299
_G_python_300, lastError = eval('t.Bind(n, r)', self.globals, _locals), None
self.considerError(lastError, None)
return (_G_python_300, self.currentError)
def _G_or_301():
self._trace(" ':('", (2787, 2792), self.input.position)
_G_exactly_302, lastError = self.exactly(':(')
self.considerError(lastError, None)
self._trace(' name', (2792, 2797), self.input.position)
_G_apply_303, lastError = self._apply(self.rule_name, "name", [])
self.considerError(lastError, None)
_locals['n'] = _G_apply_303
def _G_many_304():
self._trace("','", (2801, 2804), self.input.position)
_G_exactly_305, lastError = self.exactly(',')
self.considerError(lastError, None)
self._trace(' ws', (2804, 2807), self.input.position)
_G_apply_306, lastError = self._apply(self.rule_ws, "ws", [])
self.considerError(lastError, None)
self._trace(' name', (2807, 2812), self.input.position)
_G_apply_307, lastError = self._apply(self.rule_name, "name", [])
self.considerError(lastError, None)
return (_G_apply_307, self.currentError)
_G_many_308, lastError = self.many(_G_many_304)
self.considerError(lastError, None)
_locals['others'] = _G_many_308
self._trace(' ws', (2821, 2824), self.input.position)
_G_apply_309, lastError = self._apply(self.rule_ws, "ws", [])
self.considerError(lastError, None)
self._trace(" ')'", (2824, 2828), self.input.position)
_G_exactly_310, lastError = self.exactly(')')
self.considerError(lastError, None)
_G_python_311, lastError = eval('[n] + others if others else n', self.globals, _locals), None
self.considerError(lastError, None)
_locals['n'] = _G_python_311
_G_python_312, lastError = eval('t.Bind(n, r)', self.globals, _locals), None
self.considerError(lastError, None)
return (_G_python_312, self.currentError)
def _G_or_313():
_G_python_314, lastError = eval('r', self.globals, _locals), None
self.considerError(lastError, None)
return (_G_python_314, self.currentError)
_G_or_315, lastError = self._or([_G_or_297, _G_or_301, _G_or_313])
self.considerError(lastError, None)
return (_G_or_315, self.currentError)
def _G_or_316():
self._trace('ws', (2928, 2930), self.input.position)
_G_apply_317, lastError = self._apply(self.rule_ws, "ws", [])
self.considerError(lastError, None)
self._trace(" ':'", (2930, 2934), self.input.position)
_G_exactly_318, lastError = self.exactly(':')
self.considerError(lastError, None)
self._trace(' name', (2934, 2939), self.input.position)
_G_apply_319, lastError = self._apply(self.rule_name, "name", [])
self.considerError(lastError, None)
_locals['n'] = _G_apply_319
_G_python_320, lastError = eval('t.Bind(n, t.Apply("anything", self.rulename, []))', self.globals, _locals), None
self.considerError(lastError, None)
return (_G_python_320, self.currentError)
_G_or_321, lastError = self._or([_G_or_263, _G_or_316])
self.considerError(lastError, 'expr3')
return (_G_or_321, self.currentError)
def rule_expr4(self):
_locals = {'self': self}
self.locals['expr4'] = _locals
def _G_many1_322():
self._trace(' expr3', (3013, 3019), self.input.position)
_G_apply_323, lastError = self._apply(self.rule_expr3, "expr3", [])
self.considerError(lastError, None)
return (_G_apply_323, self.currentError)
_G_many1_324, lastError = self.many(_G_many1_322, _G_many1_322())
self.considerError(lastError, 'expr4')
_locals['es'] = _G_many1_324
_G_python_325, lastError = eval('es[0] if len(es) == 1 else t.And(es)', self.globals, _locals), None
self.considerError(lastError, 'expr4')
return (_G_python_325, self.currentError)
def rule_expr(self):
_locals = {'self': self}
self.locals['expr'] = _locals
self._trace(' expr4', (3071, 3077), self.input.position)
_G_apply_326, lastError = self._apply(self.rule_expr4, "expr4", [])
self.considerError(lastError, 'expr')
_locals['e'] = _G_apply_326
def _G_many_327():
self._trace('ws', (3081, 3083), self.input.position)
_G_apply_328, lastError = self._apply(self.rule_ws, "ws", [])
self.considerError(lastError, None)
self._trace(" '|'", (3083, 3087), self.input.position)
_G_exactly_329, lastError = self.exactly('|')
self.considerError(lastError, None)
self._trace(' expr4', (3087, 3093), self.input.position)
_G_apply_330, lastError = self._apply(self.rule_expr4, "expr4", [])
self.considerError(lastError, None)
return (_G_apply_330, self.currentError)
_G_many_331, lastError = self.many(_G_many_327)
self.considerError(lastError, 'expr')
_locals['es'] = _G_many_331
_G_python_332, lastError = eval('t.Or([e] + es) if es else e', self.globals, _locals), None
self.considerError(lastError, 'expr')
return (_G_python_332, self.currentError)
def rule_ruleValue(self):
_locals = {'self': self}
self.locals['ruleValue'] = _locals
self._trace(' ws', (3152, 3155), self.input.position)
_G_apply_333, lastError = self._apply(self.rule_ws, "ws", [])
self.considerError(lastError, 'ruleValue')
self._trace(" '->'", (3155, 3160), self.input.position)
_G_exactly_334, lastError = self.exactly('->')
self.considerError(lastError, 'ruleValue')
_G_python_335, lastError = eval('self.ruleValueExpr(True)', self.globals, _locals), None
self.considerError(lastError, 'ruleValue')
return (_G_python_335, self.currentError)
def rule_customLabel(self):
_locals = {'self': self}
self.locals['customLabel'] = _locals
def _G_label_336():
self._trace('ws', (3205, 3207), self.input.position)
_G_apply_337, lastError = self._apply(self.rule_ws, "ws", [])
self.considerError(lastError, None)
self._trace(" '^'", (3207, 3211), self.input.position)
_G_exactly_338, lastError = self.exactly('^')
self.considerError(lastError, None)
self._trace(' ws', (3211, 3214), self.input.position)
_G_apply_339, lastError = self._apply(self.rule_ws, "ws", [])
self.considerError(lastError, None)
self._trace(" '('", (3214, 3218), self.input.position)
_G_exactly_340, lastError = self.exactly('(')
self.considerError(lastError, None)
def _G_consumedby_341():
def _G_many1_342():
def _G_not_343():
self._trace("')'", (3222, 3225), self.input.position)
_G_exactly_344, lastError = self.exactly(')')
self.considerError(lastError, None)
return (_G_exactly_344, self.currentError)
_G_not_345, lastError = self._not(_G_not_343)
self.considerError(lastError, None)
self._trace(' anything', (3225, 3234), self.input.position)
_G_apply_346, lastError = self._apply(self.rule_anything, "anything", [])
self.considerError(lastError, None)
return (_G_apply_346, self.currentError)
_G_many1_347, lastError = self.many(_G_many1_342, _G_many1_342())
self.considerError(lastError, None)
return (_G_many1_347, self.currentError)
_G_consumedby_348, lastError = self.consumedby(_G_consumedby_341)
self.considerError(lastError, None)
_locals['e'] = _G_consumedby_348
self._trace(" ')'", (3239, 3243), self.input.position)
_G_exactly_349, lastError = self.exactly(')')
self.considerError(lastError, None)
_G_python_350, lastError = eval('e', self.globals, _locals), None
self.considerError(lastError, None)
return (_G_python_350, self.currentError)
_G_label_351, lastError = self.label(_G_label_336, "customLabelException")
self.considerError(lastError, 'customLabel')
return (_G_label_351, self.currentError)
def rule_semanticPredicate(self):
_locals = {'self': self}
self.locals['semanticPredicate'] = _locals
self._trace(' ws', (3295, 3298), self.input.position)
_G_apply_352, lastError = self._apply(self.rule_ws, "ws", [])
self.considerError(lastError, 'semanticPredicate')
self._trace(" '?('", (3298, 3303), self.input.position)
_G_exactly_353, lastError = self.exactly('?(')
self.considerError(lastError, 'semanticPredicate')
_G_python_354, lastError = eval('self.semanticPredicateExpr()', self.globals, _locals), None
self.considerError(lastError, 'semanticPredicate')
return (_G_python_354, self.currentError)
def rule_semanticAction(self):
_locals = {'self': self}
self.locals['semanticAction'] = _locals
self._trace(' ws', (3353, 3356), self.input.position)
_G_apply_355, lastError = self._apply(self.rule_ws, "ws", [])
self.considerError(lastError, 'semanticAction')
self._trace(" '!('", (3356, 3361), self.input.position)
_G_exactly_356, lastError = self.exactly('!(')
self.considerError(lastError, 'semanticAction')
_G_python_357, lastError = eval('self.semanticActionExpr()', self.globals, _locals), None
self.considerError(lastError, 'semanticAction')
return (_G_python_357, self.currentError)
def rule_ruleEnd(self):
_locals = {'self': self}
self.locals['ruleEnd'] = _locals
def _G_label_358():
def _G_or_359():
def _G_many_360():
self._trace('hspace', (3404, 3410), self.input.position)
_G_apply_361, lastError = self._apply(self.rule_hspace, "hspace", [])
self.considerError(lastError, None)
return (_G_apply_361, self.currentError)
_G_many_362, lastError = self.many(_G_many_360)
self.considerError(lastError, None)
def _G_many1_363():
self._trace(' vspace', (3411, 3418), self.input.position)
_G_apply_364, lastError = self._apply(self.rule_vspace, "vspace", [])
self.considerError(lastError, None)
return (_G_apply_364, self.currentError)
_G_many1_365, lastError = self.many(_G_many1_363, _G_many1_363())
self.considerError(lastError, None)
return (_G_many1_365, self.currentError)
def _G_or_366():
self._trace(' end', (3422, 3426), self.input.position)
_G_apply_367, lastError = self._apply(self.rule_end, "end", [])
self.considerError(lastError, None)
return (_G_apply_367, self.currentError)
_G_or_368, lastError = self._or([_G_or_359, _G_or_366])
self.considerError(lastError, None)
return (_G_or_368, self.currentError)
_G_label_369, lastError = self.label(_G_label_358, "rule end")
self.considerError(lastError, 'ruleEnd')
return (_G_label_369, self.currentError)
def rule_rulePart(self):
_locals = {'self': self}
self.locals['rulePart'] = _locals
_G_apply_370, lastError = self._apply(self.rule_anything, "anything", [])
self.considerError(lastError, 'rulePart')
_locals['requiredName'] = _G_apply_370
self._trace(' noindentation', (3466, 3480), self.input.position)
_G_apply_371, lastError = self._apply(self.rule_noindentation, "noindentation", [])
self.considerError(lastError, 'rulePart')
self._trace(' name', (3480, 3485), self.input.position)
_G_apply_372, lastError = self._apply(self.rule_name, "name", [])
self.considerError(lastError, 'rulePart')
_locals['n'] = _G_apply_372
def _G_pred_373():
_G_python_374, lastError = eval('n == requiredName', self.globals, _locals), None
self.considerError(lastError, None)
return (_G_python_374, self.currentError)
_G_pred_375, lastError = self.pred(_G_pred_373)
self.considerError(lastError, 'rulePart')
_G_python_376, lastError = eval('setattr(self, "rulename", n)', self.globals, _locals), None
self.considerError(lastError, 'rulePart')
def _G_optional_377():
self._trace('\n expr4', (3568, 3602), self.input.position)
_G_apply_378, lastError = self._apply(self.rule_expr4, "expr4", [])
self.considerError(lastError, None)
return (_G_apply_378, self.currentError)
def _G_optional_379():
return (None, self.input.nullError())
_G_or_380, lastError = self._or([_G_optional_377, _G_optional_379])
self.considerError(lastError, 'rulePart')
_locals['args'] = _G_or_380
def _G_or_381():
self._trace('ws', (3638, 3640), self.input.position)
_G_apply_382, lastError = self._apply(self.rule_ws, "ws", [])
self.considerError(lastError, None)
self._trace(" '='", (3640, 3644), self.input.position)
_G_exactly_383, lastError = self.exactly('=')
self.considerError(lastError, None)
self._trace(' expr', (3644, 3649), self.input.position)
_G_apply_384, lastError = self._apply(self.rule_expr, "expr", [])
self.considerError(lastError, None)
_locals['e'] = _G_apply_384
self._trace(' ruleEnd', (3651, 3659), self.input.position)
_G_apply_385, lastError = self._apply(self.rule_ruleEnd, "ruleEnd", [])
self.considerError(lastError, None)
_G_python_386, lastError = eval('t.And([args, e]) if args else e', self.globals, _locals), None
self.considerError(lastError, None)
return (_G_python_386, self.currentError)
def _G_or_387():
self._trace(' ruleEnd', (3755, 3763), self.input.position)
_G_apply_388, lastError = self._apply(self.rule_ruleEnd, "ruleEnd", [])
self.considerError(lastError, None)
_G_python_389, lastError = eval('args', self.globals, _locals), None
self.considerError(lastError, None)
return (_G_python_389, self.currentError)
_G_or_390, lastError = self._or([_G_or_381, _G_or_387])
self.considerError(lastError, 'rulePart')
return (_G_or_390, self.currentError)
def rule_rule(self):
_locals = {'self': self}
self.locals['rule'] = _locals
self._trace(' noindentation', (3780, 3794), self.input.position)
_G_apply_391, lastError = self._apply(self.rule_noindentation, "noindentation", [])
self.considerError(lastError, 'rule')
def _G_lookahead_392():
self._trace('name', (3798, 3802), self.input.position)
_G_apply_393, lastError = self._apply(self.rule_name, "name", [])
self.considerError(lastError, None)
_locals['n'] = _G_apply_393
return (_locals['n'], self.currentError)
_G_lookahead_394, lastError = self.lookahead(_G_lookahead_392)
self.considerError(lastError, 'rule')
def _G_many1_395():
self._trace(' rulePart(n)', (3805, 3817), self.input.position)
_G_python_396, lastError = eval('n', self.globals, _locals), None
self.considerError(lastError, None)
_G_apply_397, lastError = self._apply(self.rule_rulePart, "rulePart", [_G_python_396])
self.considerError(lastError, None)
return (_G_apply_397, self.currentError)
_G_many1_398, lastError = self.many(_G_many1_395, _G_many1_395())
self.considerError(lastError, 'rule')
_locals['rs'] = _G_many1_398
_G_python_399, lastError = eval('t.Rule(n, t.Or(rs))', self.globals, _locals), None
self.considerError(lastError, 'rule')
return (_G_python_399, self.currentError)
def rule_grammar(self):
_locals = {'self': self}
self.locals['grammar'] = _locals
def _G_many_400():
self._trace(' rule', (3856, 3861), self.input.position)
_G_apply_401, lastError = self._apply(self.rule_rule, "rule", [])
self.considerError(lastError, None)
return (_G_apply_401, self.currentError)
_G_many_402, lastError = self.many(_G_many_400)
self.considerError(lastError, 'grammar')
_locals['rs'] = _G_many_402
self._trace(' ws', (3865, 3868), self.input.position)
_G_apply_403, lastError = self._apply(self.rule_ws, "ws", [])
self.considerError(lastError, 'grammar')
_G_python_404, lastError = eval('t.Grammar(self.name, self.tree_target, rs)', self.globals, _locals), None
self.considerError(lastError, 'grammar')
return (_G_python_404, self.currentError)
if parsley.globals is not None:
parsley.globals = parsley.globals.copy()
parsley.globals.update(ruleGlobals)
else:
parsley.globals = ruleGlobals
return parsley
| (grammar, *a, **kw) |
28,472 | ometa.runtime | __init__ | null | def __init__(self, grammar, *a, **kw):
OMetaBase.__init__(self, dedent(grammar), *a, **kw)
self._spanStart = 0
| (self, grammar, *a, **kw) |
28,473 | ometa.runtime | _apply |
Apply a rule method to some args.
@param rule: A method of this object.
@param ruleName: The name of the rule invoked.
@param args: A sequence of arguments to it.
| def _apply(self, rule, ruleName, args):
"""
Apply a rule method to some args.
@param rule: A method of this object.
@param ruleName: The name of the rule invoked.
@param args: A sequence of arguments to it.
"""
if args:
if basestring is str:
attrname = '__code__'
else:
attrname = 'func_code'
if ((not getattr(rule, attrname, None))
or getattr(rule, attrname).co_argcount - 1 != len(args)):
for arg in args[::-1]:
self.input = ArgInput(arg, self.input)
return rule()
else:
return rule(*args)
memoRec = self.input.getMemo(ruleName)
if memoRec is None:
oldPosition = self.input
lr = LeftRecursion()
memoRec = self.input.setMemo(ruleName, lr)
try:
memoRec = self.input.setMemo(ruleName,
[rule(), self.input])
except ParseError as e:
e.trail.append(ruleName)
raise
if lr.detected:
sentinel = self.input
while True:
try:
self.input = oldPosition
ans = rule()
if (self.input == sentinel):
break
memoRec = oldPosition.setMemo(ruleName,
[ans, self.input])
except ParseError:
break
self.input = oldPosition
elif isinstance(memoRec, LeftRecursion):
memoRec.detected = True
raise self.input.nullError()
self.input = memoRec[1]
return memoRec[0]
| (self, rule, ruleName, args) |
28,474 | ometa.runtime | _not |
Call the given function. Raise ParseError iff it does not.
@param fn: A callable of no arguments.
| def _not(self, fn):
"""
Call the given function. Raise ParseError iff it does not.
@param fn: A callable of no arguments.
"""
m = self.input
try:
fn()
except ParseError:
self.input = m
return True, self.input.nullError()
else:
raise self.input.nullError()
| (self, fn) |
28,475 | ometa.runtime | _or |
Call each of a list of functions in sequence until one succeeds,
rewinding the input between each.
@param fns: A list of no-argument callables.
| def _or(self, fns):
"""
Call each of a list of functions in sequence until one succeeds,
rewinding the input between each.
@param fns: A list of no-argument callables.
"""
errors = []
for f in fns:
try:
m = self.input
ret, err = f()
errors.append(err)
return ret, joinErrors(errors)
except ParseError as e:
errors.append(e)
self.input = m
raise joinErrors(errors)
| (self, fns) |
28,476 | ometa.runtime | _trace | null | def _trace(self, src, span, inputPos):
pass
| (self, src, span, inputPos) |
28,477 | ometa.runtime | applicationArgs |
Collect rule arguments, a list of Python expressions separated by
spaces.
| def applicationArgs(self, finalChar):
"""
Collect rule arguments, a list of Python expressions separated by
spaces.
"""
args = []
while True:
try:
(arg, endchar), err = self.pythonExpr(" " + finalChar)
if not arg:
break
args.append(t.Action(arg))
if endchar == finalChar:
break
if endchar == ' ':
self.rule_anything()
except ParseError:
break
if args:
return args
else:
raise self.input.nullError()
| (self, finalChar) |
28,478 | ometa.runtime | apply |
Apply the named rule, optionally with some arguments.
@param ruleName: A rule name.
| def apply(self, ruleName, *args):
"""
Apply the named rule, optionally with some arguments.
@param ruleName: A rule name.
"""
r = getattr(self, "rule_"+ruleName, None)
if r is not None:
val, err = self._apply(r, ruleName, args)
return val, err
else:
raise NameError("No rule named '%s'" %(ruleName,))
| (self, ruleName, *args) |
28,479 | ometa.runtime | considerError | null | def considerError(self, error, typ=None):
if error:
newPos = error.position
curPos = self.currentError.position
if newPos > curPos:
self.currentError = error
elif newPos == curPos:
self.currentError.mergeWith(error)
| (self, error, typ=None) |
28,480 | ometa.runtime | consumedby | null | def consumedby(self, expr):
oldInput = self.input
_, e = expr()
slice = oldInput.data[oldInput.position:self.input.position]
return slice, e
| (self, expr) |
28,481 | ometa.runtime | digit |
Match a single digit.
| def digit(self):
"""
Match a single digit.
"""
x, e = self.rule_anything()
if x.isdigit():
return x, e
else:
raise e.withMessage(expected("digit"))
| (self) |
28,482 | ometa.runtime | eatWhitespace |
Consume input until a non-whitespace character is reached.
| def eatWhitespace(self):
"""
Consume input until a non-whitespace character is reached.
"""
consumingComment = False
while True:
try:
c, e = self.input.head()
except EOFError as e:
break
t = self.input.tail()
if c.isspace() or consumingComment:
self.input = t
if c == '\n':
consumingComment = False
elif c == '#':
consumingComment = True
else:
break
return True, e
| (self) |
28,483 | ometa.runtime | end |
Match the end of the stream.
| def end(self):
"""
Match the end of the stream.
"""
return self._not(self.rule_anything)
| (self) |
28,484 | ometa.runtime | exactly |
Match a single item from the input equal to the given
specimen, or a sequence of characters if the input is string.
@param wanted: What to match.
| def exactly(self, wanted):
"""
Match a single item from the input equal to the given
specimen, or a sequence of characters if the input is string.
@param wanted: What to match.
"""
i = self.input
if not self.tree and len(wanted) > 1:
val, p, self.input = self.input.slice(len(wanted))
else:
val, p = self.input.head()
self.input = self.input.tail()
if wanted == val:
return val, p
else:
self.input = i
raise p.withMessage(expected(None, wanted))
| (self, wanted) |
28,485 | ometa.runtime | foreignApply |
Apply the named rule of a foreign grammar.
@param grammarName: name to look up in locals/globals for grammar
@param ruleName: rule name
| def foreignApply(self, grammarName, ruleName, globals_, locals_, *args):
"""
Apply the named rule of a foreign grammar.
@param grammarName: name to look up in locals/globals for grammar
@param ruleName: rule name
"""
grammar = locals_.get(grammarName, None)
if grammar is None:
grammar = globals_[grammarName]
grammar = getattr(grammar, "_grammarClass", grammar)
instance = grammar(self.input, stream=True)
rule = getattr(instance, "rule_" + ruleName, None)
if rule is not None:
self.input.setMemo(ruleName, None)
result = instance._apply(rule, ruleName, args)
self.input = instance.input
return result
else:
raise NameError("No rule named '%s' on grammar '%s'" %
(ruleName, grammarName))
| (self, grammarName, ruleName, globals_, locals_, *args) |
28,486 | ometa.runtime | getSpan | null | def getSpan(self):
return (self._spanStart, self.input.position)
| (self) |
28,487 | ometa.runtime | isTree | null | def isTree(self):
self.tree_target = True
| (self) |
28,488 | ometa.runtime | label |
Wrap a function and add label to expected message.
| def label(self, foo, label):
"""
Wrap a function and add label to expected message.
"""
try:
val, err = foo()
err2 = err.withMessage([("Custom Exception:", label, None)])
if self.currentError == err:
self.currentError = err2
return val, err2
except ParseError as e:
raise e.withMessage([("Custom Exception:", label, None)])
| (self, foo, label) |
28,489 | ometa.runtime | letter |
Match a single letter.
| def letter(self):
"""
Match a single letter.
"""
x, e = self.rule_anything()
if x.isalpha():
return x, e
else:
raise e.withMessage(expected("letter"))
| (self) |
28,490 | ometa.runtime | letterOrDigit |
Match a single alphanumeric character.
| def letterOrDigit(self):
"""
Match a single alphanumeric character.
"""
x, e = self.rule_anything()
if x.isalnum():
return x, e
else:
raise e.withMessage(expected("letter or digit"))
| (self) |
28,491 | ometa.runtime | listpattern |
Call the given function, treating the next object on the stack as an
iterable to be used for input.
@param expr: A callable of no arguments.
| def listpattern(self, expr):
"""
Call the given function, treating the next object on the stack as an
iterable to be used for input.
@param expr: A callable of no arguments.
"""
v, e = self.rule_anything()
oldInput = self.input
try:
self.input = InputStream.fromIterable(v)
except TypeError:
raise e.withMessage(expected("an iterable"))
expr()
self.end()
self.input = oldInput
return v, e
| (self, expr) |
28,492 | ometa.runtime | lookahead |
Execute the given callable, rewinding the stream no matter whether it
returns successfully or not.
@param f: A callable of no arguments.
| def lookahead(self, f):
"""
Execute the given callable, rewinding the stream no matter whether it
returns successfully or not.
@param f: A callable of no arguments.
"""
try:
m = self.input
x = f()
return x
finally:
self.input = m
| (self, f) |
28,493 | ometa.runtime | many |
Call C{fn} until it fails to match the input. Collect the resulting
values into a list.
@param fn: A callable of no arguments.
@param initial: Initial values to populate the returned list with.
| def many(self, fn, *initial):
"""
Call C{fn} until it fails to match the input. Collect the resulting
values into a list.
@param fn: A callable of no arguments.
@param initial: Initial values to populate the returned list with.
"""
ans = []
for x, e in initial:
ans.append(x)
while True:
try:
m = self.input
v, _ = fn()
ans.append(v)
except ParseError as err:
e = err
self.input = m
break
return ans, e
| (self, fn, *initial) |
28,494 | ometa.runtime | parseGrammar |
Entry point for converting a grammar to code (of some variety).
@param name: The name for this grammar.
@param builder: A class that implements the grammar-building interface
(interface to be explicitly defined later)
| def parseGrammar(self, name):
"""
Entry point for converting a grammar to code (of some variety).
@param name: The name for this grammar.
@param builder: A class that implements the grammar-building interface
(interface to be explicitly defined later)
"""
self.name = name
res, err = self.apply("grammar")
try:
self.input.head()
except EOFError:
pass
else:
raise err
return res
| (self, name) |
28,495 | ometa.runtime | pred |
Call the given function, raising ParseError if it returns false.
@param expr: A callable of no arguments.
| def pred(self, expr):
"""
Call the given function, raising ParseError if it returns false.
@param expr: A callable of no arguments.
"""
val, e = expr()
if not val:
raise e
else:
return True, e
| (self, expr) |
28,496 | ometa.runtime | pythonExpr |
Extract a Python expression from the input and return it.
@arg endChars: A set of characters delimiting the end of the expression.
| def pythonExpr(self, endChars="\r\n"):
"""
Extract a Python expression from the input and return it.
@arg endChars: A set of characters delimiting the end of the expression.
"""
delimiters = { "(": ")", "[": "]", "{": "}"}
stack = []
expr = []
endchar = None
while True:
try:
c, e = self.rule_anything()
endchar = c
except ParseError as err:
e = err
endchar = None
break
if c in endChars and len(stack) == 0:
self.input = self.input.prev()
break
else:
expr.append(c)
if c in delimiters:
stack.append(delimiters[c])
elif len(stack) > 0 and c == stack[-1]:
stack.pop()
elif c in delimiters.values():
raise ParseError(self.input.data, self.input.position,
expected("Python expression"))
elif c in "\"'":
while True:
strc, stre = self.rule_anything()
expr.append(strc)
slashcount = 0
while strc == '\\':
strc, stre = self.rule_anything()
expr.append(strc)
slashcount += 1
if strc == c and slashcount % 2 == 0:
break
if len(stack) > 0:
raise ParseError(self.input.data, self.input.position,
expected("Python expression"))
return (''.join(expr).strip(), endchar), e
| (self, endChars='\r\n') |
28,497 | ometa.runtime | repeat |
Call C{fn} C{max} times or until it fails to match the
input. Fail if less than C{min} matches were made.
Collect the results into a list.
| def repeat(self, min, max, fn):
"""
Call C{fn} C{max} times or until it fails to match the
input. Fail if less than C{min} matches were made.
Collect the results into a list.
"""
if min == max == 0:
return '', None
ans = []
for i in range(min):
v, e = fn()
ans.append(v)
for i in range(min, max):
try:
m = self.input
v, e = fn()
ans.append(v)
except ParseError as err:
e = err
self.input = m
break
return ans, e
| (self, min, max, fn) |
28,498 | ometa.runtime | ruleValueExpr |
Find and generate code for a Python expression terminated by a close
paren/brace or end of line.
| def ruleValueExpr(self, singleLine, span=None):
"""
Find and generate code for a Python expression terminated by a close
paren/brace or end of line.
"""
(expr, endchar), err = self.pythonExpr(endChars="\r\n)]")
# if str(endchar) in ")]" or (singleLine and endchar):
# self.input = self.input.prev()
return t.Action(expr, span=span)
| (self, singleLine, span=None) |
28,499 | ometa.runtime | rule_anything |
Match a single item from the input of any kind.
| def rule_anything(self):
"""
Match a single item from the input of any kind.
"""
h, p = self.input.head()
self.input = self.input.tail()
return h, p
| (self) |
28,536 | ometa.runtime | token |
Match and return the given string, consuming any preceding whitespace.
| def token(self, tok):
"""
Match and return the given string, consuming any preceding whitespace.
"""
m = self.input
try:
self.eatWhitespace()
for c in tok:
v, e = self.exactly(c)
return tok, e
except ParseError as e:
self.input = m
raise e.withMessage(expected("token", tok))
| (self, tok) |
28,540 | ometa.runtime | semanticActionExpr |
Find and generate code for a Python expression terminated by a
close-paren, whose return value is ignored.
| def semanticActionExpr(self, span=None):
"""
Find and generate code for a Python expression terminated by a
close-paren, whose return value is ignored.
"""
val = t.Action(self.pythonExpr(')')[0][0], span=span)
self.exactly(')')
return val
| (self, span=None) |
28,541 | ometa.runtime | semanticPredicateExpr |
Find and generate code for a Python expression terminated by a
close-paren, whose return value determines the success of the pattern
it's in.
| def semanticPredicateExpr(self, span=None):
"""
Find and generate code for a Python expression terminated by a
close-paren, whose return value determines the success of the pattern
it's in.
"""
expr = t.Action(self.pythonExpr(')')[0][0], span=span)
self.exactly(')')
return t.Predicate(expr, span=span)
| (self, span=None) |
28,542 | ometa.runtime | startSpan | null | def startSpan(self):
self._spanStart = self.input.position
| (self) |
28,543 | ometa.runtime | stringtemplate | null | def stringtemplate(self, template, vals):
output = []
checkIndent = False
currentIndent = ""
for chunk in template.args:
if chunk.tag.name == ".String.":
output.append(chunk.data)
if checkIndent and chunk.data.isspace():
currentIndent = chunk.data
checkIndent = False
if chunk.data.endswith('\n'):
checkIndent = True
elif chunk.tag.name == "QuasiExprHole":
v = vals[chunk.args[0].data]
if not isinstance(v, basestring):
try:
vs = list(v)
except TypeError:
raise TypeError("Only know how to templatize strings and lists of strings")
lines = []
for x in vs:
lines.extend(x.split('\n'))
compacted_lines = []
for line in lines:
if line:
compacted_lines.append(line)
elif compacted_lines:
compacted_lines[-1] = compacted_lines[-1] + '\n'
v = ("\n" + currentIndent).join(compacted_lines)
output.append(v)
else:
raise TypeError("didn't expect %r in string template" % chunk)
return ''.join(output).rstrip('\n'), None
| (self, template, vals) |
28,544 | ometa.runtime | superApply |
Apply the named rule as defined on this object's superclass.
@param ruleName: A rule name.
| def superApply(self, ruleName, *args):
"""
Apply the named rule as defined on this object's superclass.
@param ruleName: A rule name.
"""
r = getattr(super(self.__class__, self), "rule_"+ruleName, None)
if r is not None:
self.input.setMemo(ruleName, None)
return self._apply(r, ruleName, args)
else:
raise NameError("No rule named '%s'" %(ruleName,))
| (self, ruleName, *args) |
28,546 | ometa.runtime | OMetaBase |
Base class providing implementations of the fundamental OMeta
operations. Built-in rules are defined here.
| class OMetaBase(object):
"""
Base class providing implementations of the fundamental OMeta
operations. Built-in rules are defined here.
"""
globals = None
tree = False
def __init__(self, input, globals=None, name='<string>', tree=False,
stream=False):
"""
@param input: The string or input object (if stream=True) to be parsed.
@param globals: A dictionary of names to objects, for use in evaluating
embedded Python expressions.
@param tree: Whether the input should be treated as part of a
tree of nested iterables, rather than being a standalone
string.
@param stream: Whether the input should be treated as an existing
InputStream object.
"""
if stream:
self.input = input
elif self.tree or tree:
self.input = InputStream.fromIterable(input)
else:
self.input = InputStream.fromText(input)
self.locals = {}
if self.globals is None:
if globals is None:
self.globals = {}
else:
self.globals = globals
if basestring is str:
self.globals['basestring'] = str
self.globals['unichr'] = chr
self.currentError = self.input.nullError()
def considerError(self, error, typ=None):
if error:
newPos = error.position
curPos = self.currentError.position
if newPos > curPos:
self.currentError = error
elif newPos == curPos:
self.currentError.mergeWith(error)
def _trace(self, src, span, inputPos):
pass
def superApply(self, ruleName, *args):
"""
Apply the named rule as defined on this object's superclass.
@param ruleName: A rule name.
"""
r = getattr(super(self.__class__, self), "rule_"+ruleName, None)
if r is not None:
self.input.setMemo(ruleName, None)
return self._apply(r, ruleName, args)
else:
raise NameError("No rule named '%s'" %(ruleName,))
def foreignApply(self, grammarName, ruleName, globals_, locals_, *args):
"""
Apply the named rule of a foreign grammar.
@param grammarName: name to look up in locals/globals for grammar
@param ruleName: rule name
"""
grammar = locals_.get(grammarName, None)
if grammar is None:
grammar = globals_[grammarName]
grammar = getattr(grammar, "_grammarClass", grammar)
instance = grammar(self.input, stream=True)
rule = getattr(instance, "rule_" + ruleName, None)
if rule is not None:
self.input.setMemo(ruleName, None)
result = instance._apply(rule, ruleName, args)
self.input = instance.input
return result
else:
raise NameError("No rule named '%s' on grammar '%s'" %
(ruleName, grammarName))
def apply(self, ruleName, *args):
"""
Apply the named rule, optionally with some arguments.
@param ruleName: A rule name.
"""
r = getattr(self, "rule_"+ruleName, None)
if r is not None:
val, err = self._apply(r, ruleName, args)
return val, err
else:
raise NameError("No rule named '%s'" %(ruleName,))
def _apply(self, rule, ruleName, args):
"""
Apply a rule method to some args.
@param rule: A method of this object.
@param ruleName: The name of the rule invoked.
@param args: A sequence of arguments to it.
"""
if args:
if basestring is str:
attrname = '__code__'
else:
attrname = 'func_code'
if ((not getattr(rule, attrname, None))
or getattr(rule, attrname).co_argcount - 1 != len(args)):
for arg in args[::-1]:
self.input = ArgInput(arg, self.input)
return rule()
else:
return rule(*args)
memoRec = self.input.getMemo(ruleName)
if memoRec is None:
oldPosition = self.input
lr = LeftRecursion()
memoRec = self.input.setMemo(ruleName, lr)
try:
memoRec = self.input.setMemo(ruleName,
[rule(), self.input])
except ParseError as e:
e.trail.append(ruleName)
raise
if lr.detected:
sentinel = self.input
while True:
try:
self.input = oldPosition
ans = rule()
if (self.input == sentinel):
break
memoRec = oldPosition.setMemo(ruleName,
[ans, self.input])
except ParseError:
break
self.input = oldPosition
elif isinstance(memoRec, LeftRecursion):
memoRec.detected = True
raise self.input.nullError()
self.input = memoRec[1]
return memoRec[0]
def exactly(self, wanted):
"""
Match a single item from the input equal to the given
specimen, or a sequence of characters if the input is string.
@param wanted: What to match.
"""
i = self.input
if not self.tree and len(wanted) > 1:
val, p, self.input = self.input.slice(len(wanted))
else:
val, p = self.input.head()
self.input = self.input.tail()
if wanted == val:
return val, p
else:
self.input = i
raise p.withMessage(expected(None, wanted))
def many(self, fn, *initial):
"""
Call C{fn} until it fails to match the input. Collect the resulting
values into a list.
@param fn: A callable of no arguments.
@param initial: Initial values to populate the returned list with.
"""
ans = []
for x, e in initial:
ans.append(x)
while True:
try:
m = self.input
v, _ = fn()
ans.append(v)
except ParseError as err:
e = err
self.input = m
break
return ans, e
def repeat(self, min, max, fn):
"""
Call C{fn} C{max} times or until it fails to match the
input. Fail if less than C{min} matches were made.
Collect the results into a list.
"""
if min == max == 0:
return '', None
ans = []
for i in range(min):
v, e = fn()
ans.append(v)
for i in range(min, max):
try:
m = self.input
v, e = fn()
ans.append(v)
except ParseError as err:
e = err
self.input = m
break
return ans, e
def _or(self, fns):
"""
Call each of a list of functions in sequence until one succeeds,
rewinding the input between each.
@param fns: A list of no-argument callables.
"""
errors = []
for f in fns:
try:
m = self.input
ret, err = f()
errors.append(err)
return ret, joinErrors(errors)
except ParseError as e:
errors.append(e)
self.input = m
raise joinErrors(errors)
def _not(self, fn):
"""
Call the given function. Raise ParseError iff it does not.
@param fn: A callable of no arguments.
"""
m = self.input
try:
fn()
except ParseError:
self.input = m
return True, self.input.nullError()
else:
raise self.input.nullError()
def eatWhitespace(self):
"""
Consume input until a non-whitespace character is reached.
"""
while True:
try:
c, e = self.input.head()
except EOFError as err:
e = err
break
tl = self.input.tail()
if c.isspace():
self.input = tl
else:
break
return True, e
def pred(self, expr):
"""
Call the given function, raising ParseError if it returns false.
@param expr: A callable of no arguments.
"""
val, e = expr()
if not val:
raise e
else:
return True, e
def listpattern(self, expr):
"""
Call the given function, treating the next object on the stack as an
iterable to be used for input.
@param expr: A callable of no arguments.
"""
v, e = self.rule_anything()
oldInput = self.input
try:
self.input = InputStream.fromIterable(v)
except TypeError:
raise e.withMessage(expected("an iterable"))
expr()
self.end()
self.input = oldInput
return v, e
def consumedby(self, expr):
oldInput = self.input
_, e = expr()
slice = oldInput.data[oldInput.position:self.input.position]
return slice, e
def stringtemplate(self, template, vals):
output = []
checkIndent = False
currentIndent = ""
for chunk in template.args:
if chunk.tag.name == ".String.":
output.append(chunk.data)
if checkIndent and chunk.data.isspace():
currentIndent = chunk.data
checkIndent = False
if chunk.data.endswith('\n'):
checkIndent = True
elif chunk.tag.name == "QuasiExprHole":
v = vals[chunk.args[0].data]
if not isinstance(v, basestring):
try:
vs = list(v)
except TypeError:
raise TypeError("Only know how to templatize strings and lists of strings")
lines = []
for x in vs:
lines.extend(x.split('\n'))
compacted_lines = []
for line in lines:
if line:
compacted_lines.append(line)
elif compacted_lines:
compacted_lines[-1] = compacted_lines[-1] + '\n'
v = ("\n" + currentIndent).join(compacted_lines)
output.append(v)
else:
raise TypeError("didn't expect %r in string template" % chunk)
return ''.join(output).rstrip('\n'), None
def end(self):
"""
Match the end of the stream.
"""
return self._not(self.rule_anything)
def lookahead(self, f):
"""
Execute the given callable, rewinding the stream no matter whether it
returns successfully or not.
@param f: A callable of no arguments.
"""
try:
m = self.input
x = f()
return x
finally:
self.input = m
def token(self, tok):
"""
Match and return the given string, consuming any preceding whitespace.
"""
m = self.input
try:
self.eatWhitespace()
for c in tok:
v, e = self.exactly(c)
return tok, e
except ParseError as e:
self.input = m
raise e.withMessage(expected("token", tok))
def label(self, foo, label):
"""
Wrap a function and add label to expected message.
"""
try:
val, err = foo()
err2 = err.withMessage([("Custom Exception:", label, None)])
if self.currentError == err:
self.currentError = err2
return val, err2
except ParseError as e:
raise e.withMessage([("Custom Exception:", label, None)])
def letter(self):
"""
Match a single letter.
"""
x, e = self.rule_anything()
if x.isalpha():
return x, e
else:
raise e.withMessage(expected("letter"))
def letterOrDigit(self):
"""
Match a single alphanumeric character.
"""
x, e = self.rule_anything()
if x.isalnum():
return x, e
else:
raise e.withMessage(expected("letter or digit"))
def digit(self):
"""
Match a single digit.
"""
x, e = self.rule_anything()
if x.isdigit():
return x, e
else:
raise e.withMessage(expected("digit"))
rule_digit = digit
rule_letterOrDigit = letterOrDigit
rule_letter = letter
rule_end = end
rule_ws = eatWhitespace
rule_exactly = exactly
#Deprecated.
rule_spaces = eatWhitespace
rule_token = token
def rule_anything(self):
"""
Match a single item from the input of any kind.
"""
h, p = self.input.head()
self.input = self.input.tail()
return h, p
| (input, globals=None, name='<string>', tree=False, stream=False) |
28,547 | ometa.runtime | __init__ |
@param input: The string or input object (if stream=True) to be parsed.
@param globals: A dictionary of names to objects, for use in evaluating
embedded Python expressions.
@param tree: Whether the input should be treated as part of a
tree of nested iterables, rather than being a standalone
string.
@param stream: Whether the input should be treated as an existing
InputStream object.
| def __init__(self, input, globals=None, name='<string>', tree=False,
stream=False):
"""
@param input: The string or input object (if stream=True) to be parsed.
@param globals: A dictionary of names to objects, for use in evaluating
embedded Python expressions.
@param tree: Whether the input should be treated as part of a
tree of nested iterables, rather than being a standalone
string.
@param stream: Whether the input should be treated as an existing
InputStream object.
"""
if stream:
self.input = input
elif self.tree or tree:
self.input = InputStream.fromIterable(input)
else:
self.input = InputStream.fromText(input)
self.locals = {}
if self.globals is None:
if globals is None:
self.globals = {}
else:
self.globals = globals
if basestring is str:
self.globals['basestring'] = str
self.globals['unichr'] = chr
self.currentError = self.input.nullError()
| (self, input, globals=None, name='<string>', tree=False, stream=False) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.