Search in sources :

Example 1 with AviatorEvaluatorInstance

use of com.googlecode.aviator.AviatorEvaluatorInstance in project aviatorscript by killme2008.

the class Reflector method fastGetProperty.

@SuppressWarnings("unchecked")
public static Object fastGetProperty(final String name, final String[] names, final Map<String, Object> env, final Target target, final boolean tryResolveStaticMethod, final int offset, final int len) {
    int max = Math.min(offset + len, names.length);
    for (int i = offset; i < max; i++) {
        String rName = AviatorJavaType.reserveName(names[i]);
        rName = rName != null ? rName : names[i];
        int arrayIndex = -1;
        String keyIndex = null;
        // https://commons.apache.org/proper/commons-beanutils/apidocs/org/apache/commons/beanutils/PropertyUtilsBean.html
        switch(rName.charAt(rName.length() - 1)) {
            case ']':
                int idx = rName.indexOf("[");
                if (idx < 0) {
                    throw new IllegalArgumentException("Should not happen, doesn't contains '['");
                }
                String rawName = rName;
                rName = rName.substring(0, idx);
                arrayIndex = Integer.valueOf(rawName.substring(idx + 1, rawName.length() - 1));
                break;
            case ')':
                idx = rName.indexOf("(");
                if (idx < 0) {
                    throw new IllegalArgumentException("Should not happen, doesn't contains '('");
                }
                rawName = rName;
                rName = rName.substring(0, idx);
                keyIndex = rawName.substring(idx + 1, rawName.length() - 1);
                break;
        }
        Object val = null;
        if (target.innerClazz != null) {
            final AviatorEvaluatorInstance instance = RuntimeUtils.getInstance(env);
            if (tryResolveStaticMethod && instance.isFeatureEnabled(Feature.StaticMethods) && names.length == 2) {
                val = fastGetProperty(target.innerClazz, rName, PropertyType.StaticMethod);
            } else if (instance.isFeatureEnabled(Feature.StaticFields)) {
                val = fastGetProperty(target.innerClazz, rName, PropertyType.StaticField);
            } else {
                val = fastGetProperty(target.innerClazz, rName, PropertyType.Getter);
            }
        } else {
            // in the format of a.b.[0].c
            if (rName.isEmpty()) {
                if (!(arrayIndex >= 0 || keyIndex != null)) {
                    throw new IllegalArgumentException("Invalid format");
                }
                if (target.innerEnv != null) {
                    val = target.innerEnv;
                } else {
                    val = target.targetObject;
                }
            } else {
                if (target.innerEnv != null) {
                    val = target.innerEnv.get(rName);
                    if (val == null && i == 0 && env instanceof Env) {
                        val = AviatorJavaType.tryResolveAsClass(env, rName);
                    }
                } else {
                    val = fastGetProperty(target.targetObject, rName, PropertyType.Getter);
                }
            }
        }
        if (arrayIndex >= 0) {
            if (val.getClass().isArray()) {
                val = ArrayUtils.get(val, arrayIndex);
            } else if (val instanceof List) {
                val = ((List) val).get(arrayIndex);
            } else if (val instanceof CharSequence) {
                val = ((CharSequence) val).charAt(arrayIndex);
            } else {
                throw new IllegalArgumentException("Can't access " + val + " with index `" + arrayIndex + "`, it's not an array, list or CharSequence");
            }
        }
        if (keyIndex != null) {
            if (Map.class.isAssignableFrom(val.getClass())) {
                val = ((Map) val).get(keyIndex);
            } else {
                throw new IllegalArgumentException("Can't access " + val + " with key `" + keyIndex + "`, it's not a map");
            }
        }
        if (i == max - 1) {
            return val;
        }
        if (val instanceof Map) {
            target.innerEnv = (Map<String, Object>) val;
            target.innerClazz = null;
            target.targetObject = null;
        } else if (val instanceof Class<?>) {
            target.innerClazz = (Class<?>) val;
            target.innerEnv = null;
            target.targetObject = null;
        } else if (val == null) {
            throw new NullPointerException(rName);
        } else {
            target.targetObject = val;
            target.innerEnv = null;
            target.innerClazz = null;
        }
    }
    return throwNoSuchPropertyException("Variable `" + name + "` not found in env: " + env);
}
Also used : AviatorEvaluatorInstance(com.googlecode.aviator.AviatorEvaluatorInstance) ArrayList(java.util.ArrayList) List(java.util.List) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Map(java.util.Map)

Example 2 with AviatorEvaluatorInstance

use of com.googlecode.aviator.AviatorEvaluatorInstance in project aviatorscript by killme2008.

the class InterpreterExample method main.

public static void main(final String[] args) {
    AviatorEvaluatorInstance engine = AviatorEvaluator.newInstance(EvalMode.INTERPRETER);
    // Enable tracing eval procedure(don't open it in production)
    engine.setOption(Options.TRACE_EVAL, true);
    Expression exp = engine.compile("score > 80 ? 'good' : 'bad'");
    System.out.println(exp.execute(exp.newEnv("score", 100)));
    System.out.println(exp.execute(exp.newEnv("score", 50)));
}
Also used : AviatorEvaluatorInstance(com.googlecode.aviator.AviatorEvaluatorInstance) Expression(com.googlecode.aviator.Expression)

Example 3 with AviatorEvaluatorInstance

use of com.googlecode.aviator.AviatorEvaluatorInstance in project aviatorscript by killme2008.

the class FunctionUtils method getFunction.

/**
 * Get a function from env in follow orders:
 * <ul>
 * <li>arg value</li>
 * <li>env</li>
 * <li>current evaluator instance.</li>
 * </ul>
 *
 * @param arg
 * @param env
 * @param arity
 * @return
 */
public static AviatorFunction getFunction(final AviatorObject arg, final Map<String, Object> env, final int arity) {
    if (arg.getAviatorType() != AviatorType.JavaType && arg.getAviatorType() != AviatorType.Lambda) {
        throw new ClassCastException(arg.desc(env) + " is not a function");
    }
    // Runtime type.
    Object val = null;
    if (arg instanceof AviatorFunction) {
        return (AviatorFunction) arg;
    }
    if (arg instanceof AviatorRuntimeJavaType && (val = arg.getValue(env)) instanceof AviatorFunction) {
        return (AviatorFunction) val;
    }
    // resolve by name.
    // special processing for "-" operator
    String name = ((AviatorJavaType) arg).getName();
    if (name.equals("-")) {
        if (arity == 2) {
            name = "-sub";
        } else {
            name = "-neg";
        }
    }
    AviatorFunction rt = null;
    if (env != null) {
        rt = (AviatorFunction) env.get(name);
    }
    if (rt == null) {
        AviatorEvaluatorInstance instance = RuntimeUtils.getInstance(env);
        rt = instance.getFunction(name);
    }
    return rt;
}
Also used : AviatorEvaluatorInstance(com.googlecode.aviator.AviatorEvaluatorInstance) AviatorRuntimeJavaType(com.googlecode.aviator.runtime.type.AviatorRuntimeJavaType) AviatorFunction(com.googlecode.aviator.runtime.type.AviatorFunction) AviatorJavaType(com.googlecode.aviator.runtime.type.AviatorJavaType) AviatorObject(com.googlecode.aviator.runtime.type.AviatorObject) AviatorString(com.googlecode.aviator.runtime.type.AviatorString)

Example 4 with AviatorEvaluatorInstance

use of com.googlecode.aviator.AviatorEvaluatorInstance in project aviatorscript by killme2008.

the class ConfigureEngine method main.

public static void main(final String[] args) throws Exception {
    final ScriptEngineManager sem = new ScriptEngineManager();
    ScriptEngine engine = sem.getEngineByName("AviatorScript");
    AviatorEvaluatorInstance instance = ((AviatorScriptEngine) engine).getEngine();
    // Use compatible feature set
    instance.setOption(Options.FEATURE_SET, Feature.getCompatibleFeatures());
    // Doesn't support if in compatible feature set mode.
    engine.eval("if(true) { println('support if'); }");
}
Also used : AviatorEvaluatorInstance(com.googlecode.aviator.AviatorEvaluatorInstance) AviatorScriptEngine(com.googlecode.aviator.script.AviatorScriptEngine) ScriptEngineManager(javax.script.ScriptEngineManager) ScriptEngine(javax.script.ScriptEngine) AviatorScriptEngine(com.googlecode.aviator.script.AviatorScriptEngine)

Example 5 with AviatorEvaluatorInstance

use of com.googlecode.aviator.AviatorEvaluatorInstance in project jcasbin by casbin.

the class BuiltInFunctionsUnitTest method testEvalFunc.

@Test
public void testEvalFunc() {
    AbacAPIUnitTest.TestEvalRule sub = new AbacAPIUnitTest.TestEvalRule("alice", 18);
    Map<String, Object> env = new HashMap<>();
    env.put("r_sub", sub);
    testEval("r_sub.age > 0", env, null, true);
    testEval("r_sub.name == 'alice'", env, null, true);
    testEval("r_sub.name == 'bob'", env, null, false);
    AviatorEvaluatorInstance aviatorEval = AviatorEvaluator.newInstance();
    aviatorEval.addFunction(new FunctionTest.CustomFunc());
    env.put("r_obj", "/test/url1/url2");
    testEval("r_sub.age >= 18 && custom(r_obj)", env, aviatorEval, true);
}
Also used : AviatorEvaluatorInstance(com.googlecode.aviator.AviatorEvaluatorInstance) HashMap(java.util.HashMap) Test(org.junit.Test)

Aggregations

AviatorEvaluatorInstance (com.googlecode.aviator.AviatorEvaluatorInstance)8 Map (java.util.Map)2 StringSegments (com.googlecode.aviator.AviatorEvaluatorInstance.StringSegments)1 BaseExpression (com.googlecode.aviator.BaseExpression)1 Expression (com.googlecode.aviator.Expression)1 AviatorFunction (com.googlecode.aviator.runtime.type.AviatorFunction)1 AviatorJavaType (com.googlecode.aviator.runtime.type.AviatorJavaType)1 AviatorObject (com.googlecode.aviator.runtime.type.AviatorObject)1 AviatorRuntimeJavaType (com.googlecode.aviator.runtime.type.AviatorRuntimeJavaType)1 AviatorString (com.googlecode.aviator.runtime.type.AviatorString)1 AviatorScriptEngine (com.googlecode.aviator.script.AviatorScriptEngine)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 List (java.util.List)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 ScriptEngine (javax.script.ScriptEngine)1 ScriptEngineManager (javax.script.ScriptEngineManager)1 Test (org.junit.Test)1