2010-03-01 02:50:56 +01:00
|
|
|
package com.metaweb.gridworks.expr;
|
|
|
|
|
2010-03-11 00:43:21 +01:00
|
|
|
import java.io.StringReader;
|
|
|
|
import java.util.Properties;
|
|
|
|
|
|
|
|
import clojure.lang.IFn;
|
|
|
|
|
2010-03-01 02:50:56 +01:00
|
|
|
import com.metaweb.gridworks.gel.Parser;
|
|
|
|
|
|
|
|
abstract public class MetaParser {
|
2010-03-22 01:54:56 +01:00
|
|
|
/**
|
|
|
|
* Parse an expression that might have a language prefix into an Evaluable.
|
|
|
|
* Expressions without valid prefixes or without any prefix are assumed to be
|
|
|
|
* GEL expressions.
|
|
|
|
*
|
|
|
|
* @param s
|
|
|
|
* @return
|
|
|
|
* @throws ParsingException
|
|
|
|
*/
|
2010-03-01 02:50:56 +01:00
|
|
|
static public Evaluable parse(String s) throws ParsingException {
|
|
|
|
String language = "gel";
|
|
|
|
|
|
|
|
int colon = s.indexOf(':');
|
|
|
|
if (colon >= 0) {
|
|
|
|
language = s.substring(0, colon);
|
|
|
|
}
|
|
|
|
|
|
|
|
if ("jython".equalsIgnoreCase(language)) {
|
|
|
|
return parseJython(s.substring(colon + 1));
|
|
|
|
} else if ("clojure".equalsIgnoreCase(language)) {
|
|
|
|
return parseClojure(s.substring(colon + 1));
|
|
|
|
} else if ("gel".equalsIgnoreCase(language)) {
|
|
|
|
return parseGEL(s.substring(colon + 1));
|
|
|
|
} else {
|
|
|
|
return parseGEL(s);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
static protected Evaluable parseGEL(String s) throws ParsingException {
|
|
|
|
Parser parser = new Parser(s);
|
|
|
|
|
|
|
|
return parser.getExpression();
|
|
|
|
}
|
|
|
|
|
|
|
|
static protected Evaluable parseJython(String s) throws ParsingException {
|
2010-03-11 00:43:21 +01:00
|
|
|
return new JythonEvaluable(s);
|
2010-03-01 02:50:56 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
static protected Evaluable parseClojure(String s) throws ParsingException {
|
|
|
|
try {
|
|
|
|
IFn fn = (IFn) clojure.lang.Compiler.load(new StringReader(
|
2010-03-11 00:43:21 +01:00
|
|
|
"(fn [value cell cells row rowIndex] " + s + ")"
|
2010-03-01 02:50:56 +01:00
|
|
|
));
|
|
|
|
|
|
|
|
return new Evaluable() {
|
2010-03-11 00:43:21 +01:00
|
|
|
private IFn _fn;
|
2010-03-01 02:50:56 +01:00
|
|
|
|
|
|
|
public Evaluable init(IFn fn) {
|
|
|
|
_fn = fn;
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
|
|
|
public Object evaluate(Properties bindings) {
|
|
|
|
try {
|
|
|
|
return _fn.invoke(
|
2010-03-11 00:43:21 +01:00
|
|
|
bindings.get("value"),
|
|
|
|
bindings.get("cell"),
|
|
|
|
bindings.get("cells"),
|
|
|
|
bindings.get("row"),
|
|
|
|
bindings.get("rowIndex")
|
2010-03-01 02:50:56 +01:00
|
|
|
);
|
|
|
|
} catch (Exception e) {
|
|
|
|
return new EvalError(e.getMessage());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}.init(fn);
|
|
|
|
} catch (Exception e) {
|
2010-03-11 00:43:21 +01:00
|
|
|
throw new ParsingException(e.getMessage());
|
2010-03-01 02:50:56 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|