Search in sources :

Example 1 with EvaluatorWrapper

use of org.drools.core.base.EvaluatorWrapper in project drools by kiegroup.

the class MVELConstraintBuilder method buildLiteralConstraint.

public Constraint buildLiteralConstraint(RuleBuildContext context, Pattern pattern, ValueType vtype, FieldValue field, String expression, String leftValue, String operator, String rightValue, InternalReadAccessor extractor, LiteralRestrictionDescr restrictionDescr, Map<String, OperatorDescr> aliases) {
    if (!isMvelOperator(operator)) {
        Evaluator evaluator = buildLiteralEvaluator(context, extractor, restrictionDescr, vtype);
        if (evaluator != null && evaluator.isTemporal()) {
            try {
                field = context.getCompilerFactory().getFieldFactory().getFieldValue(field.getValue(), ValueType.DATE_TYPE);
            } catch (Exception e) {
                context.addError(new DescrBuildError(context.getParentDescr(), restrictionDescr, null, e.getMessage()));
            }
        }
        return new EvaluatorConstraint(field, evaluator, extractor);
    }
    String mvelExpr = normalizeMVELLiteralExpression(vtype, field, expression, leftValue, operator, rightValue, restrictionDescr);
    IndexUtil.ConstraintType constraintType = IndexUtil.ConstraintType.decode(operator);
    MVELCompilationUnit compilationUnit = buildCompilationUnit(context, pattern, mvelExpr, aliases);
    EvaluatorWrapper[] operators = getOperators(buildOperators(context, pattern, restrictionDescr, aliases));
    return new MvelConstraint(context.getPkg().getName(), mvelExpr, compilationUnit, constraintType, field, extractor, operators);
}
Also used : DescrBuildError(org.drools.compiler.compiler.DescrBuildError) EvaluatorWrapper(org.drools.core.base.EvaluatorWrapper) EvaluatorConstraint(org.drools.core.rule.constraint.EvaluatorConstraint) IndexUtil(org.drools.core.util.index.IndexUtil) MVELCompilationUnit(org.drools.core.base.mvel.MVELCompilationUnit) MvelConstraint(org.drools.core.rule.constraint.MvelConstraint) Evaluator(org.drools.core.spi.Evaluator)

Example 2 with EvaluatorWrapper

use of org.drools.core.base.EvaluatorWrapper in project drools by kiegroup.

the class MVELConstraintBuilder method buildVariableConstraint.

public Constraint buildVariableConstraint(RuleBuildContext context, Pattern pattern, String expression, Declaration[] declarations, String leftValue, OperatorDescr operatorDescr, String rightValue, InternalReadAccessor extractor, Declaration requiredDeclaration, RelationalExprDescr relDescr, Map<String, OperatorDescr> aliases) {
    if (!isMvelOperator(operatorDescr.getOperator())) {
        if (requiredDeclaration == null) {
            return null;
        }
        EvaluatorDefinition.Target right = getRightTarget(extractor);
        EvaluatorDefinition.Target left = (requiredDeclaration.isPatternDeclaration() && !(Date.class.isAssignableFrom(requiredDeclaration.getDeclarationClass()) || Number.class.isAssignableFrom(requiredDeclaration.getDeclarationClass()))) ? EvaluatorDefinition.Target.HANDLE : EvaluatorDefinition.Target.FACT;
        final Evaluator evaluator = getEvaluator(context, relDescr, extractor.getValueType(), operatorDescr.getOperator(), relDescr.isNegated(), relDescr.getParametersText(), left, right);
        return new EvaluatorConstraint(new Declaration[] { requiredDeclaration }, evaluator, extractor);
    }
    boolean isUnification = requiredDeclaration != null && requiredDeclaration.getPattern().getObjectType().equals(new ClassObjectType(DroolsQuery.class)) && Operator.EQUAL.getOperatorString().equals(operatorDescr.getOperator());
    if (isUnification && leftValue.equals(rightValue)) {
        expression = resolveUnificationAmbiguity(expression, declarations, leftValue, rightValue);
    }
    expression = normalizeMVELVariableExpression(expression, leftValue, rightValue, relDescr);
    IndexUtil.ConstraintType constraintType = IndexUtil.ConstraintType.decode(operatorDescr.getOperator());
    MVELCompilationUnit compilationUnit = isUnification ? null : buildCompilationUnit(context, pattern, expression, aliases);
    EvaluatorWrapper[] operators = getOperators(buildOperators(context, pattern, relDescr, aliases));
    return new MvelConstraint(Collections.singletonList(context.getPkg().getName()), expression, declarations, operators, compilationUnit, constraintType, requiredDeclaration, extractor, isUnification);
}
Also used : EvaluatorWrapper(org.drools.core.base.EvaluatorWrapper) ClassObjectType(org.drools.core.base.ClassObjectType) IndexUtil(org.drools.core.util.index.IndexUtil) MVELCompilationUnit(org.drools.core.base.mvel.MVELCompilationUnit) MvelConstraint(org.drools.core.rule.constraint.MvelConstraint) Evaluator(org.drools.core.spi.Evaluator) EvaluatorConstraint(org.drools.core.rule.constraint.EvaluatorConstraint) EvaluatorDefinition(org.drools.core.base.evaluators.EvaluatorDefinition) DroolsQuery(org.drools.core.base.DroolsQuery)

Example 3 with EvaluatorWrapper

use of org.drools.core.base.EvaluatorWrapper in project drools by kiegroup.

the class PatternBuilder method combineConstraints.

private void combineConstraints(RuleBuildContext context, Pattern pattern, MVELDumper.MVELDumperContext mvelCtx) {
    List<MvelConstraint> combinableConstraints = pattern.getCombinableConstraints();
    if (combinableConstraints == null || combinableConstraints.size() < 2) {
        return;
    }
    List<Declaration> declarations = new ArrayList<Declaration>();
    List<EvaluatorWrapper> operators = new ArrayList<EvaluatorWrapper>();
    Set<String> declarationNames = new HashSet<String>();
    boolean isFirst = true;
    Collection<String> packageNames = null;
    StringBuilder expressionBuilder = new StringBuilder(combinableConstraints.size() * 25);
    for (MvelConstraint constraint : combinableConstraints) {
        pattern.removeConstraint(constraint);
        if (isFirst) {
            packageNames = constraint.getPackageNames();
            isFirst = false;
        } else {
            expressionBuilder.append(" && ");
        }
        String constraintExpression = constraint.getExpression();
        boolean isComplex = constraintExpression.contains("&&") || constraintExpression.contains("||");
        if (isComplex) {
            expressionBuilder.append("( ");
        }
        expressionBuilder.append(constraintExpression);
        if (isComplex) {
            expressionBuilder.append(" )");
        }
        for (Declaration declaration : constraint.getRequiredDeclarations()) {
            if (declarationNames.add(declaration.getBindingName())) {
                declarations.add(declaration);
            }
        }
        Collections.addAll(operators, constraint.getOperators());
    }
    String expression = expressionBuilder.toString();
    MVELCompilationUnit compilationUnit = getConstraintBuilder(context).buildCompilationUnit(context, pattern, expression, mvelCtx.getAliases());
    Constraint combinedConstraint = getConstraintBuilder(context).buildMvelConstraint(packageNames, expression, declarations.toArray(new Declaration[declarations.size()]), operators.toArray(new EvaluatorWrapper[operators.size()]), compilationUnit, IndexUtil.ConstraintType.UNKNOWN, null, null, false);
    pattern.addConstraint(combinedConstraint);
}
Also used : EvaluatorWrapper(org.drools.core.base.EvaluatorWrapper) XpathConstraint(org.drools.core.rule.constraint.XpathConstraint) NegConstraint(org.drools.core.rule.constraint.NegConstraint) Constraint(org.drools.core.spi.Constraint) MvelConstraint(org.drools.core.rule.constraint.MvelConstraint) EvaluatorConstraint(org.drools.core.rule.constraint.EvaluatorConstraint) PredicateConstraint(org.drools.core.rule.PredicateConstraint) MvelConstraint(org.drools.core.rule.constraint.MvelConstraint) ArrayList(java.util.ArrayList) MVELCompilationUnit(org.drools.core.base.mvel.MVELCompilationUnit) Declaration(org.drools.core.rule.Declaration) TypeDeclaration(org.drools.core.rule.TypeDeclaration) HashSet(java.util.HashSet)

Example 4 with EvaluatorWrapper

use of org.drools.core.base.EvaluatorWrapper in project drools by kiegroup.

the class JavaExprAnalyzer method analyze.

/**
 * Analyze an expression.
 *
 * @param availableIdentifiers
 *            Total set of declarations available.
 * @param result
 *            The AST for the expression.
 *
 * @return The <code>Set</code> of declarations used by the expression.
 *
 * @throws RecognitionException
 *             If an error occurs in the parser.
 */
private JavaAnalysisResult analyze(JavaAnalysisResult result, BoundIdentifiers availableIdentifiers) throws RecognitionException {
    final Set<String> identifiers = result.getIdentifiers();
    final Set<String> notBound = new HashSet<String>(identifiers);
    Map<String, Class<?>> usedDecls = new HashMap<String, Class<?>>();
    Map<String, Class<?>> usedGlobals = new HashMap<String, Class<?>>();
    Map<String, EvaluatorWrapper> usedOperators = new HashMap<String, EvaluatorWrapper>();
    for (Entry<String, Class<?>> entry : availableIdentifiers.getDeclrClasses().entrySet()) {
        if (identifiers.contains(entry.getKey())) {
            usedDecls.put(entry.getKey(), entry.getValue());
            notBound.remove(entry.getKey());
        }
    }
    for (String identifier : identifiers) {
        Class<?> type = availableIdentifiers.resolveVarType(identifier);
        if (type != null) {
            usedGlobals.put(identifier, type);
            notBound.remove(identifier);
        }
    }
    for (Map.Entry<String, EvaluatorWrapper> op : availableIdentifiers.getOperators().entrySet()) {
        if (identifiers.contains(op.getKey())) {
            usedOperators.put(op.getKey(), op.getValue());
            notBound.remove(op.getKey());
        }
    }
    BoundIdentifiers boundIdentifiers = new BoundIdentifiers(usedDecls, availableIdentifiers.getContext(), usedOperators, availableIdentifiers.getThisClass());
    boundIdentifiers.setGlobals(usedGlobals);
    result.setBoundIdentifiers(boundIdentifiers);
    result.setNotBoundedIdentifiers(notBound);
    return result;
}
Also used : EvaluatorWrapper(org.drools.core.base.EvaluatorWrapper) HashMap(java.util.HashMap) BoundIdentifiers(org.drools.compiler.compiler.BoundIdentifiers) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet)

Example 5 with EvaluatorWrapper

use of org.drools.core.base.EvaluatorWrapper 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)

Aggregations

EvaluatorWrapper (org.drools.core.base.EvaluatorWrapper)11 MVELCompilationUnit (org.drools.core.base.mvel.MVELCompilationUnit)5 Declaration (org.drools.core.rule.Declaration)5 HashMap (java.util.HashMap)4 HashSet (java.util.HashSet)4 Map (java.util.Map)4 InternalFactHandle (org.drools.core.common.InternalFactHandle)4 EvaluatorConstraint (org.drools.core.rule.constraint.EvaluatorConstraint)3 MvelConstraint (org.drools.core.rule.constraint.MvelConstraint)3 ArrayList (java.util.ArrayList)2 LinkedHashMap (java.util.LinkedHashMap)2 Entry (java.util.Map.Entry)2 BoundIdentifiers (org.drools.compiler.compiler.BoundIdentifiers)2 DescrBuildError (org.drools.compiler.compiler.DescrBuildError)2 RuleBuildContext (org.drools.compiler.rule.builder.RuleBuildContext)2 InternalWorkingMemory (org.drools.core.common.InternalWorkingMemory)2 Evaluator (org.drools.core.spi.Evaluator)2 KnowledgeHelper (org.drools.core.spi.KnowledgeHelper)2 Tuple (org.drools.core.spi.Tuple)2 IndexUtil (org.drools.core.util.index.IndexUtil)2