Search in sources :

Example 61 with Node

use of suite.node.Node 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 62 with Node

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

the class CircularProgrammingTest method test.

@Test
public void test() throws IOException {
    String fp = // 
    "" + // 
    "data (Binary-tree :t) over :t as Tree (Binary-tree :t, Binary-tree :t) >> \n " + // 
    "data (Binary-tree :t) over :t as Leaf :t >> \n " + // 
    "let mintree := t => \n " + // 
    "    lets ( \n " + // 
    "        mintree1 := \n " + // 
    "            case \n " + // 
    "            || `Leaf $n` => (n, Leaf n1) \n " + // 
    "            || `Tree ($l, $r)` => \n " + // 
    "                let `$minl, $l1` := mintree1 {l} >> \n " + // 
    "                let `$minr, $r1` := mintree1 {r} >> \n " + // 
    "                lesser {minl} {minr}, Tree (l1, r1) \n " + // 
    "            || anything => error () \n " + // 
    "        # \n " + // 
    "        n1 := first {mintree1 {t}} # \n " + // 
    "        t1 := second {mintree1 {t}} # \n " + // 
    "    ) >> \n " + // 
    "    t1 \n " + // 
    ">> \n " + "mintree {Tree (Tree (Leaf 1, Leaf 2), Tree (Leaf 3, Tree (Leaf 4, Leaf 5)))} \n ";
    Node result = Suite.evaluateFun(fp, true);
    assertNotNull(result);
    assertEquals("Tree, (Tree, (Leaf, 1), Leaf, 1), Tree, (Leaf, 1), Tree, (Leaf, 1), Leaf, 1", Formatter.dump(result));
}
Also used : Node(suite.node.Node) Test(org.junit.Test)

Example 63 with Node

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

the class EagerFunTest method testGcd.

@Test
public void testGcd() {
    Node f = Suite.parse("gcd {6} {9}");
    FunCompilerConfig c = Suite.fcc(f);
    c.addLibrary("MATH");
    assertEquals(Int.of(3), Suite.evaluateFun(c));
}
Also used : Node(suite.node.Node) Test(org.junit.Test)

Example 64 with Node

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

the class FunRbTreeTest method test.

@Test
public void test() {
    String s = FileUtil.read("src/main/fl/RB-TREE.slf");
    String fp = s + "0 until 10 | map {rbt-insert} | apply | {Empty}\n";
    Node result = Suite.evaluateFun(fp, false);
    assertNotNull(result);
    System.out.println("OUT:\n" + Formatter.dump(result));
}
Also used : Node(suite.node.Node) Test(org.junit.Test)

Example 65 with Node

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

the class MonadTest method eval.

private String eval(Node node) throws IOException {
    StringWriter sw = new StringWriter();
    Node node1 = Suite.substitute("use MONAD >> .0", Suite.applyWriter(node));
    Suite.evaluateFunToWriter(Suite.fcc(node1, true), sw);
    return sw.toString();
}
Also used : StringWriter(java.io.StringWriter) Node(suite.node.Node)

Aggregations

Node (suite.node.Node)139 Tree (suite.node.Tree)50 Reference (suite.node.Reference)41 Atom (suite.node.Atom)37 Int (suite.node.Int)33 ArrayList (java.util.ArrayList)32 Pair (suite.adt.pair.Pair)25 List (java.util.List)24 TermOp (suite.node.io.TermOp)21 Read (suite.streamlet.Read)21 Test (org.junit.Test)20 Map (java.util.Map)19 Suite (suite.Suite)18 Generalizer (suite.lp.doer.Generalizer)18 Fail (suite.util.Fail)18 Fun (suite.util.FunUtil.Fun)18 Str (suite.node.Str)17 Trail (suite.lp.Trail)16 RuleSet (suite.lp.kb.RuleSet)16 Tuple (suite.node.Tuple)16