mardi 24 mars 2015

Clojure RT/Compiler: How to Iterate through forms?

I am working on a Java project that has some Clojure involved. I know how to run compile and run clojure code:



public static void main(String[] args) throws Exception {
RT.init();
runCode();
}

public static Object runCode() {
String str = "(ns my-ns)" +
"(defn add [a b] (+ a b))" +
"(println (add 1 2))";

Compiler.load(new StringReader(str));

/* I know how to invoke it: */
Var foo = RT.var("my-ns", "add");
return foo.invoke(1,2);
}


What would be very useful at the point is to have a way to iterate over forms in Java, and in some sense "analyze" the compiler output. Basic things I want to know is:



  1. What is the text source of a form?

  2. What function is being called in a form.

  3. What arguments are being passed to the function (forms are ok)

  4. Be able to do this on top level forms, or drill in as needed.


Is there a way to do this using the clojure compiler, or runtime (or other Java classes in Clojure?) I see such compiler methods as analyze, for example:



Expr target = analyze(C.EXPRESSION, RT.second(form));


Though its not clear to me yet how form was constructed, and there are no Javadoc :-). Do I need to go The Compiler Source and figure out how it works?


Aucun commentaire:

Enregistrer un commentaire