Search in sources :

Example 1 with Tuple

use of suite.node.Tuple in project suite by stupidsing.

the class CompileBinderImpl method binder.

public Bind_ binder(Node node) {
    FunCreator<Bind_> fc = FunCreator.of(Bind_.class, false);
    return fc.create(new BinOp<>() {

        private FunExpr env, trail, b;

        public FunExpr apply(FunExpr bindEnv, FunExpr target) {
            this.env = bindEnv.field("env");
            this.trail = bindEnv.field("trail");
            return f.declare(ok, b -> {
                this.b = b;
                return compile_(node, target);
            });
        }

        private FunExpr compile_(Node node, FunExpr target) {
            FunExpr br = bind(f.object_(node, Node.class), target);
            FunExpr brc = bindClone(node, target);
            return new // 
            SwitchNode<FunExpr>(// 
            node).applyIf(Atom.class, n -> {
                return f.ifEquals(target, f.object(node), ok, br);
            }).applyIf(Int.class, n -> {
                return f.ifInstance(Int.class, target, i -> f.ifEquals(i.field("number"), f.int_(n.number), ok, fail), br);
            }).applyIf(Reference.class, n -> {
                FunExpr ref = env.field("refs").index(f.int_(mapper().computeIndex(n)));
                return f.invokeStatic(Binder.class, "bind", target, ref.cast_(Node.class), trail);
            }).applyIf(Str.class, n -> {
                return f.ifInstance(Str.class, target, s -> f.object(n.value).invoke("equals", s.field("value").cast_(Object.class)), br);
            }).applyIf(Tree.class, tree -> {
                return f.declare(f.invokeStatic(Tree.class, "decompose", target, f.object(tree.getOperator())), t -> {
                    Node lt = tree.getLeft();
                    Node rt = tree.getRight();
                    return f.ifNonNull(t, compile_(lt, t.invoke("getLeft"), compile_(rt, t.invoke("getRight"), ok)), brc);
                });
            }).applyIf(Tuple.class, n -> {
                return f.ifInstance(Tuple.class, target, tuple -> f.declare(tuple.field("nodes"), targets -> {
                    Node[] nodes = n.nodes;
                    FunExpr fe = ok;
                    for (int i = 0; i < nodes.length; i++) fe = compile_(nodes[i], targets.index(f.int_(i)), fe);
                    return f.if_(targets.length(), fe, brc);
                }), brc);
            }).applyIf(Node.class, n -> {
                Clone_ cloner = cloner(n);
                return f.invokeStatic(Binder.class, "bind", target, f.object(cloner).invoke("apply", env), trail);
            }).nonNullResult();
        }

        private FunExpr compile_(Node node, FunExpr target, FunExpr cps) {
            return f.assign(b, compile_(node, target), f.if_(b, cps, fail));
        }

        private FunExpr bindClone(Node node, FunExpr target) {
            if (isBindTrees)
                return bind(f.object(cloner(node)).apply(env), target);
            else
                return fail;
        }

        private FunExpr bind(FunExpr node, FunExpr target) {
            return f.ifInstanceAnd(Reference.class, target, ref -> f.seq(trail.invoke("addBind", ref, node), ok));
        }
    }).apply(Map.ofEntries());
}
Also used : Reference(suite.node.Reference) BinderFactory(suite.lp.doer.BinderFactory) Tree(suite.node.Tree) BinOp(suite.util.FunUtil2.BinOp) Node(suite.node.Node) Atom(suite.node.Atom) Map(java.util.Map) FunCreator(suite.jdk.gen.FunCreator) Binder(suite.lp.doer.Binder) SwitchNode(suite.node.io.SwitchNode) FunExpr(suite.jdk.gen.FunExpression.FunExpr) FunFactory(suite.jdk.gen.FunFactory) Int(suite.node.Int) Tuple(suite.node.Tuple) Str(suite.node.Str) Binder(suite.lp.doer.Binder) Reference(suite.node.Reference) Node(suite.node.Node) SwitchNode(suite.node.io.SwitchNode) Tree(suite.node.Tree) BinOp(suite.util.FunUtil2.BinOp) SwitchNode(suite.node.io.SwitchNode) FunExpr(suite.jdk.gen.FunExpression.FunExpr) Atom(suite.node.Atom)

Example 2 with Tuple

use of suite.node.Tuple in project suite by stupidsing.

the class SewingGeneralizerImpl method generalizer.

@Override
public Generalize_ generalizer(Node node) {
    List<Generalize_> funs = new ArrayList<>();
    Generalize_ fun;
    while (true) {
        Node node0 = node;
        Tree tree;
        if (node0 instanceof Atom) {
            Atom atom = (Atom) node0;
            String name = atom.name;
            if (ProverConstant.isCut(node0) || ProverConstant.isVariable(name)) {
                int index = vm.computeIndex(atom);
                fun = env -> env.get(index);
            } else if (ProverConstant.isWildcard(name))
                fun = env -> new Reference();
            else
                fun = env -> node0;
        } else if (node0 instanceof Dict) {
            Generalize_[][] array = // 
            Read.from2(// 
            ((Dict) node0).map).map(// 
            (key, value) -> new Generalize_[] { generalizer(key), generalizer(value) }).toArray(Generalize_[].class);
            int length = array.length;
            fun = env -> {
                @SuppressWarnings("unchecked") Pair<Node, Reference>[] pairs = new Pair[length];
                for (int i = 0; i < length; i++) pairs[i] = Pair.of(array[i][0].apply(env), Reference.of(array[i][1].apply(env)));
                return Dict.of(pairs);
            };
        } else if ((tree = Tree.decompose(node0)) != null) {
            Operator operator = tree.getOperator();
            if (operator != TermOp.OR____) {
                Generalize_ f = generalizer(tree.getLeft());
                funs.add(env -> Tree.of(operator, f.apply(env), null));
                node = tree.getRight();
                continue;
            } else {
                // delay generalizing for performance
                Generalize_ lf = generalizer(tree.getLeft());
                Generalize_ rf = generalizer(tree.getRight());
                fun = env -> Tree.of(operator, lf.apply(env), new Suspend(() -> rf.apply(env)));
            }
        } else if (node0 instanceof Tuple) {
            Generalize_[] fs = Read.from(((Tuple) node0).nodes).map(this::generalizer).toArray(Generalize_.class);
            int length = fs.length;
            fun = env -> {
                Node[] array = new Node[length];
                for (int i = 0; i < length; i++) array[i] = fs[i].apply(env);
                return Tuple.of(array);
            };
        } else
            fun = env -> node0;
        funs.add(fun);
        break;
    }
    if (1 < funs.size())
        return env -> {
            Tree t = Tree.of(null, null, null);
            Node node_ = t;
            for (Generalize_ fun_ : funs) {
                Tree t_ = Tree.decompose(node_);
                Tree.forceSetRight(t_, fun_.apply(env));
                node_ = t_.getRight();
            }
            return t.getRight();
        };
    else
        return funs.get(0);
}
Also used : Reference(suite.node.Reference) Read(suite.streamlet.Read) GeneralizerFactory(suite.lp.doer.GeneralizerFactory) TermOp(suite.node.io.TermOp) Tree(suite.node.Tree) ArrayList(java.util.ArrayList) Node(suite.node.Node) Pair(suite.adt.pair.Pair) List(java.util.List) ProverConstant(suite.lp.doer.ProverConstant) VariableMapper(suite.lp.sewing.VariableMapper) Atom(suite.node.Atom) Suspend(suite.node.Suspend) Tuple(suite.node.Tuple) Operator(suite.node.io.Operator) Dict(suite.node.Dict) Operator(suite.node.io.Operator) Reference(suite.node.Reference) Node(suite.node.Node) ArrayList(java.util.ArrayList) Suspend(suite.node.Suspend) Atom(suite.node.Atom) Dict(suite.node.Dict) Tree(suite.node.Tree) Tuple(suite.node.Tuple)

Example 3 with Tuple

use of suite.node.Tuple in project suite by stupidsing.

the class SewingProverImpl method compileCps.

private Cps compileCps(BinderFactory bf, Node node, Cps cpsx) {
    List<Node> list;
    Tree tree;
    Node[] m;
    Cps cps;
    if (1 < (list = TreeUtil.breakdown(TermOp.AND___, node)).size()) {
        cps = cpsx;
        for (Node n : List_.reverse(list)) cps = compileCps(bf, n, cps);
    } else if (1 < (list = TreeUtil.breakdown(TermOp.OR____, node)).size())
        cps = orCps(Read.from(list).map(n -> compileCps(bf, n, cpsx)));
    else if ((m = Suite.pattern(".0 = .1").match(node)) != null) {
        boolean b = complexity(m[0]) <= complexity(m[1]);
        Node n0 = b ? m[0] : m[1];
        Node n1 = b ? m[1] : m[0];
        Bind_ p = bf.binder(n1);
        Clone_ f = bf.cloner(n0);
        cps = rt -> p.test(rt, f.apply(rt.env)) ? cpsx : null;
    } else if ((m = Suite.pattern(".0 .1").match(node)) != null && m[0] instanceof Atom)
        cps = compileCpsCallPredicate(bf, ((Atom) m[0]).name, m[1], node, cpsx);
    else if (node instanceof Atom) {
        String name = ((Atom) node).name;
        if (String_.equals(name, ""))
            cps = cpsx;
        else if (String_.equals(name, "fail"))
            cps = rt -> null;
        else
            cps = compileCpsCallPredicate(bf, name, Atom.NIL, node, cpsx);
    } else if (node instanceof Reference) {
        Clone_ f = bf.cloner(node);
        cps = rt -> compileCps(passThru, f.apply(rt.env), cpsx);
    } else if ((tree = Tree.decompose(node)) != null)
        cps = compileCpsCallPredicate(bf, tree.getOperator().getName(), node, node, cpsx);
    else if (node instanceof Tuple)
        cps = compileCpsCallPredicate(bf, node, cpsx);
    else
        cps = Fail.t("cannot understand " + node);
    return cps;
}
Also used : Prover(suite.lp.doer.Prover) BindEnv(suite.lp.doer.BinderFactory.BindEnv) BuiltinPredicate(suite.lp.predicate.PredicateUtil.BuiltinPredicate) LogUtil(suite.os.LogUtil) Mutable(suite.adt.Mutable) BinderFactory(suite.lp.doer.BinderFactory) Node(suite.node.Node) ProverConstant(suite.lp.doer.ProverConstant) VariableMapper(suite.lp.sewing.VariableMapper) Suspend(suite.node.Suspend) Map(java.util.Map) Prototype(suite.lp.kb.Prototype) RuleSet(suite.lp.kb.RuleSet) Generalizer(suite.lp.doer.Generalizer) Bind_(suite.lp.doer.BinderFactory.Bind_) Cloner(suite.lp.doer.Cloner) Object_(suite.util.Object_) SystemPredicates(suite.lp.predicate.SystemPredicates) Tree(suite.node.Tree) Pair(suite.adt.pair.Pair) Friends.max(suite.util.Friends.max) List(java.util.List) Clone_(suite.lp.doer.ClonerFactory.Clone_) ListMultimap(suite.adt.map.ListMultimap) As(suite.streamlet.As) Int(suite.node.Int) TreeUtil(suite.node.util.TreeUtil) ProverConfig(suite.lp.Configuration.ProverConfig) Read(suite.streamlet.Read) Rule(suite.lp.kb.Rule) HashMap(java.util.HashMap) IList(suite.immutable.IList) ArrayList(java.util.ArrayList) Data(suite.node.Data) Formatter(suite.node.io.Formatter) String_(suite.util.String_) Rethrow(suite.util.Rethrow) Binder(suite.lp.doer.Binder) Tuple(suite.node.Tuple) Reference(suite.node.Reference) Suite(suite.Suite) SuiteException(suite.node.util.SuiteException) Iterator(java.util.Iterator) CompileExpressionImpl(suite.lp.compile.impl.CompileExpressionImpl) Source(suite.util.FunUtil.Source) TermOp(suite.node.io.TermOp) List_(suite.util.List_) Evaluate_(suite.lp.doer.EvaluatorFactory.Evaluate_) Rewrite(suite.node.util.Rewrite) Streamlet(suite.streamlet.Streamlet) Atom(suite.node.Atom) Sink(suite.util.FunUtil.Sink) ProverFactory(suite.lp.doer.ProverFactory) Env(suite.lp.sewing.Env) Fail(suite.util.Fail) Reference(suite.node.Reference) Node(suite.node.Node) Atom(suite.node.Atom) Bind_(suite.lp.doer.BinderFactory.Bind_) Clone_(suite.lp.doer.ClonerFactory.Clone_) Tree(suite.node.Tree) Tuple(suite.node.Tuple)

Example 4 with Tuple

use of suite.node.Tuple in project suite by stupidsing.

the class Formatter method format_.

private void format_(Node node, int parentPrec) {
    new // 
    SwitchNode<Node>(// 
    node).doIf(Atom.class, n -> {
        sb.append(quoteAtomIfRequired(n.name));
    }).doIf(Data.class, n -> {
        Object data = n.data;
        if (data instanceof Chars)
            sb.append("Chars<" + quoteStringIfRequired(data.toString()) + ">");
        else if (data instanceof Node)
            sb.append("Data<" + data.toString() + ">");
        else
            sb.append("Data<" + data.getClass().getSimpleName() + ">");
    }).doIf(Dict.class, n -> {
        sb.append("dict<");
        for (Entry<Node, Reference> e : n.map.entrySet()) {
            format(e.getKey(), TermOp.getLeftPrec(TermOp.AND___));
            sb.append(":");
            format(e.getValue(), TermOp.getLeftPrec(TermOp.AND___));
            sb.append(",");
        }
        sb.append(">");
    }).doIf(Int.class, n -> {
        sb.append(n.number);
    }).doIf(Reference.class, n -> {
        sb.append(n.name());
    }).doIf(Str.class, n -> {
        sb.append(quoteStringIfRequired(n.value));
    }).doIf(Tree.class, n -> {
        formatTree(parentPrec, n);
    }).doIf(Tuple.class, n -> {
        sb.append("tuple<");
        for (Node n_ : n.nodes) {
            format(n_, TermOp.getLeftPrec(TermOp.AND___));
            sb.append(", ");
        }
        sb.append(">");
    }).doIf(Node.class, n -> {
        sb.append(n.getClass().getSimpleName() + '@' + Integer.toHexString(System.identityHashCode(n)));
    }).nonNullResult();
}
Also used : Reference(suite.node.Reference) Set(java.util.Set) Chars(suite.primitive.Chars) Tree(suite.node.Tree) Node(suite.node.Node) HashSet(java.util.HashSet) ProverConstant(suite.lp.doer.ProverConstant) Data(suite.node.Data) CommentPreprocessor(suite.parser.CommentPreprocessor) String_(suite.util.String_) Atom(suite.node.Atom) Entry(java.util.Map.Entry) Int(suite.node.Int) Tuple(suite.node.Tuple) Dict(suite.node.Dict) Str(suite.node.Str) Entry(java.util.Map.Entry) Dict(suite.node.Dict) Reference(suite.node.Reference) Node(suite.node.Node) Tree(suite.node.Tree) Chars(suite.primitive.Chars) Atom(suite.node.Atom)

Example 5 with Tuple

use of suite.node.Tuple in project suite by stupidsing.

the class Comparer method compare.

@Override
public int compare(Node n0, Node n1) {
    n0 = n0.finalNode();
    n1 = n1.finalNode();
    Class<? extends Node> clazz0 = n0.getClass();
    Class<? extends Node> clazz1 = n1.getClass();
    int c = Integer.compare(order.get(clazz0), order.get(clazz1));
    if (c == 0)
        if (clazz0 == Atom.class)
            return ((Atom) n0).name.compareTo(((Atom) n1).name);
        else if (clazz0 == Dict.class) {
            Map<Node, Reference> m0 = ((Dict) n0).map;
            Map<Node, Reference> m1 = ((Dict) n1).map;
            Set<Node> keys = new HashSet<>();
            keys.addAll(m0.keySet());
            keys.addAll(m1.keySet());
            for (Node key : Read.from(keys).sort(this::compare)) c = c != 0 ? c : Object_.compare(m0.get(key), m1.get(key));
            return c;
        } else if (clazz0 == Int.class)
            return Integer.compare(((Int) n0).number, ((Int) n1).number);
        else if (clazz0 == Reference.class)
            return Integer.compare(((Reference) n0).getId(), ((Reference) n1).getId());
        else if (clazz0 == Str.class)
            return ((Str) n0).value.compareTo(((Str) n1).value);
        else if (Tree.class.isAssignableFrom(clazz0)) {
            Tree t0 = (Tree) n0;
            Tree t1 = (Tree) n1;
            c = t0.getOperator().getPrecedence() - t1.getOperator().getPrecedence();
            c = c != 0 ? c : compare(t0.getLeft(), t1.getLeft());
            c = c != 0 ? c : compare(t0.getRight(), t1.getRight());
            return c;
        } else if (clazz0 == Tuple.class) {
            Node[] nodes0 = ((Tuple) n0).nodes;
            Node[] nodes1 = ((Tuple) n1).nodes;
            int i = 0, l = min(nodes0.length, nodes1.length);
            while (c == 0 && i < l) c = compare(nodes0[i], nodes1[i]);
            if (c == 0)
                c = Integer.compare(nodes0.length, nodes1.length);
            return c;
        } else
            return Integer.compare(n0.hashCode(), n1.hashCode());
    else
        return c;
}
Also used : Reference(suite.node.Reference) Node(suite.node.Node) Atom(suite.node.Atom) Int(suite.node.Int) Str(suite.node.Str) Dict(suite.node.Dict) Tree(suite.node.Tree) Tuple(suite.node.Tuple) TreeTuple(suite.node.tree.TreeTuple) HashSet(java.util.HashSet)

Aggregations

Node (suite.node.Node)10 Reference (suite.node.Reference)10 Tree (suite.node.Tree)10 Tuple (suite.node.Tuple)10 Atom (suite.node.Atom)8 Int (suite.node.Int)7 Dict (suite.node.Dict)6 Str (suite.node.Str)6 Read (suite.streamlet.Read)6 ArrayList (java.util.ArrayList)5 List (java.util.List)5 Pair (suite.adt.pair.Pair)5 Binder (suite.lp.doer.Binder)5 ProverConstant (suite.lp.doer.ProverConstant)5 Map (java.util.Map)4 BinderFactory (suite.lp.doer.BinderFactory)4 VariableMapper (suite.lp.sewing.VariableMapper)4 Suspend (suite.node.Suspend)4 TermOp (suite.node.io.TermOp)4 HashMap (java.util.HashMap)3