Search in sources :

Example 6 with WorkingMemory

use of org.mvel2.tests.core.res.WorkingMemory in project drools by kiegroup.

the class MVELEvalExpression method evaluate.

public boolean evaluate(final Tuple tuple, final Declaration[] requiredDeclarations, final WorkingMemory workingMemory, final Object context) throws Exception {
    VariableResolverFactory factory = (VariableResolverFactory) context;
    unit.updateFactory(null, (LeftTuple) tuple, null, (InternalWorkingMemory) workingMemory, workingMemory.getGlobalResolver(), factory);
    // do we have any functions for this namespace?
    InternalKnowledgePackage pkg = workingMemory.getKnowledgeBase().getPackage("MAIN");
    if (pkg != null) {
        MVELDialectRuntimeData data = (MVELDialectRuntimeData) pkg.getDialectRuntimeRegistry().getDialectData(this.id);
        factory.setNextFactory(data.getFunctionFactory());
    }
    final Boolean result = (Boolean) MVEL.executeExpression(this.expr, null, factory);
    return result.booleanValue();
}
Also used : MVELDialectRuntimeData(org.drools.core.rule.MVELDialectRuntimeData) VariableResolverFactory(org.mvel2.integration.VariableResolverFactory) InternalKnowledgePackage(org.drools.core.definitions.InternalKnowledgePackage)

Example 7 with WorkingMemory

use of org.mvel2.tests.core.res.WorkingMemory in project drools by kiegroup.

the class ASMPredicateStubBuilder method createStubPredicate.

private void createStubPredicate(final ClassGenerator generator, final InvokerDataProvider data, final Map vars) {
    generator.setInterfaces(PredicateStub.class, CompiledInvoker.class).addField(ACC_PRIVATE + ACC_VOLATILE, "predicate", PredicateExpression.class);
    generator.addMethod(ACC_PUBLIC, "createContext", generator.methodDescr(Object.class), new ClassGenerator.MethodBody() {

        public void body(MethodVisitor mv) {
            mv.visitInsn(ACONST_NULL);
            mv.visitInsn(ARETURN);
        }
    }).addMethod(ACC_PUBLIC, "evaluate", generator.methodDescr(Boolean.TYPE, InternalFactHandle.class, Tuple.class, Declaration[].class, Declaration[].class, WorkingMemory.class, Object.class), new String[] { "java/lang/Exception" }, new ClassGenerator.MethodBody() {

        public void body(MethodVisitor mv) {
            Label syncStart = new Label();
            Label syncEnd = new Label();
            Label l1 = new Label();
            Label l2 = new Label();
            mv.visitTryCatchBlock(syncStart, l1, l2, null);
            Label l3 = new Label();
            mv.visitTryCatchBlock(l2, l3, l2, null);
            getFieldFromThis("predicate", PredicateExpression.class);
            mv.visitJumpInsn(IFNONNULL, syncEnd);
            mv.visitVarInsn(ALOAD, 0);
            mv.visitInsn(DUP);
            mv.visitVarInsn(ASTORE, 7);
            // synchronized(this) {
            mv.visitInsn(MONITORENTER);
            mv.visitLabel(syncStart);
            getFieldFromThis("predicate", PredicateExpression.class);
            // if (predicate == null) ...
            Label ifNotInitialized = new Label();
            mv.visitJumpInsn(IFNONNULL, ifNotInitialized);
            mv.visitVarInsn(ALOAD, 0);
            mv.visitVarInsn(ALOAD, 2);
            mv.visitVarInsn(ALOAD, 3);
            mv.visitVarInsn(ALOAD, 4);
            mv.visitVarInsn(ALOAD, 5);
            // ... PredicateGenerator.generate(this, tuple, declarations, declarations, workingMemory)
            invokeStatic(PredicateGenerator.class, "generate", null, PredicateStub.class, Tuple.class, Declaration[].class, Declaration[].class, WorkingMemory.class);
            mv.visitLabel(ifNotInitialized);
            mv.visitVarInsn(ALOAD, 7);
            mv.visitInsn(MONITOREXIT);
            mv.visitLabel(l1);
            mv.visitJumpInsn(GOTO, syncEnd);
            mv.visitLabel(l2);
            mv.visitVarInsn(ASTORE, 8);
            mv.visitVarInsn(ALOAD, 7);
            mv.visitInsn(MONITOREXIT);
            mv.visitLabel(l3);
            mv.visitVarInsn(ALOAD, 8);
            mv.visitInsn(ATHROW);
            mv.visitLabel(syncEnd);
            // } end of synchronized
            getFieldFromThis("predicate", PredicateExpression.class);
            mv.visitVarInsn(ALOAD, 1);
            mv.visitVarInsn(ALOAD, 2);
            mv.visitVarInsn(ALOAD, 3);
            mv.visitVarInsn(ALOAD, 4);
            mv.visitVarInsn(ALOAD, 5);
            mv.visitVarInsn(ALOAD, 6);
            invokeInterface(PredicateExpression.class, "evaluate", Boolean.TYPE, InternalFactHandle.class, Tuple.class, Declaration[].class, Declaration[].class, WorkingMemory.class, Object.class);
            mv.visitInsn(IRETURN);
        }
    }).addMethod(ACC_PUBLIC, "setPredicate", generator.methodDescr(null, PredicateExpression.class), new ClassGenerator.MethodBody() {

        public void body(MethodVisitor mv) {
            putFieldInThisFromRegistry("predicate", PredicateExpression.class, 1);
            mv.visitInsn(RETURN);
        }
    });
}
Also used : ClassGenerator(org.drools.core.rule.builder.dialect.asm.ClassGenerator) PredicateStub(org.drools.core.rule.builder.dialect.asm.PredicateStub) Label(org.mvel2.asm.Label) Declaration(org.drools.core.rule.Declaration) PredicateExpression(org.drools.core.spi.PredicateExpression) CompiledInvoker(org.drools.core.spi.CompiledInvoker) MethodVisitor(org.mvel2.asm.MethodVisitor)

Example 8 with WorkingMemory

use of org.mvel2.tests.core.res.WorkingMemory in project drools by kiegroup.

the class ASMConsequenceBuilder method createConsequenceBytecode.

protected byte[] createConsequenceBytecode(RuleBuildContext ruleContext, final Map<String, Object> consequenceContext) {
    final InvokerDataProvider data = new InvokerContext(consequenceContext);
    final String name = (String) consequenceContext.get("consequenceName");
    final Declaration[] declarations = (Declaration[]) consequenceContext.get("declarations");
    final ClassGenerator generator = InvokerGenerator.createInvokerClassGenerator(data, ruleContext).setInterfaces(Consequence.class, CompiledInvoker.class);
    generator.addMethod(ACC_PUBLIC, "getName", generator.methodDescr(String.class), new ClassGenerator.MethodBody() {

        public void body(MethodVisitor mv) {
            push(name);
            mv.visitInsn(ARETURN);
        }
    }).addMethod(ACC_PUBLIC, "evaluate", generator.methodDescr(null, KnowledgeHelper.class, WorkingMemory.class), new String[] { "java/lang/Exception" }, new GeneratorHelper.EvaluateMethod() {

        public void body(MethodVisitor mv) {
            // Tuple tuple = knowledgeHelper.getTuple();
            mv.visitVarInsn(ALOAD, 1);
            invokeInterface(KnowledgeHelper.class, "getTuple", Tuple.class);
            mv.visitVarInsn(ASTORE, 3);
            // Declaration[] declarations = ((RuleTerminalNode)knowledgeHelper.getMatch().getTuple().getTupleSink()).getDeclarations();
            mv.visitVarInsn(ALOAD, 1);
            invokeInterface(KnowledgeHelper.class, "getMatch", Activation.class);
            invokeInterface(Activation.class, "getTuple", Tuple.class);
            invokeInterface(Tuple.class, "getTupleSink", Sink.class);
            cast(RuleTerminalNode.class);
            invokeVirtual(RuleTerminalNode.class, "getRequiredDeclarations", Declaration[].class);
            mv.visitVarInsn(ASTORE, 4);
            final String[] globals = data.getGlobals();
            final String[] globalTypes = data.getGlobalTypes();
            final Boolean[] notPatterns = (Boolean[]) consequenceContext.get("notPatterns");
            int[] paramsPos = new int[declarations.length];
            int offset = 5;
            for (int i = 0; i < declarations.length; i++) {
                int factPos = offset;
                int objPos = ++offset;
                paramsPos[i] = factPos;
                // Object obj[i] = tuple.get(declarations[i]);
                // org.kie.spi.Tuple
                mv.visitVarInsn(ALOAD, 3);
                // org.kie.rule.Declaration[]
                mv.visitVarInsn(ALOAD, 4);
                // i
                push(i);
                // declarations[i]
                mv.visitInsn(AALOAD);
                invokeInterface(Tuple.class, "get", InternalFactHandle.class, Declaration.class);
                // fact[i]
                mv.visitVarInsn(ASTORE, factPos);
                // declarations[i].getValue((org.kie.common.InternalWorkingMemory)workingMemory, obj[i] );
                // org.kie.rule.Declaration[]
                mv.visitVarInsn(ALOAD, 4);
                // i
                push(i);
                // declarations[i]
                mv.visitInsn(AALOAD);
                // WorkingMemory
                mv.visitVarInsn(ALOAD, 2);
                cast(InternalWorkingMemory.class);
                // fact[i]
                mv.visitVarInsn(ALOAD, factPos);
                invokeInterface(InternalFactHandle.class, "getObject", Object.class);
                String readMethod = declarations[i].getNativeReadMethodName();
                boolean isObject = readMethod.equals("getValue");
                String returnedType = isObject ? "Ljava/lang/Object;" : typeDescr(declarations[i].getTypeName());
                mv.visitMethodInsn(INVOKEVIRTUAL, Declaration.class.getName().replace('.', '/'), readMethod, "(L" + InternalWorkingMemory.class.getName().replace('.', '/') + ";Ljava/lang/Object;)" + returnedType);
                if (isObject)
                    mv.visitTypeInsn(CHECKCAST, internalName(declarations[i].getTypeName()));
                // obj[i]
                offset += store(objPos, declarations[i].getTypeName());
                if (notPatterns[i]) {
                    mv.visitVarInsn(ALOAD, 1);
                    invokeInterface(KnowledgeHelper.class, "getWorkingMemory", WorkingMemory.class);
                    loadAsObject(objPos);
                    invokeInterface(WorkingMemory.class, "getFactHandle", FactHandle.class, Object.class);
                    cast(InternalFactHandle.class);
                    mv.visitVarInsn(ASTORE, factPos);
                }
            }
            // @{ruleClassName}.@{methodName}(KnowledgeHelper, @foreach{declr : declarations} Object, FactHandle @end)
            StringBuilder consequenceMethodDescr = new StringBuilder("(L" + KnowledgeHelper.class.getName().replace('.', '/') + ";");
            // KnowledgeHelper
            mv.visitVarInsn(ALOAD, 1);
            for (int i = 0; i < declarations.length; i++) {
                // obj[i]
                load(paramsPos[i] + 1);
                // fact[i]
                mv.visitVarInsn(ALOAD, paramsPos[i]);
                consequenceMethodDescr.append(typeDescr(declarations[i].getTypeName())).append("L" + FactHandle.class.getName().replace('.', '/') + ";");
            }
            // @foreach{type : globalTypes, identifier : globals} @{type} @{identifier} = ( @{type} ) workingMemory.getGlobal( "@{identifier}" );
            for (int i = 0; i < globals.length; i++) {
                // WorkingMemory
                mv.visitVarInsn(ALOAD, 2);
                push(globals[i]);
                invokeInterface(WorkingMemory.class, "getGlobal", Object.class, String.class);
                mv.visitTypeInsn(CHECKCAST, internalName(globalTypes[i]));
                consequenceMethodDescr.append(typeDescr(globalTypes[i]));
            }
            consequenceMethodDescr.append(")V");
            mv.visitMethodInsn(INVOKESTATIC, data.getInternalRuleClassName(), data.getMethodName(), consequenceMethodDescr.toString());
            mv.visitInsn(RETURN);
        }
    });
    return generator.generateBytecode();
}
Also used : InternalFactHandle(org.drools.core.common.InternalFactHandle) FactHandle(org.kie.api.runtime.rule.FactHandle) InternalWorkingMemory(org.drools.core.common.InternalWorkingMemory) WorkingMemory(org.drools.core.WorkingMemory) Activation(org.drools.core.spi.Activation) MethodVisitor(org.mvel2.asm.MethodVisitor) InternalWorkingMemory(org.drools.core.common.InternalWorkingMemory) ClassGenerator(org.drools.core.rule.builder.dialect.asm.ClassGenerator) GeneratorHelper(org.drools.core.rule.builder.dialect.asm.GeneratorHelper) Sink(org.drools.core.reteoo.Sink) KnowledgeHelper(org.drools.core.spi.KnowledgeHelper) Declaration(org.drools.core.rule.Declaration) InternalFactHandle(org.drools.core.common.InternalFactHandle) Tuple(org.drools.core.spi.Tuple) InvokerDataProvider(org.drools.core.rule.builder.dialect.asm.InvokerDataProvider) RuleTerminalNode(org.drools.core.reteoo.RuleTerminalNode)

Example 9 with WorkingMemory

use of org.mvel2.tests.core.res.WorkingMemory in project drools by kiegroup.

the class EvalGenerator method generate.

public static void generate(final EvalStub stub, final Tuple tuple, final Declaration[] declarations, final WorkingMemory workingMemory) {
    final String[] globals = stub.getGlobals();
    final String[] globalTypes = stub.getGlobalTypes();
    // Sort declarations based on their offset, so it can ascend the tuple's parents stack only once
    final List<DeclarationMatcher> declarationMatchers = matchDeclarationsToTuple(declarations);
    final ClassGenerator generator = createInvokerClassGenerator(stub, workingMemory).setInterfaces(EvalExpression.class, CompiledInvoker.class);
    generator.addMethod(ACC_PUBLIC, "createContext", generator.methodDescr(Object.class), new ClassGenerator.MethodBody() {

        public void body(MethodVisitor mv) {
            mv.visitInsn(ACONST_NULL);
            mv.visitInsn(ARETURN);
        }
    }).addMethod(ACC_PUBLIC, "clone", generator.methodDescr(EvalExpression.class), new ClassGenerator.MethodBody() {

        public void body(MethodVisitor mv) {
            mv.visitVarInsn(ALOAD, 0);
            mv.visitInsn(ARETURN);
        }
    }).addMethod(ACC_PUBLIC, "replaceDeclaration", generator.methodDescr(null, Declaration.class, Declaration.class)).addMethod(ACC_PUBLIC, "evaluate", generator.methodDescr(Boolean.TYPE, Tuple.class, Declaration[].class, WorkingMemory.class, Object.class), new String[] { "java/lang/Exception" }, new GeneratorHelper.EvaluateMethod() {

        public void body(MethodVisitor mv) {
            objAstorePos = 7;
            String[] expectedDeclarations = stub.getExpectedDeclarationTypes();
            int[] declarationsParamsPos = new int[declarations.length];
            mv.visitVarInsn(ALOAD, 1);
            cast(LeftTuple.class);
            // LeftTuple
            mv.visitVarInsn(ASTORE, 5);
            Tuple currentTuple = tuple;
            for (DeclarationMatcher matcher : declarationMatchers) {
                int i = matcher.getOriginalIndex();
                declarationsParamsPos[i] = objAstorePos;
                currentTuple = traverseTuplesUntilDeclaration(currentTuple, matcher.getRootDistance(), 5);
                mv.visitVarInsn(ALOAD, 2);
                push(i);
                // declarations[i]
                mv.visitInsn(AALOAD);
                // workingMemory
                mv.visitVarInsn(ALOAD, 3);
                mv.visitVarInsn(ALOAD, 5);
                invokeInterface(LeftTuple.class, "getFactHandle", InternalFactHandle.class);
                // tuple.getFactHandle().getObject()
                invokeInterface(InternalFactHandle.class, "getObject", Object.class);
                storeObjectFromDeclaration(declarations[i], expectedDeclarations[i]);
            }
            // @{ruleClassName}.@{methodName}(@foreach{declarations}, @foreach{globals})
            StringBuilder evalMethodDescr = new StringBuilder("(");
            for (int i = 0; i < declarations.length; i++) {
                // declarations[i]
                load(declarationsParamsPos[i]);
                evalMethodDescr.append(typeDescr(expectedDeclarations[i]));
            }
            // @foreach{type : globalTypes, identifier : globals} @{type} @{identifier} = ( @{type} ) workingMemory.getGlobal( "@{identifier}" );
            parseGlobals(globals, globalTypes, 3, evalMethodDescr);
            evalMethodDescr.append(")Z");
            mv.visitMethodInsn(INVOKESTATIC, stub.getInternalRuleClassName(), stub.getMethodName(), evalMethodDescr.toString());
            mv.visitInsn(IRETURN);
        }
    });
    stub.setEval(generator.<EvalExpression>newInstance());
}
Also used : WorkingMemory(org.drools.core.WorkingMemory) DeclarationMatcher(org.drools.core.rule.builder.dialect.asm.GeneratorHelper.DeclarationMatcher) LeftTuple(org.drools.core.reteoo.LeftTuple) MethodVisitor(org.mvel2.asm.MethodVisitor) EvalExpression(org.drools.core.spi.EvalExpression) GeneratorHelper.createInvokerClassGenerator(org.drools.core.rule.builder.dialect.asm.GeneratorHelper.createInvokerClassGenerator) InternalFactHandle(org.drools.core.common.InternalFactHandle) GeneratorHelper.matchDeclarationsToTuple(org.drools.core.rule.builder.dialect.asm.GeneratorHelper.matchDeclarationsToTuple) LeftTuple(org.drools.core.reteoo.LeftTuple) Tuple(org.drools.core.spi.Tuple)

Example 10 with WorkingMemory

use of org.mvel2.tests.core.res.WorkingMemory in project drools by kiegroup.

the class PredicateGenerator method generate.

public static void generate(final PredicateStub stub, final Tuple tuple, final Declaration[] previousDeclarations, final Declaration[] localDeclarations, final WorkingMemory workingMemory) {
    final String[] globals = stub.getGlobals();
    final String[] globalTypes = stub.getGlobalTypes();
    // Sort declarations based on their offset, so it can ascend the tuple's parents stack only once
    final List<DeclarationMatcher> declarationMatchers = matchDeclarationsToTuple(previousDeclarations);
    final ClassGenerator generator = createInvokerClassGenerator(stub, workingMemory).setInterfaces(PredicateExpression.class, CompiledInvoker.class);
    generator.addMethod(ACC_PUBLIC, "createContext", generator.methodDescr(Object.class), new ClassGenerator.MethodBody() {

        public void body(MethodVisitor mv) {
            mv.visitInsn(ACONST_NULL);
            mv.visitInsn(ARETURN);
        }
    }).addMethod(ACC_PUBLIC, "evaluate", generator.methodDescr(Boolean.TYPE, InternalFactHandle.class, Tuple.class, Declaration[].class, Declaration[].class, WorkingMemory.class, Object.class), new String[] { "java/lang/Exception" }, new GeneratorHelper.EvaluateMethod() {

        public void body(MethodVisitor mv) {
            objAstorePos = 9;
            int[] previousDeclarationsParamsPos = new int[previousDeclarations.length];
            mv.visitVarInsn(ALOAD, 1);
            invokeInterface(InternalFactHandle.class, "getObject", Object.class);
            mv.visitVarInsn(ASTORE, 1);
            mv.visitVarInsn(ALOAD, 2);
            cast(LeftTuple.class);
            // LeftTuple
            mv.visitVarInsn(ASTORE, 7);
            Tuple currentTuple = tuple;
            for (DeclarationMatcher matcher : declarationMatchers) {
                int i = matcher.getOriginalIndex();
                previousDeclarationsParamsPos[i] = objAstorePos;
                currentTuple = traverseTuplesUntilDeclaration(currentTuple, matcher.getRootDistance(), 7);
                mv.visitVarInsn(ALOAD, 3);
                push(i);
                // declarations[i]
                mv.visitInsn(AALOAD);
                // workingMemory
                mv.visitVarInsn(ALOAD, 5);
                mv.visitVarInsn(ALOAD, 7);
                invokeInterface(LeftTuple.class, "getFactHandle", InternalFactHandle.class);
                // tuple.getFactHandle().getObject()
                invokeInterface(InternalFactHandle.class, "getObject", Object.class);
                storeObjectFromDeclaration(previousDeclarations[i], previousDeclarations[i].getTypeName());
            }
            int[] localDeclarationsParamsPos = parseDeclarations(localDeclarations, 4, 2, 5, false);
            // @{ruleClassName}.@{methodName}(@foreach{previousDeclarations}, @foreach{localDeclarations}, @foreach{globals})
            StringBuilder predicateMethodDescr = new StringBuilder("(");
            for (int i = 0; i < previousDeclarations.length; i++) {
                // previousDeclarations[i]
                load(previousDeclarationsParamsPos[i]);
                predicateMethodDescr.append(typeDescr(previousDeclarations[i].getTypeName()));
            }
            for (int i = 0; i < localDeclarations.length; i++) {
                // localDeclarations[i]
                load(localDeclarationsParamsPos[i]);
                predicateMethodDescr.append(typeDescr(localDeclarations[i].getTypeName()));
            }
            // @foreach{type : globalTypes, identifier : globals} @{type} @{identifier} = ( @{type} ) workingMemory.getGlobal( "@{identifier}" );
            parseGlobals(globals, globalTypes, 5, predicateMethodDescr);
            predicateMethodDescr.append(")Z");
            mv.visitMethodInsn(INVOKESTATIC, stub.getInternalRuleClassName(), stub.getMethodName(), predicateMethodDescr.toString());
            mv.visitInsn(IRETURN);
        }
    });
    stub.setPredicate(generator.<PredicateExpression>newInstance());
}
Also used : WorkingMemory(org.drools.core.WorkingMemory) DeclarationMatcher(org.drools.core.rule.builder.dialect.asm.GeneratorHelper.DeclarationMatcher) LeftTuple(org.drools.core.reteoo.LeftTuple) MethodVisitor(org.mvel2.asm.MethodVisitor) GeneratorHelper.createInvokerClassGenerator(org.drools.core.rule.builder.dialect.asm.GeneratorHelper.createInvokerClassGenerator) InternalFactHandle(org.drools.core.common.InternalFactHandle) GeneratorHelper.matchDeclarationsToTuple(org.drools.core.rule.builder.dialect.asm.GeneratorHelper.matchDeclarationsToTuple) LeftTuple(org.drools.core.reteoo.LeftTuple) Tuple(org.drools.core.spi.Tuple)

Aggregations

VariableResolverFactory (org.mvel2.integration.VariableResolverFactory)14 MethodVisitor (org.mvel2.asm.MethodVisitor)9 MVELDialectRuntimeData (org.drools.core.rule.MVELDialectRuntimeData)8 InternalFactHandle (org.drools.core.common.InternalFactHandle)7 WorkingMemory (org.drools.core.WorkingMemory)6 InternalKnowledgePackage (org.drools.core.definitions.InternalKnowledgePackage)6 Tuple (org.drools.core.spi.Tuple)6 LeftTuple (org.drools.core.reteoo.LeftTuple)5 Declaration (org.drools.core.rule.Declaration)5 InternalWorkingMemory (org.drools.core.common.InternalWorkingMemory)4 ClassGenerator (org.drools.core.rule.builder.dialect.asm.ClassGenerator)4 DeclarationMatcher (org.drools.core.rule.builder.dialect.asm.GeneratorHelper.DeclarationMatcher)4 GeneratorHelper.createInvokerClassGenerator (org.drools.core.rule.builder.dialect.asm.GeneratorHelper.createInvokerClassGenerator)4 GeneratorHelper.matchDeclarationsToTuple (org.drools.core.rule.builder.dialect.asm.GeneratorHelper.matchDeclarationsToTuple)4 Label (org.mvel2.asm.Label)4 DroolsVarFactory (org.drools.core.base.mvel.MVELCompilationUnit.DroolsVarFactory)3 RuleTerminalNode (org.drools.core.reteoo.RuleTerminalNode)3 CompiledInvoker (org.drools.core.spi.CompiledInvoker)3 KnowledgeHelper (org.drools.core.spi.KnowledgeHelper)3 HashMap (java.util.HashMap)2