MAGx2
MAGx2

Reputation: 3189

Compile ClojureScript in Java application

I'm trying to compile String that contains Clojure Script code in Java/Groovy. I'm not really happy with using "java -jar ...".execute().

Is there any way to invoke clojurescript library (version 1.8.51) to compile code?

Edit: So combining these two links I got this code (Groovy):

    IFn require = Clojure.var("clojure.core", "require");
    require.invoke(Clojure.read("cljs.analyzer.api"))
    require.invoke(Clojure.read("cljs.compiler.api"))

    IFn emptyEnv = Clojure.var("cljs.analyzer.api", "empty-env")
    IFn analyze = Clojure.var("cljs.analyzer.api", "analyze")
    IFn emit = Clojure.var("cljs.compiler", "emit-str")

    final inputText = "(defn plus [a b] (+ a b))"
    emit.invoke(
            analyze.invoke(emptyEnv.invoke(), "'$inputText"
            )
    )

My problem is that emit function return empty string :/. Is there anything I'm doing wrong?

Edit2: The analyze method return this:

{
    :op :constant, 
    :env {:ns {:name cljs.user}, 
    :context :statement, 
    :locals {}, 
    :fn-scope [], 
    :js-globals ...removed..., 
    :form #object[org.codehaus.groovy.runtime.GStringImpl 0x37816ea6 "'(defn plus [a b] (+ a b))"], 
    :tag any
}

Upvotes: 1

Views: 178

Answers (1)

Piotrek Bzdyl
Piotrek Bzdyl

Reputation: 13185

It should be very easy to call ClojureScript Compiler API from Clojure, for example as presented in answers to a similar question on how to do it from Clojure.

But as you want to do it from Java or Groovy, you will have to use some Clojure Java API for calling Clojure from Java.

Upvotes: 1

Related Questions