code stringlengths 17 6.64M |
|---|
class PoisonOnly(CPSelectMixin, SMTPoison):
pass
|
class PLDI2015(BaseSMTEncoder):
'Preserve the encoding of Alive as of the original Alive paper.\n '
pass
|
class LLVM4Mixin(BaseSMTEncoder):
'Prior to LLVM 5.0, shifts returned undefined values when the shift amount\n exceeded the bit-width.\n '
|
def shift_op(op, poisons):
def _(term, smt):
x = smt.eval(term.x)
y = smt.eval(term.y)
z = smt._conditional_value([z3.ULT(y, y.size())], op(x, y), term.name)
for f in poisons:
if smt.has_analysis(f, term):
smt.add_nonpoison(z3.Implies(smt.get_analysis(f... |
class SMTUndef_LLVM4(LLVM4Mixin, SMTUndef):
pass
|
class SMTPoison_LLVM4(LLVM4Mixin, SMTPoison):
pass
|
class NewShlMixin(LLVM4Mixin):
pass
|
class SMTPoisonNewShl(NewShlMixin, SMTPoison):
pass
|
class SMTUndefNewShl(NewShlMixin, SMTUndef):
pass
|
class FPImpreciseUndef(SMTUndef):
pass
|
class OldNSZ(BaseSMTEncoder):
def _float_binary_operator(self, term, op):
x = self.eval(term.x)
y = self.eval(term.y)
if ('nnan' in term.flags):
self.add_defs(z3.Not(z3.fpIsNaN(x)), z3.Not(z3.fpIsNaN(y)), z3.Not(z3.fpIsNaN(op(x, y))))
if ('ninf' in term.flags):
... |
class BrokenNSZ(BaseSMTEncoder):
def _float_binary_operator(self, term, op):
x = self.eval(term.x)
y = self.eval(term.y)
if ('nnan' in term.flags):
self.add_defs(z3.Not(z3.fpIsNaN(x)), z3.Not(z3.fpIsNaN(y)), z3.Not(z3.fpIsNaN(op(x, y))))
if ('ninf' in term.flags):
... |
def read_opt_files(files, filter=None, extended_results=False):
'Parse and iterate optimizations given in files.\n\n files - iterable of open files or strings\n filter - selects which optimizations to return, None means return all\n extended_results\n - if True, returns any features provided with the ... |
def all_of(*preds):
preds = filter(None, preds)
if (len(preds) == 0):
return None
if (len(preds) == 1):
return preds[0]
return (lambda opt: all((p(opt) for p in preds)))
|
def any_of(*preds):
preds = filter(None, preds)
if (len(preds) == 1):
return preds[0]
return (lambda opt: any((p(opt) for p in preds)))
|
def contains_node(cls):
return (lambda opt: any((isinstance(t, cls) for t in opt.subterms())))
|
def match_name(pattern):
if (pattern is None):
return None
try:
regex = re.compile(pattern)
return (lambda opt: regex.search(opt.name))
except re.error as e:
raise Error('Invalid pattern: {}'.format(e))
|
class Transform(pretty.PrettyRepr):
def __init__(self, src, tgt, pre=(), asm=(), name=''):
self.name = name
self.pre = pre
self.asm = asm
self.src = src
self.tgt = tgt
def pretty(self):
return pretty.pfun(type(self).__name__, (self.src, self.tgt, self.pre, sel... |
@format_doc.register(Transform)
def _(opt, fmt, prec):
return format_parts(opt.name, ([('Assume:', p) for p in opt.asm] + [('Pre:', p) for p in opt.pre]), opt.src, opt.tgt, fmt)
|
def most_specific(c1, c2):
if (c1 > c2):
(c1, c2) = (c2, c1)
if (c1 == NUMBER):
if (c2 == PTR):
return None
if (c2 == INT_PTR):
return INT
if ((c1 == FLOAT) and (c2 != FLOAT)):
return None
if ((c1 == PTR) and (c2 != PTR)):
return None
... |
def meets_constraint(con, ty):
if (con == BOOL):
return (ty == IntType(1))
return isinstance(ty, _constraint_class[con])
|
class TypeConstraints(object):
logger = logger.getChild('TypeConstraints')
def __init__(self):
self.sets = disjoint.DisjointSubsets()
self.specifics = {}
self.constraints = collections.defaultdict((lambda : FIRST_CLASS))
self.ordering = set()
self.width_equalities = se... |
class TypeEnvironment(object):
'Contains the constraints gathered during type checking.\n '
pointer_width = 64
float_tys = (HalfType(), SingleType(), DoubleType())
def __init__(self, vars, constraint, specific, min_width, lower_bounds, upper_bounds, width_equality, default_id):
self.vars = v... |
def _name(term):
return Formatter().operand(term)
|
class TypeModel(object):
'Maps values to types for a specific context (e.g., a transformation).\n\n Usually generated from a TypeModel.\n '
def __init__(self, environment, types):
self.environment = environment
self.types = types
def __getitem__(self, key):
return self.types[se... |
class _EnvironmentExtender(TypeConstraints):
'Used by TypeEnvironment.extend.\n '
logger = logger.getChild('_EnvironmentExtender')
def __init__(self, environment, **kws):
self.environment = environment
self.tyvar_reps = ([None] * environment.tyvars)
self.rep_tyvar = {}
su... |
class Validator(object):
"Compare type constraints for a term against a supplied type vector.\n\n Usage:\n given a TypeEnvironment e, a type vector v, and a term t,\n\n > t.type_constraints(Validator(e,v))\n\n will return None for success and raise an Error if the term's constraints\n are not met.\n ... |
class Error(error.Error):
pass
|
class NegatableFlag(argparse.Action):
"Action type for paired Boolean flags, e.g., '--spam'/'--no-spam'.\n\n This is an alternative to specifying two separate options with a common\n dest and opposite storage actions. If --spam and --no-spam occur in the\n argument list, the last one wins.\n\n Usage:\n par... |
class DisjointSubsets(object):
'\n Stores values in one or more subsets. Each value exists in only one\n subset at a time. Subsets may be unified.\n '
def __init__(self):
self._parent = {}
self._subset = {}
def __contains__(self, key):
return (key in self._parent)
def key... |
class Tag(pretty.PrettyRepr):
'Subclasses of Tag may be used to label objects, so that they\n may be added to sets or DisjointSubsets multiple times.'
def __init__(self, value):
self.val = value
def __eq__(self, other):
return ((type(self) == type(other)) and (self.val == other.val))
... |
def singledispatch(default):
registry = {object: default}
def dispatch(cls):
for k in cls.mro():
if (k in registry):
return registry[k]
raise NotImplementedError
def register(cls, fun=None):
if (fun is None):
return (lambda f: register(cls,... |
def _lookup2(cls1, cls2, registry):
'\n Find the most specific implementation for (cls1,cls2) in registry.\n \n A more specific superclass of cls1 beats a more specific superclass\n of cls2.\n '
for k1 in cls1.mro():
for k2 in cls2.mro():
if ((k1, k2) in registry):
ret... |
def doubledispatch(default):
'\n Create a multimethod which dispatches on the first two arguments.\n '
registry = {(object, object): default}
cache = {}
def dispatch(cls1, cls2):
try:
return cache[(cls1, cls2)]
except KeyError:
fun = _lookup2(cls1, cls2, regi... |
def iter_seq(doc_it):
docs = tuple(doc_it)
return (text(docs[0]) if (len(docs) == 1) else _Seq(docs))
|
def seq(*docs):
return iter_seq(docs)
|
def group(*docs):
doc = (text(docs[0]) if (len(docs) == 1) else iter_seq(docs))
if (isinstance(doc, _Group) or (not bool(doc))):
return doc
return _Group(doc)
|
def text(string):
'Converts a string to a Doc.\n\n Docs are passed through unchanged. Other objects are passed to prepr.\n '
if isinstance(string, Doc):
return string
if isinstance(string, str):
return _Text(string)
return prepr(string)
|
def prepr(obj):
'Converts an object to a Doc, similar to repr.\n\n prepr(obj) -> obj.pretty(), if obj has a member pretty.\n prepr(obj) special-cases tuples, lists, dicts, sets, and frozensets.\n prepr(obj) -> text(repr(obj)) for all other objects\n '
if hasattr(obj, 'pretty'):
return _Pretty(obj)... |
def pprint(*objs, **kws):
"Pretty-print specified objects.\n\n pprint(*objs, file=sys.stdout, sep=line, end='\n', grouped=True, first=True,\n indent=0, prefix='', **kws)\n\n Keywords:\n file - where to write the objects\n sep - a Doc output between objects\n end - a string written af... |
def pformat(*objs, **kws):
"Return a string containing the pretty-printed objects.\n\n pformat(*objs, sep=line, end='', **kws)\n\n Keywords:\n sep - a Doc output between objects\n end - a string written after any objs have been written\n width - desired maximum width\n indent - indentatio... |
class PrettyRepr(object):
'Mixin class for objects which can pretty-print their representation.\n '
def pretty(self):
'Return a Doc representing the object.'
return text(super(PrettyRepr, self).__repr__())
def __repr__(self):
return self.pretty().oneline()
def pprint(self, ... |
class Doc(PrettyRepr):
'The intermediate formatting tree generated during pretty printing.\n\n Use text, prepr, group, seq, line, lbreak, and others to create Docs.\n\n Combine Docs with +, or use | to put a line between them.\n '
__slots__ = ()
(Text, Line, Break, GBegin, GEnd) = range(5)
def __a... |
class _Text(Doc):
__slots__ = ('text',)
def __init__(self, text):
assert ('\n' not in text)
self.text = text
def send_to(self, out, indent):
out.send((Doc.Text, self.text))
def __nonzero__(self):
return bool(self.text)
|
class _Line(Doc):
__slots__ = ()
def send_to(self, out, indent):
out.send((Doc.Line, indent))
def __repr__(self):
return '_Line()'
|
class _Break(Doc):
__slots__ = ()
def send_to(self, out, indent):
out.send((Doc.Break, indent))
def __repr__(self):
return '_Break()'
def __nonzero__(self):
return False
|
class _Group(Doc):
__slots__ = ('doc',)
def __init__(self, doc):
assert bool(doc)
self.doc = doc
def send_to(self, out, indent):
out.send((Doc.GBegin,))
self.doc.send_to(out, indent)
out.send((Doc.GEnd,))
|
class _Seq(Doc):
__slots__ = ('docs',)
def __init__(self, docs):
self.docs = docs
def send_to(self, out, indent):
for doc in self.docs:
text(doc).send_to(out, indent)
def __nonzero__(self):
return any((bool(doc) for doc in self.docs))
|
class _Nest(Doc):
__slots__ = ('indent', 'doc')
def __init__(self, indent, doc):
self.indent = indent
self.doc = doc
def send_to(self, out, indent):
self.doc.send_to(out, (indent + self.indent))
def __nonzero__(self):
return bool(self.doc)
|
class _Pretty(Doc):
__slots__ = ('obj',)
def __init__(self, obj):
self.obj = obj
def send_to(self, out, indent):
self.obj.pretty().send_to(out, indent)
|
def joinit(iterable, delimiter):
it = iter(iterable)
(yield next(it))
for x in it:
(yield delimiter)
(yield x)
|
def grow_groups(next):
'Delays GEnd event until the next Line or Break.\n\n If a group is immediately followed by trailing text, we should take it\n into account when choosing whether to break the group. This stream\n transformer pushes GEnds past any trailing text.\n\n Furthermore, since GBegin can always be... |
def add_hp(next):
'Annotate events with their horizontal position.\n\n Assuming an infinitely-wide canvas, how many characters to the right is the\n _end_ of this event.\n '
next.next()
pos = 0
while True:
event = (yield)
if (event[0] == Doc.Text):
pos += len(event[1])
... |
class Buf(object):
'Sequence type providing O(1) insert at either end, and O(1) concatenation.\n '
def __init__(self):
self.head = []
self.tail = self.head
def append_left(self, item):
self.head = [item, self.head]
def append(self, item):
last = self.tail
se... |
def add_GBegin_pos(next):
'Annotate GBegin events with the horizontal position of the end of the\n group.\n\n Because this waits until the entire group has been seen, so its latency and\n memory use are unbounded.\n '
next.next()
bufs = []
while True:
event = (yield)
if (event[0] =... |
def find_group_ends(width, next):
"Annotate GBegin events with the horizontal position of the end of the\n group.\n\n GBegins corresponding to groups larger than the width will be annotated with\n 'None'. This keeps memory usage and latency bounded, at the cost of some\n potential inaccuracy. (Zero-width grou... |
def text_events(width, out, prefix='', start_at=0):
'Write an annotated event stream to some method.\n\n Arguments:\n width - Desired maximum width for printing\n out - A function which accepts strings (e.g. sys.stdout.write)\n Keywords:\n prefix - A string to put the start of each subsequent line. T... |
def nest(indent, doc):
return _Nest(indent, doc)
|
def pfun(name, args, indent=2):
args = tuple((prepr(a) for a in args))
if (len(args) == 0):
return seq(name, '()')
return group(name, '(', lbreak, commaline.join(args), ')').nest(indent)
|
def pfun_(name, args):
if (len(args) == 0):
return seq(name, '()')
return group(name, '(', commaline.join(args), ')').nest((len(name) + 1))
|
def pdict(dict):
return group('{', commaline.join((group(prepr(k), ':', line, prepr(v)).nest(2) for (k, v) in dict.iteritems())), '}').nest(1)
|
def plist(list):
return group('[', commaline.join((prepr(v) for v in list)), ']').nest(1)
|
def ptuple(tup):
if (len(tup) == 0):
return text('()')
if (len(tup) == 1):
return group('(', prepr(tup[0]), ',)').nest(1)
return group('(', commaline.join((prepr(v) for v in tup)), ')').nest(1)
|
def pset(set):
nm = type(set).__name__
return seq(nm, '(', plist(sorted(set)), ')').nest((len(nm) + 1))
|
def block_print(obj, width=80):
def blk(next):
next.next()
try:
while True:
event = (yield)
if ((event[0] == Doc.Line) or (event[0] == Doc.Break)):
next.send((Doc.GBegin,))
next.send((event[0], 0))
... |
def mk_and(clauses):
'mk_and([p,q,r]) -> And(p,q,r)'
if (len(clauses) == 1):
return clauses[0]
if (len(clauses) == 0):
return z3.BoolVal(True)
return z3.And(clauses)
|
def mk_or(clauses):
'mk_or([p,q,r]) -> Or(p,q,r)'
if (len(clauses) == 1):
return clauses[0]
if (len(clauses) == 0):
return z3.BoolVal(False)
return z3.Or(clauses)
|
def mk_not(clauses):
'mk_not([p,q,r]) -> Not(And(p,q,r))'
if (len(clauses) == 1):
return z3.Not(clauses[0])
if (len(clauses) == 0):
return z3.BoolVal(False)
return z3.Not(z3.And(clauses))
|
def mk_forall(qvars, clauses):
'mk_forall(vs, [p,q,r]) -> ForAll(vs, And(p,q,r))'
if (len(qvars) == 0):
return mk_and(clauses)
return z3.ForAll(qvars, mk_and(clauses))
|
def bool_to_BitVec(b):
return z3.If(b, z3.BitVecVal(1, 1), z3.BitVecVal(0, 1))
|
def bv_log2(bitwidth, v):
def rec(h, l):
if (h <= l):
return z3.BitVecVal(l, bitwidth)
mid = (l + int(((h - l) / 2)))
return z3.If((z3.Extract(h, (mid + 1), v) != 0), rec(h, (mid + 1)), rec(mid, l))
return rec((v.size() - 1), 0)
|
def zext_or_trunc(v, src, tgt):
if (tgt == src):
return v
if (tgt > src):
return z3.ZeroExt((tgt - src), v)
return z3.Extract((tgt - 1), 0, v)
|
def ctlz(output_width, v):
size = v.size()
def rec(i):
if (i < 0):
return z3.BitVecVal(size, output_width)
return z3.If((z3.Extract(i, i, v) == z3.BitVecVal(1, 1)), z3.BitVecVal(((size - 1) - i), output_width), rec((i - 1)))
return rec((size - 1))
|
def cttz(output_width, v):
size = v.size()
def rec(i):
if (i == size):
return z3.BitVecVal(size, output_width)
return z3.If((z3.Extract(i, i, v) == z3.BitVecVal(1, 1)), z3.BitVecVal(i, output_width), rec((i + 1)))
return rec(0)
|
def ComputeNumSignBits(bitwidth, v):
size = v.size()
size1 = (size - 1)
sign = z3.Extract(size1, size1, v)
def rec(i):
if (i < 0):
return z3.BitVecVal(size, bitwidth)
return z3.If((z3.Extract(i, i, v) == sign), rec((i - 1)), z3.BitVecVal((size1 - i), bitwidth))
return ... |
def fpUEQ(x, y):
return z3.Or(z3.fpEQ(x, y), z3.fpIsNaN(x), z3.fpIsNaN(y))
|
def detect_fpMod():
"Determine whether Z3's fpRem is correct, and set fpMod accordingly.\n "
import logging
log = logging.getLogger(__name__)
log.debug('Setting fpMod')
if z3.is_true(z3.simplify(((z3.FPVal(3, z3.Float32()) % 2) < 0))):
log.debug('Correct fpRem detected')
fpMod.__c... |
def fpMod(x, y, ctx=None):
detect_fpMod()
return fpMod(x, y, ctx)
|
def fpMod_using_fpRem(x, y, ctx=None):
y = z3.fpAbs(y)
z = z3.fpRem(z3.fpAbs(x), y, ctx)
r = z3.If(z3.fpIsNegative(z), (z + y), z, ctx)
return z3.If(z3.Not((z3.fpIsNegative(x) == z3.fpIsNegative(r)), ctx), z3.fpNeg(r), r, ctx)
|
def fpRem_trampoline(x, y, ctx=None):
return z3.fpRem(x, y)
|
def _xml_escape(data):
'Escape &, <, >, ", \', etc. in a string of data.'
from_symbols = '&><"\''
to_symbols = ((('&' + s) + ';') for s in 'amp gt lt quot apos'.split())
for (from_, to_) in zip(from_symbols, to_symbols):
data = data.replace(from_, to_)
return data
|
class _Constants(object):
pass
|
class ParseBaseException(Exception):
'base exception class for all parsing runtime exceptions'
def __init__(self, pstr, loc=0, msg=None, elem=None):
self.loc = loc
if (msg is None):
self.msg = pstr
self.pstr = ''
else:
self.msg = msg
sel... |
class ParseException(ParseBaseException):
"exception thrown when parse expressions don't match class;\n supported attributes by name are:\n - lineno - returns the line number of the exception text\n - col - returns the column number of the exception text\n - line - returns the line cont... |
class ParseFatalException(ParseBaseException):
'user-throwable exception thrown when inconsistent parse content\n is found; stops all parsing immediately'
pass
|
class ParseSyntaxException(ParseFatalException):
"just like C{L{ParseFatalException}}, but thrown internally when an\n C{L{ErrorStop<And._ErrorStop>}} ('-' operator) indicates that parsing is to stop immediately because\n an unbacktrackable syntax error has been found"
def __init__(self, pe):
... |
class RecursiveGrammarException(Exception):
'exception thrown by C{validate()} if the grammar could be improperly recursive'
def __init__(self, parseElementList):
self.parseElementTrace = parseElementList
def __str__(self):
return ('RecursiveGrammarException: %s' % self.parseElementTrace... |
class _ParseResultsWithOffset(object):
def __init__(self, p1, p2):
self.tup = (p1, p2)
def __getitem__(self, i):
return self.tup[i]
def __repr__(self):
return repr(self.tup)
def setOffset(self, i):
self.tup = (self.tup[0], i)
|
class ParseResults(object):
'Structured parse results, to provide multiple means of access to the parsed data:\n - as a list (C{len(results)})\n - by list index (C{results[0], results[1]}, etc.)\n - by attribute (C{results.<resultsName>})\n '
def __new__(cls, toklist, name=None, asLis... |
def col(loc, strg):
'Returns current column within a string, counting newlines as line separators.\n The first column is number 1.\n\n Note: the default parsing behavior is to expand tabs in the input string\n before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString... |
def lineno(loc, strg):
'Returns current line number within a string, counting newlines as line separators.\n The first line is number 1.\n\n Note: the default parsing behavior is to expand tabs in the input string\n before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parse... |
def line(loc, strg):
'Returns the line of text containing loc within a string, counting newlines as line separators.\n '
lastCR = strg.rfind('\n', 0, loc)
nextCR = strg.find('\n', loc)
if (nextCR >= 0):
return strg[(lastCR + 1):nextCR]
else:
return strg[(lastCR + 1):]
|
def _defaultStartDebugAction(instring, loc, expr):
print((((('Match ' + _ustr(expr)) + ' at loc ') + _ustr(loc)) + ('(%d,%d)' % (lineno(loc, instring), col(loc, instring)))))
|
def _defaultSuccessDebugAction(instring, startloc, endloc, expr, toks):
print(((('Matched ' + _ustr(expr)) + ' -> ') + str(toks.asList())))
|
def _defaultExceptionDebugAction(instring, loc, expr, exc):
print(('Exception raised:' + _ustr(exc)))
|
def nullDebugAction(*args):
"'Do-nothing' debug action, to suppress debugging output during parsing."
pass
|
def _trim_arity(func, maxargs=2):
if (func in singleArgBuiltins):
return (lambda s, l, t: func(t))
limit = [0]
foundArity = [False]
def wrapper(*args):
while 1:
try:
ret = func(*args[limit[0]:])
foundArity[0] = True
return re... |
class ParserElement(object):
'Abstract base level parser element class.'
DEFAULT_WHITE_CHARS = ' \n\t\r'
verbose_stacktrace = False
def setDefaultWhitespaceChars(chars):
'Overrides the default whitespace chars\n '
ParserElement.DEFAULT_WHITE_CHARS = chars
setDefaultWhitespa... |
class Token(ParserElement):
'Abstract C{ParserElement} subclass, for defining atomic matching patterns.'
def __init__(self):
super(Token, self).__init__(savelist=False)
def setName(self, name):
s = super(Token, self).setName(name)
self.errmsg = ('Expected ' + self.name)
r... |
class Empty(Token):
'An empty token, will always match.'
def __init__(self):
super(Empty, self).__init__()
self.name = 'Empty'
self.mayReturnEmpty = True
self.mayIndexError = False
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.