Search in sources :

Example 6 with MVELCompilationUnit

use of org.drools.core.base.mvel.MVELCompilationUnit in project drools by kiegroup.

the class MVELConsequenceBuilder method build.

public void build(final RuleBuildContext context, String consequenceName) {
    // pushing consequence LHS into the stack for variable resolution
    context.getDeclarationResolver().pushOnBuildStack(context.getRule().getLhs());
    try {
        MVELDialect dialect = (MVELDialect) context.getDialect("mvel");
        final RuleDescr ruleDescr = context.getRuleDescr();
        String text = (RuleImpl.DEFAULT_CONSEQUENCE_NAME.equals(consequenceName)) ? (String) ruleDescr.getConsequence() : (String) ruleDescr.getNamedConsequences().get(consequenceName);
        text = processMacros(text);
        Map<String, Declaration> decls = context.getDeclarationResolver().getDeclarations(context.getRule());
        AnalysisResult analysis = dialect.analyzeBlock(context, text, new BoundIdentifiers(DeclarationScopeResolver.getDeclarationClasses(decls), context, Collections.EMPTY_MAP, KnowledgeHelper.class), null, "drools", KnowledgeHelper.class);
        if (analysis == null) {
            // something bad happened, issue already logged in errors
            return;
        }
        final BoundIdentifiers usedIdentifiers = analysis.getBoundIdentifiers();
        final Declaration[] declarations = new Declaration[usedIdentifiers.getDeclrClasses().size()];
        String[] declrStr = new String[declarations.length];
        int j = 0;
        for (String str : usedIdentifiers.getDeclrClasses().keySet()) {
            declrStr[j] = str;
            declarations[j++] = decls.get(str);
        }
        Arrays.sort(declarations, SortDeclarations.instance);
        for (int i = 0; i < declrStr.length; i++) {
            declrStr[i] = declarations[i].getIdentifier();
        }
        context.getRule().setRequiredDeclarationsForConsequence(consequenceName, declrStr);
        MVELCompilationUnit unit = dialect.getMVELCompilationUnit(text, analysis, declarations, null, null, context, "drools", KnowledgeHelper.class, false, MVELCompilationUnit.Scope.CONSEQUENCE);
        MVELConsequence expr = new MVELConsequence(unit, dialect.getId(), consequenceName);
        if (RuleImpl.DEFAULT_CONSEQUENCE_NAME.equals(consequenceName)) {
            context.getRule().setConsequence(expr);
        } else {
            context.getRule().addNamedConsequence(consequenceName, expr);
        }
        MVELDialectRuntimeData data = (MVELDialectRuntimeData) context.getPkg().getDialectRuntimeRegistry().getDialectData("mvel");
        data.addCompileable(context.getRule(), expr);
        expr.compile(data, context.getRule());
    } catch (final Exception e) {
        copyErrorLocation(e, context.getRuleDescr());
        context.addError(new DescrBuildError(context.getParentDescr(), context.getRuleDescr(), null, "Unable to build expression for 'consequence': " + e.getMessage() + " '" + context.getRuleDescr().getConsequence() + "'"));
    }
}
Also used : MVELCompilationUnit(org.drools.core.base.mvel.MVELCompilationUnit) MVELConsequence(org.drools.core.base.mvel.MVELConsequence) AnalysisResult(org.drools.compiler.compiler.AnalysisResult) BoundIdentifiers(org.drools.compiler.compiler.BoundIdentifiers) MVELDialectRuntimeData(org.drools.core.rule.MVELDialectRuntimeData) DescrBuildError(org.drools.compiler.compiler.DescrBuildError) RuleDescr(org.drools.compiler.lang.descr.RuleDescr) KnowledgeHelper(org.drools.core.spi.KnowledgeHelper) Declaration(org.drools.core.rule.Declaration)

Example 7 with MVELCompilationUnit

use of org.drools.core.base.mvel.MVELCompilationUnit in project drools by kiegroup.

the class MVELDialect method getMVELCompilationUnit.

public MVELCompilationUnit getMVELCompilationUnit(final String expression, final AnalysisResult analysis, Declaration[] previousDeclarations, Declaration[] localDeclarations, final Map<String, Class<?>> otherInputVariables, final PackageBuildContext context, String contextIndeifier, Class kcontextClass, boolean readLocalsFromTuple, MVELCompilationUnit.Scope scope) {
    Map<String, Class> resolvedInputs = new LinkedHashMap<String, Class>();
    List<String> ids = new ArrayList<String>();
    if (analysis.getBoundIdentifiers().getThisClass() != null || (localDeclarations != null && localDeclarations.length > 0)) {
        Class cls = analysis.getBoundIdentifiers().getThisClass();
        ids.add("this");
        resolvedInputs.put("this", // the only time cls is null is in accumumulate's acc/reverse
        (cls != null) ? cls : Object.class);
    }
    ids.add(contextIndeifier);
    resolvedInputs.put(contextIndeifier, kcontextClass);
    ids.add("kcontext");
    resolvedInputs.put("kcontext", kcontextClass);
    if (scope.hasRule()) {
        ids.add("rule");
        resolvedInputs.put("rule", Rule.class);
    }
    List<String> strList = new ArrayList<String>();
    for (String identifier : analysis.getIdentifiers()) {
        Class<?> type = analysis.getBoundIdentifiers().resolveVarType(identifier);
        if (type != null) {
            strList.add(identifier);
            ids.add(identifier);
            resolvedInputs.put(identifier, type);
        }
    }
    String[] globalIdentifiers = strList.toArray(new String[strList.size()]);
    strList.clear();
    for (String op : analysis.getBoundIdentifiers().getOperators().keySet()) {
        strList.add(op);
        ids.add(op);
        resolvedInputs.put(op, context.getConfiguration().getComponentFactory().getExpressionProcessor().getEvaluatorWrapperClass());
    }
    EvaluatorWrapper[] operators = new EvaluatorWrapper[strList.size()];
    for (int i = 0; i < operators.length; i++) {
        operators[i] = analysis.getBoundIdentifiers().getOperators().get(strList.get(i));
    }
    if (previousDeclarations != null) {
        for (Declaration decl : previousDeclarations) {
            if (analysis.getBoundIdentifiers().getDeclrClasses().containsKey(decl.getIdentifier())) {
                ids.add(decl.getIdentifier());
                resolvedInputs.put(decl.getIdentifier(), decl.getDeclarationClass());
            }
        }
    }
    if (localDeclarations != null) {
        for (Declaration decl : localDeclarations) {
            if (analysis.getBoundIdentifiers().getDeclrClasses().containsKey(decl.getIdentifier())) {
                ids.add(decl.getIdentifier());
                resolvedInputs.put(decl.getIdentifier(), decl.getDeclarationClass());
            }
        }
    }
    // "not bound" identifiers could be drools, kcontext and rule
    // but in the case of accumulate it could be vars from the "init" section.
    // String[] otherIdentifiers = otherInputVariables == null ? new String[]{} : new String[otherInputVariables.size()];
    strList = new ArrayList<String>();
    if (otherInputVariables != null) {
        MVELAnalysisResult mvelAnalysis = (MVELAnalysisResult) analysis;
        for (Entry<String, Class<?>> stringClassEntry : otherInputVariables.entrySet()) {
            if ((!analysis.getNotBoundedIdentifiers().contains(stringClassEntry.getKey()) && !mvelAnalysis.getMvelVariables().keySet().contains(stringClassEntry.getKey())) || "rule".equals(stringClassEntry.getKey())) {
                // and rule was already included
                continue;
            }
            ids.add(stringClassEntry.getKey());
            strList.add(stringClassEntry.getKey());
            resolvedInputs.put(stringClassEntry.getKey(), stringClassEntry.getValue());
        }
    }
    String[] otherIdentifiers = strList.toArray(new String[strList.size()]);
    String[] inputIdentifiers = new String[resolvedInputs.size()];
    String[] inputTypes = new String[resolvedInputs.size()];
    int i = 0;
    for (String id : ids) {
        inputIdentifiers[i] = id;
        inputTypes[i++] = resolvedInputs.get(id).getName();
    }
    String name;
    if (context != null && context.getPkg() != null && context.getPkg().getName() != null) {
        if (context instanceof RuleBuildContext) {
            name = context.getPkg().getName() + "." + ((RuleBuildContext) context).getRuleDescr().getClassName();
        } else {
            name = context.getPkg().getName() + ".Unknown";
        }
    } else {
        name = "Unknown";
    }
    return new MVELCompilationUnit(name, expression, globalIdentifiers, operators, previousDeclarations, localDeclarations, otherIdentifiers, inputIdentifiers, inputTypes, languageLevel, ((MVELAnalysisResult) analysis).isTypesafe(), readLocalsFromTuple);
}
Also used : EvaluatorWrapper(org.drools.core.base.EvaluatorWrapper) RuleBuildContext(org.drools.compiler.rule.builder.RuleBuildContext) ArrayList(java.util.ArrayList) MVELCompilationUnit(org.drools.core.base.mvel.MVELCompilationUnit) LinkedHashMap(java.util.LinkedHashMap) Declaration(org.drools.core.rule.Declaration)

Example 8 with MVELCompilationUnit

use of org.drools.core.base.mvel.MVELCompilationUnit in project drools by kiegroup.

the class MVELSalienceBuilder method build.

public void build(RuleBuildContext context) {
    boolean typesafe = context.isTypesafe();
    // pushing consequence LHS into the stack for variable resolution
    context.getDeclarationResolver().pushOnBuildStack(context.getRule().getLhs());
    try {
        // This builder is re-usable in other dialects, so specify by name
        MVELDialect dialect = (MVELDialect) context.getDialect("mvel");
        Map<String, Declaration> decls = context.getDeclarationResolver().getDeclarations(context.getRule());
        MVELAnalysisResult analysis = (MVELAnalysisResult) dialect.analyzeExpression(context, context.getRuleDescr(), context.getRuleDescr().getSalience(), new BoundIdentifiers(DeclarationScopeResolver.getDeclarationClasses(decls), context));
        context.setTypesafe(analysis.isTypesafe());
        final BoundIdentifiers usedIdentifiers = analysis.getBoundIdentifiers();
        int i = usedIdentifiers.getDeclrClasses().keySet().size();
        Declaration[] previousDeclarations = new Declaration[i];
        i = 0;
        for (String id : usedIdentifiers.getDeclrClasses().keySet()) {
            previousDeclarations[i++] = decls.get(id);
        }
        Arrays.sort(previousDeclarations, SortDeclarations.instance);
        MVELCompilationUnit unit = dialect.getMVELCompilationUnit(context.getRuleDescr().getSalience(), analysis, previousDeclarations, null, null, context, "drools", KnowledgeHelper.class, false, MVELCompilationUnit.Scope.EXPRESSION);
        MVELSalienceExpression expr = new MVELSalienceExpression(unit, dialect.getId());
        context.getRule().setSalience(KiePolicyHelper.isPolicyEnabled() ? new SafeSalience(expr) : expr);
        MVELDialectRuntimeData data = (MVELDialectRuntimeData) context.getPkg().getDialectRuntimeRegistry().getDialectData("mvel");
        data.addCompileable(context.getRule(), expr);
        expr.compile(data, context.getRule());
    } catch (final Exception e) {
        copyErrorLocation(e, context.getRuleDescr());
        context.addError(new DescrBuildError(context.getParentDescr(), context.getRuleDescr(), null, "Unable to build expression for 'salience' : " + e.getMessage() + "'" + context.getRuleDescr().getSalience() + "'"));
    } finally {
        context.setTypesafe(typesafe);
    }
}
Also used : SafeSalience(org.drools.core.definitions.rule.impl.RuleImpl.SafeSalience) MVELCompilationUnit(org.drools.core.base.mvel.MVELCompilationUnit) BoundIdentifiers(org.drools.compiler.compiler.BoundIdentifiers) MVELDialectRuntimeData(org.drools.core.rule.MVELDialectRuntimeData) DescrBuildError(org.drools.compiler.compiler.DescrBuildError) MVELSalienceExpression(org.drools.core.base.mvel.MVELSalienceExpression) Declaration(org.drools.core.rule.Declaration)

Example 9 with MVELCompilationUnit

use of org.drools.core.base.mvel.MVELCompilationUnit in project jbpm by kiegroup.

the class MVELActionBuilder method buildAction.

protected void buildAction(final PackageBuildContext context, final DroolsAction action, final ActionDescr actionDescr, final ContextResolver contextResolver, final MVELDialect dialect, final MVELAnalysisResult analysis, final String text, Map<String, Class<?>> variables) throws Exception {
    Set<String> variableNames = analysis.getNotBoundedIdentifiers();
    if (contextResolver != null) {
        for (String variableName : variableNames) {
            if (analysis.getMvelVariables().keySet().contains(variableName) || variableName.equals("kcontext") || variableName.equals("context")) {
                continue;
            }
            VariableScope variableScope = (VariableScope) contextResolver.resolveContext(VariableScope.VARIABLE_SCOPE, variableName);
            if (variableScope == null) {
                context.getErrors().add(new DescrBuildError(context.getParentDescr(), actionDescr, null, "Could not find variable '" + variableName + "' " + "for action '" + actionDescr.getText() + "'"));
            } else {
                variables.put(variableName, context.getDialect().getTypeResolver().resolveType(variableScope.findVariable(variableName).getType().getStringType()));
            }
        }
    }
    MVELCompilationUnit unit = dialect.getMVELCompilationUnit(text, analysis, null, null, variables, context, "context", org.kie.api.runtime.process.ProcessContext.class, false, MVELCompilationUnit.Scope.EXPRESSION);
    MVELAction expr = new MVELAction(unit, context.getDialect().getId());
    action.setMetaData("Action", expr);
    MVELDialectRuntimeData data = (MVELDialectRuntimeData) context.getPkg().getDialectRuntimeRegistry().getDialectData(dialect.getId());
    data.addCompileable(action, expr);
    expr.compile(data);
    collectTypes("MVELDialect", analysis, (ProcessBuildContext) context);
}
Also used : MVELDialectRuntimeData(org.drools.core.rule.MVELDialectRuntimeData) DescrBuildError(org.drools.compiler.compiler.DescrBuildError) MVELAction(org.jbpm.process.instance.impl.MVELAction) MVELCompilationUnit(org.drools.core.base.mvel.MVELCompilationUnit) VariableScope(org.jbpm.process.core.context.variable.VariableScope)

Example 10 with MVELCompilationUnit

use of org.drools.core.base.mvel.MVELCompilationUnit in project jbpm by kiegroup.

the class MVELReturnValueEvaluatorBuilder method buildReturnValueEvaluator.

public void buildReturnValueEvaluator(final PackageBuildContext context, final ReturnValueConstraintEvaluator constraintNode, final ReturnValueDescr descr, final ContextResolver contextResolver, final MVELDialect dialect, final MVELAnalysisResult analysis, final String text, Map<String, Class<?>> variables) throws Exception {
    Set<String> variableNames = analysis.getNotBoundedIdentifiers();
    if (contextResolver != null) {
        for (String variableName : variableNames) {
            if (analysis.getMvelVariables().keySet().contains(variableName) || variableName.equals("kcontext") || variableName.equals("context")) {
                continue;
            }
            VariableScope variableScope = (VariableScope) contextResolver.resolveContext(VariableScope.VARIABLE_SCOPE, variableName);
            if (variableScope == null) {
                context.getErrors().add(new DescrBuildError(context.getParentDescr(), descr, null, "Could not find variable '" + variableName + "' for action '" + descr.getText() + "'"));
            } else {
                variables.put(variableName, context.getDialect().getTypeResolver().resolveType(variableScope.findVariable(variableName).getType().getStringType()));
            }
        }
    }
    MVELCompilationUnit unit = dialect.getMVELCompilationUnit(text, analysis, null, null, variables, context, "context", org.kie.api.runtime.process.ProcessContext.class, false, MVELCompilationUnit.Scope.EXPRESSION);
    // MVELReturnValueExpression expr = new MVELReturnValueExpression( unit, context.getDialect().getId() );
    MVELReturnValueEvaluator expr = new MVELReturnValueEvaluator(unit, dialect.getId());
    // expr.setVariableNames(variableNames);
    constraintNode.setEvaluator(expr);
    MVELDialectRuntimeData data = (MVELDialectRuntimeData) context.getPkg().getDialectRuntimeRegistry().getDialectData(dialect.getId());
    data.addCompileable(constraintNode, expr);
    expr.compile(data);
    collectTypes("MVELReturnValue", analysis, (ProcessBuildContext) context);
}
Also used : MVELDialectRuntimeData(org.drools.core.rule.MVELDialectRuntimeData) DescrBuildError(org.drools.compiler.compiler.DescrBuildError) MVELReturnValueEvaluator(org.jbpm.process.instance.impl.MVELReturnValueEvaluator) MVELCompilationUnit(org.drools.core.base.mvel.MVELCompilationUnit) VariableScope(org.jbpm.process.core.context.variable.VariableScope)

Aggregations

MVELCompilationUnit (org.drools.core.base.mvel.MVELCompilationUnit)17 DescrBuildError (org.drools.compiler.compiler.DescrBuildError)12 Declaration (org.drools.core.rule.Declaration)10 MVELDialectRuntimeData (org.drools.core.rule.MVELDialectRuntimeData)10 BoundIdentifiers (org.drools.compiler.compiler.BoundIdentifiers)6 AnalysisResult (org.drools.compiler.compiler.AnalysisResult)5 EvaluatorWrapper (org.drools.core.base.EvaluatorWrapper)5 MvelConstraint (org.drools.core.rule.constraint.MvelConstraint)4 KnowledgeHelper (org.drools.core.spi.KnowledgeHelper)4 EvaluatorConstraint (org.drools.core.rule.constraint.EvaluatorConstraint)3 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 LinkedHashMap (java.util.LinkedHashMap)2 ClassObjectType (org.drools.core.base.ClassObjectType)2 MVELAccumulator (org.drools.core.base.mvel.MVELAccumulator)2 Pattern (org.drools.core.rule.Pattern)2 Accumulator (org.drools.core.spi.Accumulator)2 Constraint (org.drools.core.spi.Constraint)2 Evaluator (org.drools.core.spi.Evaluator)2 IndexUtil (org.drools.core.util.index.IndexUtil)2