checkpoint
[sbp.git] / src / edu / berkeley / sbp / misc / Demo.java
index 4e0dc1b..f163d93 100644 (file)
@@ -3,19 +3,482 @@ import edu.berkeley.sbp.util.*;
 import edu.berkeley.sbp.*;
 import edu.berkeley.sbp.chr.*;
 import java.util.*;
+import java.lang.annotation.*;
+import java.lang.reflect.*;
 import java.io.*;
 
 public class Demo {
     public static void main(String[] s) throws Exception {
-        /*
-        Tree<String> gram = new CharParser(MetaGrammar.make()).parse(new FileInputStream(s[0])).expand1();
-        MetaGrammar g = (MetaGrammar)new MetaGrammar().walk(gram);
-        Union meta = g.done();
-        //Tree<String> out = new CharParser(meta).parse(new FileInputStream(s[1])).expand1();
-        Forest<String> out = new CharParser(meta).parse(new FileInputStream(s[1]));
-        GraphViz gv = new GraphViz();
-        out.toGraphViz(gv);
-        gv.dump(new PrintWriter(new OutputStreamWriter(System.out)));
-        */
+        Tree<String> res = new CharParser(MetaGrammar.make()).parse(new FileInputStream(s[0])).expand1();
+        
+        MetaGrammar.Meta m =
+            new ReflectiveMeta(MG.class,
+                               new Class[] {
+                                   MG.Grammar.class,
+                                   MG.NonTerminal.class,
+                                   MG.Range.class,
+                                   MG.El.class,
+                                   MG.Seq.class,
+                                   MG.NonTerminalReference.class,
+                                   MG.StringLiteral.class,
+                                   MG.Epsilon.class,
+                                   MG.Tree.class,
+                                   MG.CharClass.class
+                               });
+        MetaGrammar.Meta.MetaGrammarFile mgf = m.new MetaGrammarFile(res);
+        MetaGrammar.BuildContext bc = new MetaGrammar.BuildContext(mgf);
+        Union meta = mgf.get("s").build(bc);
+
+        System.err.println("parsing " + s[1]);
+        Tree t = new CharParser(meta).parse(new FileInputStream(s[1])).expand1();
+
+        System.out.println(t.toPrettyString());
+        Reducer red = (Reducer)t.head();
+        System.out.println(red.reduce(t));
+    }
+
+    public static class ReflectiveMeta extends MetaGrammar.Meta {
+        private final Class _cl;
+        private final Class[] _inner;
+        public ReflectiveMeta(Class c, Class[] inner) {
+            this._cl = c;
+            this._inner = inner;
+        }
+        private boolean match(Method m, String s) { return match(m.getAnnotation(tag.class), null, s); }
+        private boolean match(tag t, Class c, String s) {
+            if (t==null) return false;
+            if (t.value().equals(s)) return true;
+            if (c != null && t.equals("") && c.getSimpleName().equals(s)) return true;
+            return false;
+        }
+        private boolean match(nonterminal t, Class c, String s) {
+            if (t==null) return false;
+            if (t.value().equals(s)) return true;
+            if (c != null && t.equals("") && c.getSimpleName().equals(s)) return true;
+            return false;
+        }
+        private boolean match(Class c, String s, String nonTerminalName) {
+            if (match((tag)c.getAnnotation(tag.class), c, s)) return true;
+            if (match((nonterminal)c.getAnnotation(nonterminal.class), c, nonTerminalName)) return true;
+            return false;
+        }
+        public boolean match(Constructor con, String s, String nonTerminalName) {
+            Class c = con.getDeclaringClass();
+            if (match((tag)con.getAnnotation(tag.class), null, s)) return true;
+            if (match((nonterminal)con.getAnnotation(nonterminal.class), c, s)) return true;
+            return false;
+        }
+        public Object repeatTag() {
+            return new Reducer() {
+                    public String toString() { return "[**]"; }
+                    public Object reduce(Tree t) {
+                        Object[] ret = new Object[t.numChildren()];
+                        for(int i=0; i<t.numChildren(); i++) {
+                            Tree tc = t.child(i);
+                            if (tc.head() != null && tc.head() instanceof Reducer)
+                                ret[i] = ((Reducer)tc.head()).reduce(tc);
+                            else if (tc.numChildren() == 0)
+                                ret[i] = tc.head();
+                            else {
+                                System.err.println("FIXME: don't know what to do about " + tc);
+                                ret[i] = null;
+                            }
+                        }
+                        return ret;
+                    }
+                };
+        }
+        public Sequence resolveTag(String tag, String nonTerminalName, Element[] els, Object[] labels, boolean[] drops) {
+            Production p = new Production(tag, nonTerminalName, els, labels, drops);
+            for(Method m : _cl.getMethods())
+                if (new TargetMethod(m).isCompatible(p))
+                    return new TargetMethod(m).makeSequence(p);
+            for(Class c : _inner)
+                for(Constructor con : c.getConstructors())
+                    if (new TargetConstructor(con).isCompatible(p))
+                        return new TargetConstructor(con).makeSequence(p);
+            for(Class c : _inner)
+                if (new TargetClass(c).isCompatible(p))
+                    return new TargetClass(c).makeSequence(p);
+            throw new RuntimeException("could not find a Java method/class/ctor matching tag \""+tag+"\", nonterminal \""+nonTerminalName+"\"");
+        }
+    }
+    /*
+    public static Object makeFlattener(final Method m, final Element[] els, final Object[] labels, final boolean[] drops) {
+        return new Reducer() {
+                public Object reduce(Tree t) {
+                    Object[] o = new Object[m.getParameterTypes()];
+                    int j = 0;
+                    for(int i=0; i<els.length; i++)
+                }
+            };
+    }
+    */
+
+    
+    /**
+     *  Constructors, classes, and methods with this attribute will
+     *  match every production of the nonterminal called "value()"
+     *  that is arg-compatible.  If value() is undefined, then the
+     *  class/constructor/method name is used.
+     */ 
+    @Retention(RetentionPolicy.RUNTIME) public static @interface nonterminal { String value() default ""; }
+
+    /**
+     *  Constructors, classes, and methods with this attribute will
+     *  match every tree tagged with "value()" that is arg-compatible.
+     *  If value() is undefined, then the class/constructor/method
+     *  name is used.
+     */ 
+    @Retention(RetentionPolicy.RUNTIME) public static @interface tag         { String value() default ""; }
+
+    /**
+     *  If any parameter to a method or field in a class has a named
+     *  arg-tag, that parameter/field matches the child of the tree
+     *  which either has that label or else is a reference to a
+     *  nonterminal with the corresponding name.
+     *  
+     *  The remaining non-named arg-tags match the remaining children
+     *  of the tree in sequential order.
+     *
+     *  If any arg-tagged parameters/fields remain, the match fails.
+     *  If there were no arg-tagged parameters-fields, it is as if all
+     *  of them were non-named and arg-tagged.
+     *
+     *  A method/constructor is arg-compatible if all of its arguments
+     *  are arg-compatible.
+     *
+     *  A class is arg-compatible if all of its fields are
+     *  arg-compatible, or if one of its constructors is arg-compatible.
+     *
+     */
+    @Retention(RetentionPolicy.RUNTIME) public static @interface arg         { String value() default ""; }
+
+    public static class Production {
+        public String tag;
+        public String nonTerminal;
+        public Object[] labels;
+        public boolean[] drops;
+        public Element[] elements;
+        public int count = 0;
+        public Production(String tag, String nonTerminal, Element[] elements, Object[] labels, boolean[] drops) {
+            this.tag = tag;
+            this.elements = elements; // FIXME: use this
+            this.nonTerminal = nonTerminal;
+            this.labels = labels;
+            this.drops = drops;
+            for(int i=0; i<drops.length; i++)
+                if (!drops[i])
+                    count++;
+        }
+    }
+
+    public static abstract class Target {
+        public abstract String getName();
+        public abstract tag getTag();
+        public abstract nonterminal getNonTerminal();
+        public abstract int[] buildSequence(Production p);
+        public boolean isCompatible(Production p) {
+            tag t = getTag();
+            if (t != null &&
+                (t.value().equals(p.tag) ||
+                 (t.value().equals("") && p.tag.equals(getName()))))
+                return buildSequence(p)!=null;
+
+            nonterminal n = getNonTerminal();
+            if (n != null &&
+                (n.value().equals(p.nonTerminal) ||
+                 (n.value().equals("") && p.nonTerminal.equals(getName()))))
+                return buildSequence(p)!=null;
+
+            return false;
+        }
+        public int[] buildSequence(Production p, String[] names, arg[] argtags) {
+            int argTagged = 0;
+            for(int i=0; i<argtags.length; i++)
+                if (argtags[i] != null)
+                    argTagged++;
+
+            // FIXME: can be smarter here
+            if (names.length==p.count) {
+                int[] ret = new int[p.count];
+                for(int i=0; i<p.count; i++) ret[i] = i;
+                return ret;
+            } else if (argTagged==p.count) {
+                int[] ret = new int[argtags.length];
+                int j = 0;
+                for(int i=0; i<argtags.length; i++)
+                    ret[i] = argtags[i]==null ? -1 : (j++);
+                return ret;
+            } else {
+                return null;
+            }
+        }
+        public Sequence makeSequence(Production p) {
+            return Sequence.rewritingSequence(new TargetReducer(p), p.elements, p.labels, p.drops);
+        }
+        public abstract Object plant(Object[] fields, int[] map);
+        public class TargetReducer implements Reducer {
+            private Production p;
+            private int[] map;
+            public TargetReducer(Production p) {
+                this.p = p;
+                this.map = buildSequence(p);
+            }
+            public String toString() { return "reducer-"+Target.this; }
+            public Object reduce(Tree t) {
+                Object[] objects = new Object[t.numChildren()];
+                for(int i=0; i<t.numChildren(); i++) {
+                    Tree tc = t.child(i);
+                    if (tc.head() != null && tc.head() instanceof Reducer)
+                        objects[i] = ((Reducer)tc.head()).reduce(tc);
+                    else if (tc.numChildren() == 0)
+                        objects[i] = tc.head();
+                    else if (t.numChildren()==1) {
+                        //FIXME: EVIL!!
+                        objects[i] = reduce(t.child(0));
+                    } else {
+                        System.err.println("FIXME: don't know what to do about " + tc);
+                        objects[i] = null;
+                    }
+                }
+                return plant(objects, map);
+            }
+        }
+    }
+
+    public static interface Reducer {
+        public Object reduce(Tree t);
     }
+
+    public static class TargetClass extends Target {
+        public final Class _class;
+        public TargetClass(Class _class) { this._class = _class; }
+        public String getName() { return _class.getSimpleName(); }
+        public tag getTag() { return (tag)_class.getAnnotation(tag.class); }
+        public nonterminal getNonTerminal() { return (nonterminal)_class.getAnnotation(nonterminal.class); }
+        public String toString() { return _class.getSimpleName(); }
+        public int[] buildSequence(Production p) {
+            Field[]  f       = _class.getDeclaredFields();
+            String[] names   = new String[f.length];
+            arg[]    argtags = new arg[f.length];
+            for(int i=0; i<f.length; i++) {
+                names[i]   = f[i].getName();
+                argtags[i] = f[i].getAnnotation(arg.class);
+            }
+            int[] ret = buildSequence(p, names, argtags);
+            if (ret!=null) return ret;
+            for(Constructor c : _class.getConstructors())
+                if (new TargetConstructor(c).buildSequence(p)!=null)
+                    return new TargetConstructor(c).buildSequence(p);
+            return null;
+        }
+        public Object plant(Object[] fields, int[] map) {
+            try {
+                Object ret = _class.newInstance();
+                Field[] f = _class.getFields();
+                int j = 0;
+                for(int i=0; i<f.length; i++)
+                    if (map[i] != -1) {
+                        Object tgt = Reflection.lub(fields[map[i]]);
+                        if (f[i].getType() == String.class) tgt = stringify(tgt);
+                        // FUGLY
+                        tgt = coerce(tgt, f[i].getType());
+                        System.err.println("setting a " + f[i].getType().getName() + " to " + Reflection.show(tgt));
+                        f[i].set(ret, tgt);
+                    }
+                return ret;
+            } catch (Exception e) {
+                e.printStackTrace();
+                throw new RuntimeException(e);
+            }
+        }
+    }
+
+    public static String stringify(Object o) {
+        if (o==null) return "";
+        if (!(o instanceof Object[])) return o.toString();
+        Object[] arr = (Object[])o;
+        StringBuffer ret = new StringBuffer();
+        for(int i=0; i<arr.length; i++)
+            ret.append(arr[i]);
+        return ret.toString();
+    }
+
+    public static class TargetConstructor extends Target {
+        public final Constructor _ctor;
+        public TargetConstructor(Constructor _ctor) { this._ctor = _ctor; }
+        public String getName() { return _ctor.getName(); }
+        public tag getTag() { return (tag)_ctor.getAnnotation(tag.class); }
+        public nonterminal getNonTerminal() { return (nonterminal)_ctor.getAnnotation(nonterminal.class); }
+        public String toString() { return _ctor.getName(); }
+        public int[] buildSequence(Production p) {
+            Annotation[][] annotations = _ctor.getParameterAnnotations();
+            int len = annotations.length;
+            int ofs = 0;
+            String name = _ctor.getDeclaringClass().getName();
+            /*
+            if (name.indexOf('$') > name.lastIndexOf('.')) {
+                len--;
+                ofs++;
+            }
+            */
+            String[] names   = new String[len];
+            arg[]    argtags = new arg[len];
+            for(int i=0; i<names.length; i++)
+                for(Annotation a : annotations[i+ofs])
+                    if (a instanceof arg)
+                        argtags[i+ofs] = (arg)a;
+            return buildSequence(p, names, argtags);
+        }
+        public Object plant(Object[] fields, int[] map) {
+            try {
+                Class[] argTypes = _ctor.getParameterTypes();
+                Object[] args = new Object[argTypes.length];
+                int j = 0;
+                for(int i=0; i<args.length; i++)
+                    if (map[i] != -1) {
+                        Object tgt = Reflection.lub(fields[map[i]]);
+                        if (argTypes[i] == String.class) tgt = stringify(tgt);
+                        // FUGLY
+                        tgt = coerce(tgt, argTypes[i]);
+                        System.err.println("setting a " + argTypes[i].getName() + " to " + Reflection.show(tgt));
+                        args[i] = tgt;
+                    }
+                return _ctor.newInstance(args);
+            } catch (Exception e) {
+                throw new RuntimeException(e);
+            }
+        }
+    }
+    public static class TargetMethod extends Target {
+        public final Method _method;
+        public TargetMethod(Method _method) { this._method = _method; }
+        public String getName() { return _method.getName(); }
+        public String toString() { return _method.getName(); }
+        public tag getTag() { return (tag)_method.getAnnotation(tag.class); }
+        public nonterminal getNonTerminal() { return (nonterminal)_method.getAnnotation(nonterminal.class); }
+        public int[] buildSequence(Production p) {
+            Annotation[][] annotations = _method.getParameterAnnotations();
+            String[] names   = new String[annotations.length];
+            arg[]    argtags = new arg[annotations.length];
+            for(int i=0; i<names.length; i++)
+                for(Annotation a : annotations[i])
+                    if (a instanceof arg)
+                        argtags[i] = (arg)a;
+            int[] ret = buildSequence(p, names, argtags);
+            return ret;
+        }
+        public Object plant(Object[] fields, int[] map) {
+            try {
+                Class[] argTypes = _method.getParameterTypes();
+                Object[] args = new Object[argTypes.length];
+                int j = 0;
+                for(int i=0; i<args.length; i++)
+                    if (map[i] != -1) {
+                        Object tgt = Reflection.lub(fields[map[i]]);
+                        if (argTypes[i] == String.class) tgt = stringify(tgt);
+                        // FUGLY
+                        tgt = coerce(tgt, argTypes[i]);
+                        System.err.println("setting a " + argTypes[i].getName() + " to " + Reflection.show(tgt));
+                        args[i] = tgt;
+                    }
+                return _method.invoke(null, args);
+            } catch (Exception e) {
+                throw new RuntimeException(e);
+            }
+        }
+    }
+
+    public static Object coerce(Object o, Class c) {
+        if (o==null) return null;
+        if (c.isInstance(o)) return o;
+        if (c == char.class) {
+            return o.toString().charAt(0);
+        }
+        if (c.isArray() && (c.getComponentType().isInstance(o))) {
+            Object[] ret = (Object[])Array.newInstance(c.getComponentType(), 1);
+            ret[0] = o;
+            return ret;
+        }
+        if (o.getClass().isArray() && c.isArray()) {
+            boolean ok = true;
+            for(int i=0; i<((Object[])o).length; i++) {
+                Object ob = (((Object[])o)[i]);
+                if (ob != null) {
+                    System.err.println("no hit with " + c.getComponentType().getName() + " on " + Reflection.show(((Object[])o)[i]));
+                    ok = false;
+                }
+            }
+            if (ok) {
+                System.err.println("hit with " + c.getComponentType().getName());
+                return Array.newInstance(c.getComponentType(), ((Object[])o).length);
+            }
+        }
+        return o;
+    }
+
+    public static class MG {
+        public static @tag Grammar grammar(Grammar g) { return g; }
+        public static @nonterminal class Grammar {
+            public @arg("NonTerminal") NonTerminal[] nonterminals;
+            public String toString() {
+                String ret = "[ ";
+                for(NonTerminal nt : nonterminals) ret += nt + ", ";
+                return ret + " ]";
+            }
+        }
+        public static @nonterminal class NonTerminal extends El {
+            public @arg("Word") String  name;
+            public @arg("RHS")  Seq[][] sequences;
+        }
+
+        public static @tag void range(char c) { }
+        public static class Range extends El {
+            public @tag("range") Range(char only) { first = only; last = only; }
+            public @tag("-")     Range(char first, char last) { this.first = first; this.last = last; }
+            public char first;
+            public char last;
+        }
+        public static class El { }
+        public static /*abstract*/ @nonterminal("Sequence") class Seq extends El { }
+        public static @tag("&")   Seq and(Sequence s,    El[] elements) { return new Seq(); }
+        public static @tag("&~")  Seq andnot(Sequence s, El[] elements) { return new Seq(); }
+        public static @tag        Seq ps(El[] elements) { return new Seq(); }
+        public static @tag        Seq psx(Seq s) { return s; }
+        public static @tag("::")  Seq tag(String tagname, Seq seq) { return new Seq(); }
+        public static @tag(":")   void colon(String s, El e) { }
+        public static @tag(")")   void close(String foo) { }
+        public static @tag("/")   Seq slash(Seq s, El e) { return new Seq(); }
+        public static @tag("->")  Seq arrow(Seq s, El e) { return new Seq(); }
+
+        public static @tag("nonTerminal") class NonTerminalReference extends El { public @arg String nonTerminal; }
+        public static @tag("literal")     class StringLiteral        extends El { public @arg String string; }
+        public static @tag("()")          class Epsilon              extends El { }
+        public static @tag("{")           class Tree                 extends El { public @arg Seq body; }
+        public static                     class CharClass            extends El { public @tag("[") CharClass(Range[] ranges) { } }
+
+        public static @tag("++")  void plusmax(El e) { }
+        public static @tag("+")   void plus(El e) { }
+        public static @tag("++/") void plusmaxfollow(El e, El sep) { }
+        public static @tag("+/")  void plusfollow(El e, El sep) { }
+        public static @tag("**")  void starmax(El e) { }
+        public static @tag("*")   void star(El e) { }
+        public static @tag("**/") void starmaxfollow(El e, El sep) { }
+        public static @tag("*/")  void starfollow(El e, El sep) { }
+        public static @tag("!")   void bang(El e) { }
+        public static @tag("?")   void question(El e) { }
+        public static @tag("^")   void caret(String s) { }
+        public static @tag("~")   void tilde(El e) { }
+        public static @tag("^^")  void doublecaret(El e) { }
+        public static @tag("(")   void subexpression(Seq[][] rhs) { }
+
+        public static @nonterminal("Word")    String word(String s) { return null; }
+        public static @nonterminal("Quoted")  String quoted(String s) { return null; }
+        public static @nonterminal("escaped") String c(char c) { return null; }
+        public static @tag("\"\"")            String emptystring() { return null; }
+        public static @tag("\r")              String lf() { return null; }
+        public static @tag("\n")              String cr() { return null; }
+    }
+
 }