Search in sources :

Example 11 with Atom

use of suite.node.Atom 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 12 with Atom

use of suite.node.Atom 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 13 with Atom

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

the class PeepholeOptimizer method optimize.

public List<Pair<Reference, Node>> optimize(List<Pair<Reference, Node>> lnis0) {
    List<Pair<Reference, Node>> lnis1 = new ArrayList<>();
    for (Pair<Reference, Node> lni0 : lnis0) {
        Node node0 = lni0.t1;
        Node node1;
        Node[] m;
        if ((m = ADDI__.match(node0)) != null) {
            Node m0 = m[0];
            int i = TreeUtil.evaluate(m[1]);
            if (i == 1)
                node1 = Suite.substitute("INC .0", m0);
            else if (i == -1)
                node1 = Suite.substitute("DEC .0", m0);
            else if (0 < i)
                node1 = Suite.substitute("ADD (.0, .1)", m0, Int.of(i));
            else if (i < 0)
                node1 = Suite.substitute("SUB (.0, .1)", m0, Int.of(-i));
            else
                node1 = Atom.NIL;
        } else if ((m = MOV___.match(node0)) != null) {
            Node m0 = m[0];
            Node m1 = m[1];
            if (m0 == m1)
                node1 = Atom.NIL;
            else if (m0 instanceof Atom && m1 instanceof Int && ((Int) m1).number == 0)
                node1 = Suite.substitute("XOR (.0, .0)", m0);
            else
                node1 = Suite.substitute("MOV (.0, .1)", m0, m1);
        } else
            node1 = node0;
        lnis1.add(Pair.of(lni0.t0, node1));
    }
    return lnis1;
}
Also used : Reference(suite.node.Reference) Node(suite.node.Node) ArrayList(java.util.ArrayList) Atom(suite.node.Atom) Int(suite.node.Int) Pair(suite.adt.pair.Pair)

Example 14 with Atom

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

the class CommandDispatcher method elaborate.

private void elaborate(Node node0, Sink<Node> sink) {
    int[] count = { 0 };
    NodeEnv<Atom> ne = new CompileGeneralizerImpl().g(node0).source();
    Node node1 = ne.node;
    Node elab = new Data<Source<Boolean>>(() -> {
        String dump = ne.dumpVariables();
        if (!dump.isEmpty())
            opt.prompt().println(dump);
        count[0]++;
        return Boolean.FALSE;
    });
    sink.sink(Tree.of(TermOp.AND___, node1, elab));
    if (count[0] == 1)
        opt.prompt().println(count[0] + " solution\n");
    else
        opt.prompt().println(count[0] + " solutions\n");
}
Also used : CompileGeneralizerImpl(suite.lp.compile.impl.CompileGeneralizerImpl) Node(suite.node.Node) Data(suite.node.Data) Atom(suite.node.Atom)

Example 15 with Atom

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

the class InterpretFunEager method eager.

public Node eager(Node node) {
    Node mode = isLazyify ? Atom.of("LAZY") : Atom.of("EAGER");
    Node query = Suite.substitute("source .in, fc-process-function .0 .in .out, sink .out", mode);
    RuleSet rs = Suite.newRuleSet(List.of("auto.sl", "fc/fc.sl"));
    Finder finder = new SewingProverBuilder2().build(rs).apply(query);
    Node parsed = FindUtil.collectSingle(finder, node);
    IntrinsicCallback ic = isLazyify ? lazyIntrinsicCallback() : Intrinsics.eagerIntrinsicCallback;
    Map<String, Node> df = new HashMap<>();
    df.put(TermOp.AND___.name, f2((a, b) -> Tree.of(TermOp.AND___, a, b)));
    df.put("+call%i-t1", f1(i -> fn(1, l -> Data.<Intrinsic>get(i).invoke(ic, l))));
    df.put("+call%i-t2", f1(i -> fn(2, l -> Data.<Intrinsic>get(i).invoke(ic, l))));
    df.put("+call%i-t3", f1(i -> fn(3, l -> Data.<Intrinsic>get(i).invoke(ic, l))));
    df.put("+call%i-v1", f1(i -> fn(1, l -> Data.<Intrinsic>get(i).invoke(ic, l))));
    df.put("+call%i-v2", f1(i -> fn(2, l -> Data.<Intrinsic>get(i).invoke(ic, l))));
    df.put("+call%i-v3", f1(i -> fn(3, l -> Data.<Intrinsic>get(i).invoke(ic, l))));
    df.put("+compare", f2((a, b) -> Int.of(Comparer.comparer.compare(a, b))));
    df.put("+get%i", f1(a -> new Data<>(Intrinsics.intrinsics.get(((Atom) a).name.split("!")[1]))));
    df.put("+is-list", f1(a -> b(Tree.decompose(a) != null)));
    df.put("+is-pair", f1(a -> b(Tree.decompose(a) != null)));
    df.put("+lcons", f2((a, b) -> Tree.of(TermOp.OR____, a, b)));
    df.put("+lhead", f1(a -> Tree.decompose(a).getLeft()));
    df.put("+ltail", f1(a -> Tree.decompose(a).getRight()));
    df.put("+pcons", f2((a, b) -> Tree.of(TermOp.AND___, a, b)));
    df.put("+pleft", f1(a -> Tree.decompose(a).getLeft()));
    df.put("+pright", f1(a -> Tree.decompose(a).getRight()));
    for (Entry<Operator, IntInt_Bool> e : TreeUtil.boolOperations.entrySet()) {
        IntInt_Bool fun = e.getValue();
        df.put(e.getKey().getName(), f2((a, b) -> b(fun.apply(compare(a, b), 0))));
    }
    for (Entry<Operator, IntInt_Int> e : TreeUtil.intOperations.entrySet()) {
        IntInt_Int fun = e.getValue();
        df.put(e.getKey().getName(), f2((a, b) -> Int.of(fun.apply(i(a), i(b)))));
    }
    List<String> keys = df.keySet().stream().sorted().collect(Collectors.toList());
    Eager_ eager0 = new Eager_(0, IMap.empty());
    Frame frame = new Frame(null);
    for (String key : keys) {
        eager0 = eager0.put(Atom.of(key));
        frame.add(df.get(key));
    }
    return eager0.eager_(parsed).apply(frame);
}
Also used : IntInt_Bool(suite.node.util.TreeUtil.IntInt_Bool) APPLY(suite.fp.match.Matchers.APPLY) DECONS(suite.fp.match.Matchers.DECONS) Fun(suite.util.FunUtil.Fun) BinOp(suite.util.FunUtil2.BinOp) Node(suite.node.Node) BOOLEAN(suite.fp.match.Matchers.BOOLEAN) VAR(suite.fp.match.Matchers.VAR) Map(java.util.Map) FindUtil(suite.lp.search.FindUtil) RuleSet(suite.lp.kb.RuleSet) NUMBER(suite.fp.match.Matchers.NUMBER) ERROR(suite.fp.match.Matchers.ERROR) IntrinsicCallback(suite.fp.intrinsic.Intrinsics.IntrinsicCallback) TREE(suite.fp.match.Matchers.TREE) IMap(suite.immutable.IMap) FUN(suite.fp.match.Matchers.FUN) To(suite.util.To) Intrinsic(suite.fp.intrinsic.Intrinsics.Intrinsic) Collectors(java.util.stream.Collectors) Matcher(suite.fp.match.Matcher) PRAGMA(suite.fp.match.Matchers.PRAGMA) Tree(suite.node.Tree) UNWRAP(suite.fp.match.Matchers.UNWRAP) IntInt_Int(suite.primitive.IntInt_Int) Iterate(suite.util.FunUtil.Iterate) Pair(suite.adt.pair.Pair) List(java.util.List) Entry(java.util.Map.Entry) Int(suite.node.Int) TreeUtil(suite.node.util.TreeUtil) IF(suite.fp.match.Matchers.IF) SewingProverBuilder2(suite.lp.search.SewingProverBuilder2) Comparer(suite.node.util.Comparer) HashMap(java.util.HashMap) TCO(suite.fp.match.Matchers.TCO) ArrayList(java.util.ArrayList) CONS(suite.fp.match.Matchers.CONS) Data(suite.node.Data) Formatter(suite.node.io.Formatter) Intrinsics(suite.fp.intrinsic.Intrinsics) DEFVARS(suite.fp.match.Matchers.DEFVARS) Suite(suite.Suite) Source(suite.util.FunUtil.Source) Finder(suite.lp.search.ProverBuilder.Finder) Pattern(suite.BindArrayUtil.Pattern) TermOp(suite.node.io.TermOp) ATOM(suite.fp.match.Matchers.ATOM) WRAP(suite.fp.match.Matchers.WRAP) CHARS(suite.fp.match.Matchers.CHARS) Atom(suite.node.Atom) Operator(suite.node.io.Operator) Fail(suite.util.Fail) Str(suite.node.Str) Operator(suite.node.io.Operator) RuleSet(suite.lp.kb.RuleSet) IntrinsicCallback(suite.fp.intrinsic.Intrinsics.IntrinsicCallback) HashMap(java.util.HashMap) Node(suite.node.Node) Finder(suite.lp.search.ProverBuilder.Finder) SewingProverBuilder2(suite.lp.search.SewingProverBuilder2) Data(suite.node.Data) Atom(suite.node.Atom) IntInt_Int(suite.primitive.IntInt_Int) Intrinsic(suite.fp.intrinsic.Intrinsics.Intrinsic) IntInt_Bool(suite.node.util.TreeUtil.IntInt_Bool)

Aggregations

Atom (suite.node.Atom)22 Node (suite.node.Node)17 Reference (suite.node.Reference)11 Tree (suite.node.Tree)11 TermOp (suite.node.io.TermOp)9 ArrayList (java.util.ArrayList)7 Pair (suite.adt.pair.Pair)7 Int (suite.node.Int)7 List (java.util.List)6 HashMap (java.util.HashMap)5 Map (java.util.Map)5 Suite (suite.Suite)5 Generalizer (suite.lp.doer.Generalizer)5 Prototype (suite.lp.kb.Prototype)5 RuleSet (suite.lp.kb.RuleSet)5 Data (suite.node.Data)5 TreeUtil (suite.node.util.TreeUtil)5 Read (suite.streamlet.Read)5 Fail (suite.util.Fail)5 Operator (suite.node.io.Operator)4