示例#1
0
 def times(self, a, b, prod):
     """Like Prolog times; at most one argument may be a variable,
     if none are checks whether prod=a+b, else binds the variable
     accordingly.
     """
     if (a.is_var() and (b.is_var() or prod.is_var())) or (b.is_var() and prod.is_var()):
         return Errors(self, ["Only one variable allowed in times."])
     if ((not (a.is_var() or a.is_numconst()))
         or (not (b.is_var() or b.is_numconst()))
         or (not (prod.is_var() or prod.is_numconst()))):
         return Errors(self, ["times expects numbers"])
     if a.is_var():
         if b.num == 0:
             return Errors(self, ["times: divide by 0 not allowed"])
         else:
             return Substitutions(self, [self.bindResult(a, prod.num / b.num)])
     elif b.is_var():
         if a.num == 0:
             return Errors(self, ["times: divide by 0 not allowed"])
         else:
             return Substitutions(self, [self.bindResult(b, prod.num / a.num)])
     elif prod.is_var():
         return Substitutions(self, [self.bindResult(prod, a.num * b.num)])
     else:
         res = prod.num == a.num * b.num
         return Success(self) if res else Failure(self)
示例#2
0
 def equal(self, a, b):
     """Unify the two terms"""
     if b.is_var():
         if a.is_var():
             return Failure(self)
         subst = a.unify(b)
         return Failure(self) if subst is None else Substitutions(self, [subst])
     if a.is_var():
         subst = b.unify(a)
         return Failure(self) if subst is None else Substitutions(self, [subst])
     elif a.val == b.val:
         return Success(self) 
     else:
         return Failure(self) 
示例#3
0
 def yicesAssert(self, sessionIn, formula, sessionOut):
     ''' Assert formula into a logical context.  Input has to be in
     yices format.  '''
     print('yicesAssert: entry')
     command = '(assert %s)' % formula
     result = self.yices_command(sessionIn, command)
     return Substitutions(self, [{sessionOut: mk_term(result)}])
示例#4
0
 def now(self, tok):
     """Binds the argument to the current unix timestamp
     (of this computer)"""
     if tok.is_var():
         return Substitutions(self, [{tok: terms.StringConst(time.time())}])
     else:
         return Failure(self)
示例#5
0
 def cons(self, head, tail, out):
     """Create the cons of head to tail bound to variable out"""
     if tail.is_const() and tail.val is None:
         res = [head]
     else:
         res = [head.val] + list(tail.get_args())
     return Substitutions(self, [ self.bindResult(out, res)])
示例#6
0
 def find_theorems(self, sal_file, thm_file):
     self.log.info('find_theorems: sal_file = {0}'.format(sal_file))
     (s, out, err) = self.callTool('grep', 'theorem', sal_file['file'])
     with open('theorems', 'w') as f:
         f.write(out)
     thm_file_ref = self.fs.put_file('theorems')
     return Substitutions(self, [self.bindResult(thm_file, thm_file_ref)])
示例#7
0
 def remove_cr(self, inf, outname, outf):
     with open(inf['file']) as infh:
         with open(outname.val, 'wb') as outfh:
             for line in infh:
                 line = line.rstrip()
                 outfh.write(line + '\n')
     outfref = self.fs.put_file(outname.val)
     return Substitutions(self, [ self.bindResult(outf, outfref) ])
示例#8
0
 def yicesInconsistent(self, sessionIn, result):
     ''' Passively checks consistency of the context.  Only makes sense
     when preceded by a call to yicesCheck.  It returns the result as a string.'''
     print('yicesInconsistent: entry')
     sid = self.session_id(sessionIn)
     s_entry = self.session(sid)
     mgr = s_entry['manager']
     out = mgr.yices_inconsistent()
     return Substitutions(self, [{result: mk_term(out)}])
示例#9
0
 def popen(self, cmd, result):
     """Runs a shell command and get the (text) result back."""
     if not cmd.is_array():
         return Failure(self)  # TODO error claims
     cmd = list(unicode(x) for x in cmd.get_args())
     try:
         shell_res = subprocess.check_output(cmd)
         return Substitutions(self, [{result: terms.StringConst(shell_res)}])
     except subprocess.CalledProcessError as e:
         return Failure(self)  # TODO error claims
示例#10
0
 def plus(self, a, b, sum):
     """Like Prolog sum; at most one argument may be a variable,
     if none are checks whether sum=a+b, else binds the variable
     accordingly.
     """
     if (a.is_var() and (b.is_var() or sum.is_var())) or (b.is_var() and sum.is_var()):
         return Errors(self, ["Only one variable allowed in plus."])
     if ((not (a.is_var() or a.is_numconst()))
         or (not (b.is_var() or b.is_numconst()))
         or (not (sum.is_var() or sum.is_numconst()))):
         return Errors(self, ["plus expects numbers"])
     if a.is_var():
         return Substitutions(self, [self.bindResult(a, sum.num - b.num)])
     elif b.is_var():
         return Substitutions(self, [self.bindResult(b, sum.num - a.num)])
     elif sum.is_var():
         return Substitutions(self, [self.bindResult(sum, a.num + b.num)])
     else:
         res = sum.num == a.num + b.num
         return Success(self) if res else Failure(self)
示例#11
0
 def gcc_compile(self, src, deps, obj):
     dst = os.path.splitext(src['file'])[0] + '.o'
     env = os.environ
     env['LC_ALL'] = 'C'
     env['LANG'] = 'C'
     (ret, _, err) = self.callTool('gcc', '-c', '-o', dst, src['file'], env=env)
     if ret != 0:
         self.log.error(err)
         return Errors(self,  [ err ] )
     objref = self.fs.put_file(dst)
     return Substitutions(self, [ self.bindResult(obj, objref) ])
示例#12
0
 def gcc_link(self, ofiles, exename, exe):
     filenames = [ r['file'] for r in ofiles ]
     args = [ 'gcc', '-o', exename.val ] + filenames
     env = os.environ
     env['LC_ALL'] = 'C'
     env['LANG'] = 'C'
     (ret, _, err) = self.callTool(*args, env=env)
     if ret != 0:
         self.log.error(err)
         return Errors(self,  [ err ] ) 
     exeref = self.fs.put_file(exename.val)
     return Substitutions(self, [ self.bindResult(exe, exeref) ])
示例#13
0
 def yicesReset(self, sessionIn, sessionOut):
     ''' Reset the logical context.'''
     print('yicesReset: entry')
     sid = self.session_id(sessionIn)
     s_entry = self.session(sid)
     mgr = s_entry['manager']
     result = mgr.yices_reset()
     if result == 0:
         self.fail(mgr.yices_get_last_error_msg())
     else:
         session_out = self.tick(sessionIn)
         return Substitutions(self, [{sessionOut: mk_term(session_out)}])
示例#14
0
 def popen_at(self, cmd, timestamp, result):
     """Runs a shell command and get the (text) result back.  The timestamp
     can be anything, its purpose is to repeat an action that would
     otherwise be cached (like several printf of the same string)
     """
     if not cmd.is_array():
         return Failure(self)  # TODO error claims
     cmd = list(unicode(x) for x in cmd.get_args())
     try:
         shell_res = subprocess.check_output(cmd)
         return Substitutions(self, [{result: terms.StringConst(shell_res)}])
     except subprocess.CalledProcessError as e:
         return Failure(self)  # TODO error claims
示例#15
0
 def yicesStart(self, session):
     """
     Creates a fresh Yices session with session_info initialized so that
     decls is the current list of declarations, unsatcore is the unsatisfiable
     core, assignment is the model, and stack is the length of the decls
     at the point of the more recently scoped push.  
     """
     print('yicesStart: entry')
     sessionOut = self.add_session('yices', {
         'manager': YicesContextManager(),
         'timestamp': 0
     })
     return Substitutions(self, [{session: mk_term(sessionOut)}])
示例#16
0
 def negateModel(self, yices_file, model, out):
     '''
     Create a new yices file containing the input yices files and
     asserting the negation of the model.
     '''
     with tempfile.NamedTemporaryFile(delete=False, dir='.') as oc:
         out_file = os.path.basename(oc.name)
         with open(yices_file['file'], 'r') as ic:
             for line in ic:
                 print >> oc, line
         print >> oc, '(assert (not (and %s)))' % model.val
     outref = self.fs.put_file(out_file)
     return Substitutions(self, [self.bindResult(out, outref)])
示例#17
0
 def yicesCheck(self, sessionIn, sessionOut, result):
     ''' Check consistency of the context.  This method performs a
     satisfiability check.  It returns the result as a string.'''
     print('yicesCheck: entry')
     sid = self.session_id(sessionIn)
     s_entry = self.session(sid)
     mgr = s_entry['manager']
     out = mgr.yices_check()
     newSession = self.tick(sessionIn)
     return Substitutions(self, [{
         sessionOut: mk_term(newSession),
         result: mk_term(out)
     }])
示例#18
0
 def yicesModel(self, sessionIn, model):
     print('yicesModel: entry')
     sid = self.session_id(sessionIn)
     s_entry = self.session(sid)
     mgr = s_entry['manager']
     assignment = mgr.yices_assignment()
     print('assignment: %s' % assignment)
     vars = [var for var in assignment]
     out = ''
     for var in vars:
         out += '(= %s %s)' % (var, assignment[var])
     out = '(and %s)' % out
     print('model %s' % out)
     return Substitutions(self, [{model: mk_term(out)}])
示例#19
0
 def in_range(self, low, up, result):
     """Result in [low, up] range."""
     low = int(low.val)
     up = int(up.val)
     if low > up:
         return Failure(self)
     if result.is_var():
         return Substitutions(
             self, [self.bindResult(result, i) for i in range(low, up + 1)])
         #return Substitutions(self, [{result : etb.terms.mk_const(i)} for i in range(low, up+1)])
     else:
         result = int(result.val)
         if low <= result <= up:
             return Success(self)
         else:
             return Failure(self)
示例#20
0
 def yicesIncludeFile(self, sessionIn, file, sessionOut):
     print('yicesIncludeFile: entry')
     sid = self.session_id(sessionIn)
     print('sid: %s' % sid)
     s_entry = self.session(sid)
     print('s_entry: %s' % s_entry)
     mgr = s_entry['manager']
     print('mgr: %s' % mgr)
     print('file: %s' % file)
     print('filename: %s' % file['file'])
     yid = mgr.yices_include(file['file'])
     print('yid: %s' % yid)
     if yid != 0:
         session_out = self.tick(sessionIn)
         return Substitutions(self, [{sessionOut: mk_term(session_out)}])
     else:
         self.fail(mgr.yices_get_last_error_msg())
示例#21
0
 def match_facts(self, goal, facts):
     """Put in facts the sorted list of facts that match goal."""
     # get the actual list of facts (sorted)
     print goal, facts
     _, goal = goal.negative_rename()  # avoid collisions
     with self._etb.logic_state:
         found_facts = list(subst(goal) for subst in \
                            self._etb.logic_state.match_facts_against(goal))
     print found_facts
     found_facts.sort()
     found_facts = terms.Array(found_facts)
     # bind/check
     if facts.is_var():
         return Substitutions(self, [{ facts: found_facts}])
     elif facts == found_facts:
         return Success(self)
     else:
         return Failure(self)
示例#22
0
 def yices(self, formula, result, model):
     with tempfile.NamedTemporaryFile(delete=False, dir='.') as oc:
         new_file = os.path.basename(oc.name)
         print >> oc, '(include "%s")' % formula['file']
         print >> oc, '(check)'
     (ret, out, err) = self.callTool('yices', '-e', new_file)
     if ret != 0:
         self.log.error(err)
         return Errors(self, ['error("yices", "%s")' % err])
     output = out.split('\n')
     if output[0] == 'sat':
         s = self.bindResult(result, output[0])
         s = self.bindResult(model, ''.join(output[1:]), current=s)
     else:
         s = self.bindResult(result, output[0])
         s = self.bindResult(model, [], current=s)
     if s == []:
         return Failure(self)
     else:
         return Substitutions(self, [s])
示例#23
0
 def yicesPop(sessionIn, sessionOut):
     ''' Remove the top level from the assertion stack.'''
     print('yicesPop: entry')
     result = self.yices_pop(sessionIn)
     return Substitutions(self, [{sessionOut: mk_term(result)}])
示例#24
0
 def yicesPush(self, sessionIn, sessionOut):
     ''' Create a new level on the assertion stack.'''
     print('yicesPush: entry')
     result = self.yices_push(sessionIn)
     return Substitutions(self, [{sessionOut: mk_term(result)}])
示例#25
0
 def yicesDefine(self, sessionIn, var, type, body, sessionOut):
     ''' Define a variable.  "var", "type", and 
     "body" have to be in yices syntax.'''
     print('yicesDefine: entry')
     result = self.yices_define(sessionIn, var, type, body)
     return Substitutions(self, [{sessionOut: mk_term(result)}])
示例#26
0
 def yicesVersion(self, version):
     print('finding version')
     result = libyices.yices_version()
     print('found version')
     return Substitutions(self, [{version: mk_term(result)}])
示例#27
0
 def nil(self, v):
     if v.is_var():
         return Substitutions(self, [{v: mk_term([])}])
     else:
         return Errors(self, ["checking not supported"])
示例#28
0
 def cons(self, head, tail, out):
     if tail.is_const() and tail.val is None:
         res = [head]
     else:
         res = [head.val] + list(tail.get_args())
     return Substitutions(self, [self.bindResult(out, res)])
示例#29
0
 def yicesDeclare(self, sessionIn, var, type, sessionOut):
     ''' Define a variable.  If "body is not "None" the variable
     will become a yices macro.  "var", "type" have to be in yices syntax.'''
     print('yicesDeclare: entry')
     result = self.yices_define(sessionIn, var, type)
     return Substitutions(self, [{sessionOut: mk_term(result)}])
示例#30
0
 def nil(self, v):
     if v.is_var():
         return Substitutions(self, [self.bindResult(v, mk_term([]))])
     else:
         return Errors(self, ["nil passed a non variable: %s" % v])