def apply(self, x): targets = x.get(0) types = x.get(1) if not isinstance(targets, Tuple): return Boolean.create(True) for i in range(targets.size()): idx = min(i, types.size() - 1) con = Tuple([TYPE, Tuple([QUOTE, targets.get(i)]), types.get(idx)]) if not self.evaluator.apply(con).bool_value(): return Boolean.create(False) return Boolean.create(True)
def apply(self, x): matchTuple = x.get(0) zipTerm = x.get(1) sub_f = x.get(2) zipTerm = self.evaluator.apply(zipTerm) zipList = [] for t in zipTerm: zipList.append(t) for i in range(len(zipList) - 1): if len(zipList[i]) != len(zipList[i + 1]): return Boolean.create(False) for i in range(len(zipList[0])): zipArgs = [None] * len(zipList) for j in range(len(zipList)): zipArgs[j] = zipList[j].get(i) zipTuple = Tuple(zipArgs) s = matchTuple.match(zipTuple) if not self.evaluator.apply(sub_f.substitute(s)).bool_value(): return Boolean.create(False) return Boolean.create(True)
def load_def(self, C): for m in C.get_module_names(): for e in C.get_matching_entries(m, DEF, Variable()): if isinstance(e.get_name(), Symbolic): uri = m + e.get_name() f = NamedFunction(uri, e.get_value(), self.functions[fun_uri.EVAL]) # print("Loading:", uri) else: uri = m + e.get_name()[0] args = None if len(e.get_name()) == 2: args = e.get_name()[1] else: arg_list = [] for i in range(1, len(e.get_name())): arg_list.append(e.get_name()[i]) args = Tuple(arg_list) # print("Loading:", uri) f = NamedFunction(uri, e.get_value(), self.functions[fun_uri.EVAL], args=args) self.add_function(uri, f)
def apply(self, args): f = self.evaluator.apply(args[0]).get_function_or_panic() C = self.evaluator.apply(args[1]) current_value = args.get(Reduce.INIT_VAL) for e in C: if current_value is None: current_value = e else: current_value = f.apply(Tuple([current_value, e])) return current_value
def check(self, type_def, term): # Logger.msg("TypeCheck", str(type_def) + " ?? " + str(term)) r = False if isinstance(type_def, Tuple): type_class = type_def[0] if type_class == Symbolic("basic-type"): e = Tuple([type_def[1], term]) r = self.evaluator.apply(e).bool_value() elif type_class == Symbolic("set-of"): subType = type_def.get(1) if isinstance(term, Set): r = True Logger.inc_depth() for e in term: if not self.check(subType, e): #print("---> FAIL") r = False break Logger.dec_depth() else: r = False elif type_class == Symbolic("list-of"): subType = type_def.get(1) if isinstance(term, List): r = True Logger.inc_depth() for e in term: if not self.check(subType, e): r = False break Logger.dec_depth() else: r = False elif type_class == Symbolic("collection-of"): subType = type_def.get(1) if isinstance(t, Collection): r = True Logger.inc_depth() for e in term: if not self.check(subType, e): r = False break Logger.dec_depth() else: r = False elif type_class == Symbolic("signed-tuple"): signature = type_def.get(1) min = type_def.get_or_default(Symbolic("min"), Integer(len(signature))) max = type_def.get_or_default(Symbolic("max"), Integer(len(signature))) repeat = type_def.get_or_default(Symbolic("repeat"), Integer(1)) tSize = Integer(len(type_def)) repeat_start_idx = len(signature) - repeat.int_value() if isinstance(term, Tuple) and tSize >= min and tSize <= max: Logger.inc_depth() r = True for i in range(0, len(signature)): sig_idx = i if i >= signature.size(): sig_idx = repeat_start_idx + \ (i - signature.size()) % repeat.getIntValue() if not self.check(signature.get(sig_idx), term.get(i)): r = False break Logger.dec_depth() else: r = False elif type_class == Symbolic("key-value-tuple"): keyTypeCol = type_def.get(1) r = True Logger.inc_depth() for kvp in keyTypeCol: e = term.get(kvp.get_key()) if e is None: r = False break if not self.check(kvp.get_value(), e): r = False break Logger.dec_depth() elif type_class == Symbolic("enum"): r = term in type_def.get(1) elif type_class == Symbolic("numerical-range"): min = type_def.get_or_default(Symbolic("min"), Infinity.neg()) max = type_def.get_or_default(Symbolic("max"), Infinity.pos()) r = False if isinstance(term, Numerical): if term >= min and term <= max: r = True elif type_class == Symbolic("typed-key-value"): r = False if isinstance(term, KeyValue): if self.check(type_def[1], term.get_key()) and self.check( type_def[1], term.get_value()): r = True elif type_class == Symbolic("or-type"): r = False for choice in type_def[1]: if self.check(choice, term): r = True break else: raise ValueError("#type expression not supported:", type_def) elif isinstance(type_def, Symbolic): e = Tuple([type_def, term]) r = self.evaluator.apply(e).bool_value() else: r = False raise ValueError("#type expression not supported:", type_def) # if not r: # Logger.msg("TypeCheck", str(term) + " !! " + str(type_def)) return r
test_file = test_folder + "example-module.aiddl" C = Container() freg = dfun.get_default_function_registry(C) test_mod = parser.parse(test_file, C, freg, test_folder) e = C.get_entry(Symbolic("a")) assert (e.get_type() == Symbolic("org.aiddl.term.numerical.integer")) assert (e.get_name() == Symbolic("a")) assert (e.get_value() == Integer(1)) E = C.get_matching_entries(Variable("?M"), Variable("?T"), Tuple([Symbolic("X"), Variable("_")])) assert (len(E) == 5) e = Entry(Symbolic("t"), Symbolic("a"), List([Integer(1), Symbolic("x")])) C.set_entry(e, module=test_mod) e_c = C.get_entry(Symbolic("a")) assert (e == e_c) e = C.get_entry(Symbolic("SR")) t_c = Set([Symbolic("c"), Symbolic("d"), Symbolic("e")]) ref = e.get_value() res = C.resolve_reference(ref)
def as_tuple(self): return Tuple([self._type, self._name, self._value])
def parse_string(s, aiddl_paths, freg): str_id = 0 str_lookup = {} bs = False current_str_start = None slices = [] s_new = "" for i in range(len(s)): c = s[i] if c == '"' and not bs and current_str_start is not None: str_lookup[str_id] = s[current_str_start:i] slices.append((current_str_start, i, str(str_id))) s_new += ' "%d"' % (str_id) current_str_start = None str_id += 1 elif c == '"' and not bs: current_str_start = i + 1 elif current_str_start is None: s_new += c if c == '\\': bs = True else: bs = False # for sl in slices: # s = s[:sl[0]] + sl[2] + s[sl[1]:] s = s_new s = re.sub(r";;.*\n", "", s) s = s.replace("\n", " ") s = s.replace("\t", " ") for token in SPECIAL: s = s.replace(token, " " + token + " ") while " " in s: s = s.replace(" ", " ") s = s.strip() stack = [] module_name = None self_ref = None local_refs = {} tokens = s.split(" ") tuple_depth = 0 for token in tokens: token = token.strip() if token == CLIST: assembled_list = [] current = pop(stack) while current != OLIST: assembled_list.append(current) current = pop(stack) assembled_list.reverse() term = List(assembled_list) # push(stack, term) elif token == CTUPLE: tuple_depth -= 1 assembled_list = [] current = pop(stack) while current != OTUPLE: assembled_list.append(current) current = pop(stack) assembled_list.reverse() term = Tuple(assembled_list) # push(stack, term) if tuple_depth == 0: if term.get(0) == MOD: self_ref = term.get(1) module_name = term.get(2) elif term.get(0) == REQ or \ term.get(0) == NAMES or \ term.get(0) == NAMES_ALT: local_refs[term.get(1)] = term.get(2) if isinstance(term.get(2), String): fname = term.get(2).get_string_value() req_mod_n = get_mod_name_from_file(fname, aiddl_paths) local_refs[term.get(1)] = req_mod_n elif token == CSET: assembled_set = [] current = pop(stack) while current != OSET: assembled_set.append(current) current = pop(stack) term = Set(assembled_set) elif token in SPECIAL: push(stack, token) if token == OTUPLE: tuple_depth += 1 continue else: term = None if token[0] == "?": term = Variable(name=token) elif token == "_": term = Variable() elif token[0] == '"': string = str_lookup[int(token[1:-1])] term = String(string) elif "/" in token: n = token.split("/")[0] d = token.split("/")[1] term = Rational(int(n), int(d)) elif is_float(token): term = Real(float(token)) elif is_int(token): term = Integer(int(token)) elif is_bin(token): term = Integer(int(token[2:], 2)) elif is_oct(token): term = Integer(int(token[2:], 8)) elif is_hex(token): term = Integer(int(token[2:], 16)) elif token in INFINITY: if "-" in token: term = Infinity.neg() else: term = Infinity.pos() else: term = Symbolic(token) if len(stack) > 0: back_resolve = True while back_resolve and len(stack) > 0: back_resolve = False if peek(stack) == SREF: pop(stack) term = Reference(term, module_name) back_resolve = True elif peek(stack) == REF: pop(stack) name = pop(stack) if not isinstance(name, FunctionReference): if term == self_ref: # print("Pointing to %s in module %s (aka %s)" # % (str(name), str(module_name), str(term))) term = Reference(name, module_name, alias=term) else: # print("Pointing to %s in module %s (aka %s)" # % (str(name), str(module_name), str(term))) term = Reference(name, local_refs[term], alias=term) else: bad_fref = name.get_fref() if term == self_ref: term = FunctionReference(bad_fref, freg, module=module_name) else: term = FunctionReference(bad_fref, freg, module=module_name) back_resolve = True elif peek(stack) == FREF: pop(stack) term = FunctionReference(term, freg) back_resolve = True elif peek(stack) == ASSOC: pop(stack) key = pop(stack) if isinstance(key, KeyValue): term = KeyValue(key._key, KeyValue(key._value, term)) else: term = KeyValue(key, term) back_resolve = True push(stack, term) return (stack, module_name, self_ref, local_refs)
def apply(self, arg): # if not self.evaluatable(arg): # return arg # if arg in self.cache.keys(): # return self.cache[arg] if self.verbose: print(self.log_indent + str(arg)) self.log_indent += " " operator = None if not isinstance(arg, Tuple) or len(arg) == 0: if isinstance(arg, Collection): newCol = [] for t in arg: newCol.append(self.apply(t)) if isinstance(arg, List): result = List(newCol) else: result = Set(newCol) elif isinstance(arg, KeyValue): result = KeyValue(self.apply(arg.get_key()), self.apply(arg.get_value())) elif isinstance(arg, Reference): #print("-----", arg, self.follow_references) if self.follow_references: result = self.apply(self.db.resolve_reference(arg)) else: result = self.db.resolve_reference(arg) #print(arg, "resolved to", result) else: result = arg else: operator = arg.get(0) if isinstance(operator, Reference): target = operator.get_ref_target() if isinstance(target, Symbolic): uri = operator.convert2uri() if self.freg.has_function(uri): operator = uri else: operator = self.db.resolve_reference(operator) else: operator = self.db.resolve_reference(operator) # if self.verbose: # tail = str(operator) resolvedArguments = [] processed_op = self.apply(operator) if not self.freg.has_function(processed_op): resolvedArguments.append(processed_op) for i in range(1, arg.size()): if operator not in self.delayedEval: if isinstance(arg.get(i), Reference): res_arg = self.db.resolve_reference(arg.get(i)) else: res_arg = arg.get(i) # if len(self.selfStack) > 0: # if operator != TYPE: # res_arg = res_arg.substitute(self.selfStack[-1]) # elif i == 1: # res_arg = res_arg.substitute(self.selfStack[-1]) # if operator == TYPE and i == 2: # s = Substitution() # s.add(SELF, resolvedArguments[1]) # res_arg = res_arg.substitute(s) # self.selfStack.append(s) # doPop = True if operator not in self.delayedEval: resolvedArguments.append(self.apply(res_arg)) else: resolvedArguments.append(res_arg) else: resolvedArguments.append(arg.get(i)) if len(resolvedArguments) == 1: processedArgs = resolvedArguments[0] else: processedArgs = Tuple(resolvedArguments) if self.freg.has_function(operator): result = self.freg.get_function(operator).apply(processedArgs) else: result = processedArgs if self.verbose: if operator is None: operator = Symbolic("-") self.log_indent = self.log_indent[0:-2] print(self.log_indent + str(result) + "//" + str(operator)) self.cache[arg] = result return result