Search in sources :

Example 11 with Reference

use of suite.node.Reference 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)

Example 12 with Reference

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

the class Rewrite method rewrite.

public Node rewrite(Source<Node[]> source, Node node) {
    Trail trail = new Trail();
    return rewrite(node0 -> {
        Node node1;
        if (!(node0 instanceof Reference)) {
            int pit = trail.getPointInTime();
            Node[] ft = source.source();
            if (Binder.bind(node0, ft[0], trail))
                node1 = ft[1];
            else {
                trail.unwind(pit);
                node1 = node0;
            }
        } else
            node1 = node0;
        return node1;
    }, node);
}
Also used : Trail(suite.lp.Trail) Reference(suite.node.Reference) Node(suite.node.Node)

Example 13 with Reference

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

the class Nodify method newNodifier.

@SuppressWarnings("unchecked")
private Nodifier newNodifier(Type type) {
    Nodifier nodifier;
    if (type instanceof Class) {
        Class<?> clazz = (Class<?>) type;
        if (clazz == boolean.class)
            nodifier = new Nodifier(object -> Atom.of(object.toString()), node -> node == Atom.TRUE);
        else if (clazz == int.class)
            nodifier = new Nodifier(object -> Int.of((Integer) object), node -> ((Int) node).number);
        else if (clazz == Chars.class)
            nodifier = new Nodifier(object -> new Str(object.toString()), node -> To.chars(((Str) node).value));
        else if (clazz == String.class)
            nodifier = new Nodifier(object -> new Str(object.toString()), node -> ((Str) node).value);
        else if (clazz.isEnum())
            nodifier = new Nodifier(object -> Atom.of(object.toString()), Read.from(clazz.getEnumConstants()).toMap(e -> Atom.of(e.toString()))::get);
        else if (clazz.isArray()) {
            Class<?> componentType = clazz.getComponentType();
            Nodifier nodifier1 = getNodifier(componentType);
            Fun<Object, Node> forward = object -> {
                Node node = Atom.NIL;
                for (int i = Array.getLength(object) - 1; 0 <= i; i--) node = Tree.of(TermOp.OR____, apply_(nodifier1, Array.get(object, i)), node);
                return node;
            };
            nodifier = new Nodifier(forward, node -> {
                List<Object> list = // 
                Read.from(// 
                Tree.iter(node, TermOp.OR____)).map(// 
                n -> apply_(nodifier1, n)).toList();
                int size = list.size();
                Object objects = Array.newInstance(componentType, size);
                for (int i = 0; i < size; i++) Array.set(objects, i, list.get(i));
                return objects;
            });
        } else if (// polymorphism
        clazz.isInterface())
            nodifier = new Nodifier(object -> {
                Class<?> clazz1 = object.getClass();
                Node n = apply_(getNodifier(clazz1), object);
                return Tree.of(TermOp.COLON_, Atom.of(clazz1.getName()), n);
            }, node -> {
                Tree tree = Tree.decompose(node, TermOp.COLON_);
                if (tree != null) {
                    Class<?> clazz1;
                    try {
                        clazz1 = Class.forName(((Atom) tree.getLeft()).name);
                    } catch (ClassNotFoundException ex) {
                        clazz1 = Fail.t(ex);
                    }
                    return apply_(getNodifier(clazz1), tree.getRight());
                } else
                    // happens when an enum implements an interface
                    return Fail.t("cannot instantiate enum from interfaces");
            });
        else {
            List<FieldInfo> fieldInfos = // 
            Read.from(// 
            inspect.fields(clazz)).map(field -> {
                Type type1 = field.getGenericType();
                return new FieldInfo(field, field.getName(), getNodifier(type1));
            }).toList();
            List<Pair<Atom, FieldInfo>> pairs = Read.from(fieldInfos).map(f -> Pair.of(Atom.of(f.name), f)).toList();
            nodifier = new Nodifier(object -> Rethrow.ex(() -> {
                Dict dict = new Dict();
                for (Pair<Atom, FieldInfo> pair : pairs) {
                    FieldInfo fieldInfo = pair.t1;
                    Node value = apply_(fieldInfo.nodifier, fieldInfo.field.get(object));
                    dict.map.put(pair.t0, Reference.of(value));
                }
                return dict;
            }), node -> Rethrow.ex(() -> {
                Map<Node, Reference> map = ((Dict) node).map;
                Object object1 = Object_.new_(clazz);
                for (Pair<Atom, FieldInfo> pair : pairs) {
                    FieldInfo fieldInfo = pair.t1;
                    Node value = map.get(pair.t0).finalNode();
                    fieldInfo.field.set(object1, apply_(fieldInfo.nodifier, value));
                }
                return object1;
            }));
        }
    } else if (type instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType) type;
        Type rawType = pt.getRawType();
        Type[] typeArgs = pt.getActualTypeArguments();
        Class<?> clazz = rawType instanceof Class ? (Class<?>) rawType : null;
        if (collectionClasses.contains(clazz)) {
            Nodifier nodifier1 = getNodifier(typeArgs[0]);
            nodifier = new Nodifier(object -> {
                Tree start = Tree.of(null, null, null), tree = start;
                for (Object o : (Collection<?>) object) {
                    Tree tree0 = tree;
                    Tree.forceSetRight(tree0, tree = Tree.of(TermOp.OR____, apply_(nodifier1, o), null));
                }
                Tree.forceSetRight(tree, Atom.NIL);
                return start.getRight();
            }, node -> {
                List<Object> list = Read.from(Tree.iter(node, TermOp.OR____)).map(n -> apply_(nodifier1, n)).toList();
                Collection<Object> object1 = (Collection<Object>) instantiate(clazz);
                object1.addAll(list);
                return object1;
            });
        } else if (mapClasses.contains(clazz)) {
            Nodifier kn = getNodifier(typeArgs[0]);
            Nodifier vn = getNodifier(typeArgs[1]);
            nodifier = new Nodifier(object -> {
                Dict dict = new Dict();
                for (Entry<?, ?> e : ((Map<?, ?>) object).entrySet()) dict.map.put(apply_(kn, e.getKey()), Reference.of(apply_(vn, e.getValue())));
                return dict;
            }, node -> {
                Map<Node, Reference> map = ((Dict) node).map;
                Map<Object, Object> object1 = (Map<Object, Object>) instantiate(clazz);
                for (Entry<Node, Reference> e : map.entrySet()) object1.put(apply_(kn, e.getKey()), apply_(vn, e.getValue().finalNode()));
                return object1;
            });
        } else
            nodifier = getNodifier(rawType);
    } else
        nodifier = Fail.t("unrecognized type " + type);
    return nodifier;
}
Also used : Read(suite.streamlet.Read) Array(java.lang.reflect.Array) HashMap(java.util.HashMap) Fun(suite.util.FunUtil.Fun) ArrayList(java.util.ArrayList) Node(suite.node.Node) HashSet(java.util.HashSet) Map(java.util.Map) Dict(suite.node.Dict) Reference(suite.node.Reference) Inspect(suite.inspect.Inspect) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) TermOp(suite.node.io.TermOp) Field(java.lang.reflect.Field) Chars(suite.primitive.Chars) Tree(suite.node.Tree) Pair(suite.adt.pair.Pair) List(java.util.List) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) Atom(suite.node.Atom) Entry(java.util.Map.Entry) Int(suite.node.Int) Str(suite.node.Str) Node(suite.node.Node) Int(suite.node.Int) Str(suite.node.Str) ParameterizedType(java.lang.reflect.ParameterizedType) Entry(java.util.Map.Entry) Tree(suite.node.Tree) Fun(suite.util.FunUtil.Fun) Pair(suite.adt.pair.Pair) Reference(suite.node.Reference) Atom(suite.node.Atom) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) Dict(suite.node.Dict) Collection(java.util.Collection) HashMap(java.util.HashMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 14 with Reference

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

the class Chr method chrThen.

private Streamlet<State> chrThen(Streamlet<State> states, Node then) {
    Generalizer generalizer = new Generalizer();
    Atom a = atom(".a"), b = atom(".b");
    if (Binder.bind(then, generalizer.generalize(Suite.substitute(".0 = .1", a, b)), new Trail())) {
        // built-in syntactic equality
        Reference from = generalizer.getVariable(a);
        Reference to = generalizer.getVariable(b);
        states = states.map(new Fun<>() {

            public State apply(State state) {
                IMap<Prototype, ISet<Node>> factsByPrototype1 = IMap.empty();
                for (Pair<Prototype, ISet<Node>> e : state.factsByPrototype) factsByPrototype1 = factsByPrototype1.put(e.t0, replace(e.t1));
                return new State(factsByPrototype1);
            }

            private ISet<Node> replace(ISet<Node> facts) {
                ISet<Node> facts1 = ISet.empty();
                for (Node node : facts) facts1 = facts1.replace(rw.replace(from, to, node));
                return facts1;
            }
        });
    }
    return states.map(state -> {
        Prototype prototype = Prototype.of(then);
        ISet<Node> facts = getFacts(state, prototype);
        return setFacts(state, prototype, facts.replace(then));
    });
}
Also used : Generalizer(suite.lp.doer.Generalizer) Trail(suite.lp.Trail) Prototype(suite.lp.kb.Prototype) Reference(suite.node.Reference) Node(suite.node.Node) ISet(suite.immutable.ISet) Atom(suite.node.Atom) Fun(suite.util.FunUtil.Fun)

Example 15 with Reference

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

the class RecursiveFactorizerTest method rewriteNewArgument.

private String rewriteNewArgument(String pred0, String predx, String newArgument, String s0) {
    Source<Node[]> source = () -> {
        Reference[] r = new Reference[64];
        for (int i = 0; i < r.length; i++) r[i] = new Reference();
        Fun<String, Fun<Boolean, Node>> fun = hs -> b -> {
            Source<Node> g = To.source(r);
            Node head = terminalNode(hs);
            Node n0 = !b ? g.source() : operatorNode(TermOp.TUPLE_, List.of(g.source(), terminalNode(" "), terminalNode(newArgument)));
            Node n1 = operatorNode(g, TermOp.TUPLE_, g.source(), n0);
            return operatorNode(g, TermOp.TUPLE_, head, n1);
        };
        return new Node[] { fun.apply(pred0).apply(false), fun.apply(predx).apply(true) };
    };
    FactorizeResult fr0 = recursiveFactorizer.parse(s0);
    FNode fn0 = fr0.node;
    Node node0 = nodify.nodify(FNode.class, fn0);
    Node nodex = rw.rewrite(source, node0);
    FNode fnx = nodify.unnodify(FNode.class, nodex);
    FactorizeResult frx = new FactorizeResult(fr0.pre, fnx, fr0.post);
    String sx = frx.unparse();
    return sx;
}
Also used : Reference(suite.node.Reference) FNode(suite.node.parser.FactorizeResult.FNode) Node(suite.node.Node) FNode(suite.node.parser.FactorizeResult.FNode) Fun(suite.util.FunUtil.Fun)

Aggregations

Reference (suite.node.Reference)38 Node (suite.node.Node)31 Tree (suite.node.Tree)21 Atom (suite.node.Atom)17 ArrayList (java.util.ArrayList)15 Pair (suite.adt.pair.Pair)13 Int (suite.node.Int)13 List (java.util.List)11 Generalizer (suite.lp.doer.Generalizer)10 TermOp (suite.node.io.TermOp)10 Read (suite.streamlet.Read)10 Trail (suite.lp.Trail)9 Dict (suite.node.Dict)9 Tuple (suite.node.Tuple)9 HashMap (java.util.HashMap)8 Map (java.util.Map)7 Binder (suite.lp.doer.Binder)7 Str (suite.node.Str)7 Fail (suite.util.Fail)7 Suite (suite.Suite)6