Search in sources :

Example 66 with BaseDescr

use of org.drools.compiler.lang.descr.BaseDescr in project drools by kiegroup.

the class PatternAccumulateConstraint method buildPattern.

@Override
public void buildPattern() {
    Map<String, List<BaseDescr>> constraintsByVar = new HashMap<>();
    for (BaseDescr constraint : constraintDescrs) {
        Set<String> exprIds = DrlxParseUtil.parseExpression(constraint.getText()).getExpr().findAll(NameExpr.class).stream().map(NameExpr::toString).collect(toSet());
        for (AccumulateDescr.AccumulateFunctionCallDescr accFunc : source.getFunctions()) {
            if (exprIds.contains(accFunc.getBind())) {
                constraintsByVar.computeIfAbsent(accFunc.getBind(), s -> new ArrayList<>()).add(constraint);
                break;
            }
        }
    }
    constraintsByVar.forEach((id, constraints) -> {
        pattern.setIdentifier(id);
        new PatternDSLPattern(context, packageModel, pattern, constraints, null, false).buildPattern();
    });
    pattern.setIdentifier(null);
}
Also used : PackageModel(org.drools.modelcompiler.builder.PackageModel) AccumulateDescr(org.drools.compiler.lang.descr.AccumulateDescr) DrlxParseUtil(org.drools.modelcompiler.builder.generator.DrlxParseUtil) Set(java.util.Set) HashMap(java.util.HashMap) BaseDescr(org.drools.compiler.lang.descr.BaseDescr) NameExpr(org.drools.javaparser.ast.expr.NameExpr) ArrayList(java.util.ArrayList) PatternDescr(org.drools.compiler.lang.descr.PatternDescr) RuleContext(org.drools.modelcompiler.builder.generator.RuleContext) List(java.util.List) DSLNode(org.drools.modelcompiler.builder.generator.visitor.DSLNode) Map(java.util.Map) Collectors.toSet(java.util.stream.Collectors.toSet) HashMap(java.util.HashMap) NameExpr(org.drools.javaparser.ast.expr.NameExpr) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) BaseDescr(org.drools.compiler.lang.descr.BaseDescr) AccumulateDescr(org.drools.compiler.lang.descr.AccumulateDescr)

Example 67 with BaseDescr

use of org.drools.compiler.lang.descr.BaseDescr in project drools by kiegroup.

the class TypeDeclarationConfigurator method wireDurationAccessor.

private static void wireDurationAccessor(KnowledgeBuilderImpl kbuilder, Annotated annotated, TypeDeclaration type, PackageRegistry pkgRegistry) {
    Duration duration = annotated.getTypedAnnotation(Duration.class);
    if (duration != null) {
        BaseDescr typeDescr = annotated instanceof BaseDescr ? ((BaseDescr) annotated) : new BaseDescr();
        String durationField;
        try {
            durationField = duration.value();
        } catch (Exception e) {
            kbuilder.addBuilderResult(new TypeDeclarationError(typeDescr, e.getMessage()));
            return;
        }
        type.setDurationAttribute(durationField);
        InternalKnowledgePackage pkg = pkgRegistry.getPackage();
        MVELAnalysisResult results = getMvelAnalysisResult(kbuilder, typeDescr, type, pkgRegistry, durationField, pkg);
        if (results != null) {
            type.setDurationExtractor(getFieldExtractor(type, durationField, pkg, results));
        } else {
            kbuilder.addBuilderResult(new TypeDeclarationError(typeDescr, "Error processing @duration for TypeDeclaration '" + type.getFullName() + "': cannot access the field '" + durationField + "'"));
        }
    }
}
Also used : TypeDeclarationError(org.drools.compiler.compiler.TypeDeclarationError) MVELAnalysisResult(org.drools.compiler.rule.builder.dialect.mvel.MVELAnalysisResult) Duration(org.kie.api.definition.type.Duration) BaseDescr(org.drools.compiler.lang.descr.BaseDescr) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) InternalKnowledgePackage(org.drools.core.definitions.InternalKnowledgePackage)

Example 68 with BaseDescr

use of org.drools.compiler.lang.descr.BaseDescr in project drools by kiegroup.

the class MVELExprAnalyzer method analyzeExpression.

// ------------------------------------------------------------
// Instance methods
// ------------------------------------------------------------
/**
 * Analyze an expression.
 *
 * @param expr
 *            The expression to analyze.
 * @param availableIdentifiers
 *            Total set of declarations available.
 *
 * @return The <code>Set</code> of declarations used by the expression.
 * @throws RecognitionException
 *             If an error occurs in the parser.
 */
@SuppressWarnings("unchecked")
public static MVELAnalysisResult analyzeExpression(final PackageBuildContext context, final String expr, final BoundIdentifiers availableIdentifiers, final Map<String, Class<?>> localTypes, String contextIdentifier, Class kcontextClass) {
    if (expr.trim().length() <= 0) {
        MVELAnalysisResult result = analyze((Set<String>) Collections.EMPTY_SET, availableIdentifiers);
        result.setMvelVariables(new HashMap<String, Class<?>>());
        result.setTypesafe(true);
        return result;
    }
    MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = true;
    MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING = true;
    MVEL.COMPILER_OPT_ALLOW_RESOLVE_INNERCLASSES_WITH_DOTNOTATION = true;
    MVEL.COMPILER_OPT_SUPPORT_JAVA_STYLE_CLASS_LITERALS = true;
    MVELDialect dialect = (MVELDialect) context.getDialect("mvel");
    ParserConfiguration conf = context.getMVELDialectRuntimeData().getParserConfiguration();
    conf.setClassLoader(context.getKnowledgeBuilder().getRootClassLoader());
    // first compilation is for verification only
    // @todo proper source file name
    final ParserContext parserContext1 = new ParserContext(conf);
    if (localTypes != null) {
        for (Entry entry : localTypes.entrySet()) {
            parserContext1.addInput((String) entry.getKey(), (Class) entry.getValue());
        }
    }
    if (availableIdentifiers.getThisClass() != null) {
        parserContext1.addInput("this", availableIdentifiers.getThisClass());
    }
    if (availableIdentifiers.getOperators() != null) {
        for (Entry<String, EvaluatorWrapper> opEntry : availableIdentifiers.getOperators().entrySet()) {
            parserContext1.addInput(opEntry.getKey(), opEntry.getValue().getClass());
        }
    }
    parserContext1.setStrictTypeEnforcement(false);
    parserContext1.setStrongTyping(false);
    parserContext1.setInterceptors(dialect.getInterceptors());
    Class<?> returnType;
    try {
        returnType = MVEL.analyze(expr, parserContext1);
    } catch (Exception e) {
        BaseDescr base = (context instanceof RuleBuildContext) ? ((RuleBuildContext) context).getRuleDescr() : context.getParentDescr();
        if (e instanceof CompileException && e.getCause() != null && e.getMessage().startsWith("[Error: null]")) {
            // rewrite error message in cause original message is null
            e = new CompileException(e.getCause().toString(), ((CompileException) e).getExpr(), ((CompileException) e).getCursor(), e.getCause());
        }
        DialectUtil.copyErrorLocation(e, context.getParentDescr());
        context.addError(new DescrBuildError(base, context.getParentDescr(), null, "Unable to Analyse Expression " + expr + ":\n" + e.getMessage()));
        return null;
    }
    Set<String> requiredInputs = new HashSet<String>();
    requiredInputs.addAll(parserContext1.getInputs().keySet());
    HashMap<String, Class<?>> variables = (HashMap<String, Class<?>>) ((Map) parserContext1.getVariables());
    if (localTypes != null) {
        for (String str : localTypes.keySet()) {
            // we have to do this due to mvel regressions on detecting true local vars
            variables.remove(str);
        }
    }
    // MVEL includes direct fields of context object in non-strict mode. so we need to strip those
    if (availableIdentifiers.getThisClass() != null) {
        requiredInputs.removeIf(s -> PropertyTools.getFieldOrAccessor(availableIdentifiers.getThisClass(), s) != null);
    }
    // now, set the required input types and compile again
    final ParserContext parserContext2 = new ParserContext(conf);
    parserContext2.setStrictTypeEnforcement(true);
    parserContext2.setStrongTyping(true);
    parserContext2.setInterceptors(dialect.getInterceptors());
    for (String input : requiredInputs) {
        if ("this".equals(input)) {
            continue;
        }
        Class<?> cls = availableIdentifiers.resolveType(input);
        if (cls == null) {
            if (input.equals(contextIdentifier) || input.equals("kcontext")) {
                cls = kcontextClass;
            } else if (input.equals("rule")) {
                cls = Rule.class;
            } else if (localTypes != null) {
                cls = localTypes.get(input);
            }
        }
        if (cls != null) {
            parserContext2.addInput(input, cls);
        }
    }
    if (availableIdentifiers.getThisClass() != null) {
        parserContext2.addInput("this", availableIdentifiers.getThisClass());
    }
    boolean typesafe = context.isTypesafe();
    try {
        returnType = MVEL.analyze(expr, parserContext2);
        typesafe = true;
    } catch (Exception e) {
        // is this an error, or can we fall back to non-typesafe mode?
        if (typesafe) {
            BaseDescr base = (context instanceof RuleBuildContext) ? ((RuleBuildContext) context).getRuleDescr() : context.getParentDescr();
            DialectUtil.copyErrorLocation(e, context.getParentDescr());
            context.addError(new DescrBuildError(base, context.getParentDescr(), null, "Unable to Analyse Expression " + expr + ":\n" + e.getMessage()));
            return null;
        }
    }
    if (typesafe) {
        requiredInputs = new HashSet<String>();
        requiredInputs.addAll(parserContext2.getInputs().keySet());
        requiredInputs.addAll(variables.keySet());
        variables = (HashMap<String, Class<?>>) ((Map) parserContext2.getVariables());
        if (localTypes != null) {
            for (String str : localTypes.keySet()) {
                // we have to do this due to mvel regressions on detecting true local vars
                variables.remove(str);
            }
        }
    }
    MVELAnalysisResult result = analyze(requiredInputs, availableIdentifiers);
    result.setReturnType(returnType);
    result.setMvelVariables(variables);
    result.setTypesafe(typesafe);
    return result;
}
Also used : EvaluatorWrapper(org.drools.core.base.EvaluatorWrapper) RuleBuildContext(org.drools.compiler.rule.builder.RuleBuildContext) HashMap(java.util.HashMap) CompileException(org.mvel2.CompileException) RecognitionException(org.antlr.runtime.RecognitionException) ParserConfiguration(org.mvel2.ParserConfiguration) Entry(java.util.Map.Entry) DescrBuildError(org.drools.compiler.compiler.DescrBuildError) CompileException(org.mvel2.CompileException) BaseDescr(org.drools.compiler.lang.descr.BaseDescr) Rule(org.kie.api.definition.rule.Rule) ParserContext(org.mvel2.ParserContext) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet)

Example 69 with BaseDescr

use of org.drools.compiler.lang.descr.BaseDescr in project drools by kiegroup.

the class DRL6Expressions method exclusiveOrExpression.

// $ANTLR end "inclusiveOrExpression"
// $ANTLR start "exclusiveOrExpression"
// src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:273:1: exclusiveOrExpression returns [BaseDescr result] : left= andExpression ( XOR right= andExpression )* ;
public final BaseDescr exclusiveOrExpression() throws RecognitionException {
    BaseDescr result = null;
    BaseDescr left = null;
    BaseDescr right = null;
    try {
        // src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:274:3: (left= andExpression ( XOR right= andExpression )* )
        // src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:274:5: left= andExpression ( XOR right= andExpression )*
        {
            pushFollow(FOLLOW_andExpression_in_exclusiveOrExpression1383);
            left = andExpression();
            state._fsp--;
            if (state.failed)
                return result;
            if (state.backtracking == 0) {
                if (buildDescr) {
                    result = left;
                }
            }
            // src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:275:3: ( XOR right= andExpression )*
            loop29: while (true) {
                int alt29 = 2;
                int LA29_0 = input.LA(1);
                if ((LA29_0 == XOR)) {
                    alt29 = 1;
                }
                switch(alt29) {
                    case 1:
                        // src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:275:5: XOR right= andExpression
                        {
                            match(input, XOR, FOLLOW_XOR_in_exclusiveOrExpression1391);
                            if (state.failed)
                                return result;
                            pushFollow(FOLLOW_andExpression_in_exclusiveOrExpression1395);
                            right = andExpression();
                            state._fsp--;
                            if (state.failed)
                                return result;
                            if (state.backtracking == 0) {
                                if (buildDescr) {
                                    ConstraintConnectiveDescr descr = ConstraintConnectiveDescr.newXor();
                                    descr.addOrMerge(result);
                                    descr.addOrMerge(right);
                                    result = descr;
                                }
                            }
                        }
                        break;
                    default:
                        break loop29;
                }
            }
        }
    } catch (RecognitionException re) {
        throw re;
    } finally {
    // do for sure before leaving
    }
    return result;
}
Also used : BaseDescr(org.drools.compiler.lang.descr.BaseDescr) AnnotatedBaseDescr(org.drools.compiler.lang.descr.AnnotatedBaseDescr) ConstraintConnectiveDescr(org.drools.compiler.lang.descr.ConstraintConnectiveDescr)

Example 70 with BaseDescr

use of org.drools.compiler.lang.descr.BaseDescr in project drools by kiegroup.

the class DRL6Expressions method relationalExpression.

// $ANTLR start "relationalExpression"
// src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:368:1: relationalExpression returns [BaseDescr result] : left= shiftExpression ( ( operator | LEFT_PAREN )=>right= orRestriction )* ;
public final BaseDescr relationalExpression() throws RecognitionException {
    relationalExpression_stack.push(new relationalExpression_scope());
    BaseDescr result = null;
    ParserRuleReturnScope left = null;
    BaseDescr right = null;
    relationalExpression_stack.peek().lsd = null;
    try {
        // src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:371:3: (left= shiftExpression ( ( operator | LEFT_PAREN )=>right= orRestriction )* )
        // src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:371:5: left= shiftExpression ( ( operator | LEFT_PAREN )=>right= orRestriction )*
        {
            pushFollow(FOLLOW_shiftExpression_in_relationalExpression1832);
            left = shiftExpression();
            state._fsp--;
            if (state.failed)
                return result;
            if (state.backtracking == 0) {
                if (buildDescr) {
                    if ((left != null ? ((DRL6Expressions.shiftExpression_return) left).result : null) == null) {
                        result = new AtomicExprDescr((left != null ? input.toString(left.start, left.stop) : null));
                    } else if ((left != null ? ((DRL6Expressions.shiftExpression_return) left).result : null) instanceof AtomicExprDescr) {
                        if ((left != null ? input.toString(left.start, left.stop) : null).equals(((AtomicExprDescr) (left != null ? ((DRL6Expressions.shiftExpression_return) left).result : null)).getExpression())) {
                            result = (left != null ? ((DRL6Expressions.shiftExpression_return) left).result : null);
                        } else {
                            result = new AtomicExprDescr((left != null ? input.toString(left.start, left.stop) : null));
                        }
                    } else if ((left != null ? ((DRL6Expressions.shiftExpression_return) left).result : null) instanceof BindingDescr) {
                        if ((left != null ? input.toString(left.start, left.stop) : null).equals(((BindingDescr) (left != null ? ((DRL6Expressions.shiftExpression_return) left).result : null)).getExpression())) {
                            result = (left != null ? ((DRL6Expressions.shiftExpression_return) left).result : null);
                        } else {
                            BindingDescr bind = (BindingDescr) (left != null ? ((DRL6Expressions.shiftExpression_return) left).result : null);
                            int offset = bind.isUnification() ? 2 : 1;
                            String fullExpression = (left != null ? input.toString(left.start, left.stop) : null).substring((left != null ? input.toString(left.start, left.stop) : null).indexOf(":") + offset).trim();
                            result = new BindingDescr(bind.getVariable(), bind.getExpression(), fullExpression, bind.isUnification());
                        }
                    } else {
                        result = (left != null ? ((DRL6Expressions.shiftExpression_return) left).result : null);
                    }
                    relationalExpression_stack.peek().lsd = result;
                }
            }
            // src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:396:3: ( ( operator | LEFT_PAREN )=>right= orRestriction )*
            loop37: while (true) {
                int alt37 = 2;
                int LA37_0 = input.LA(1);
                if ((LA37_0 == ID)) {
                    int LA37_2 = input.LA(2);
                    if ((((((helper.validateIdentifierKey(DroolsSoftKeywords.NOT))) || ((helper.isPluggableEvaluator(false)))) && synpred9_DRL6Expressions()))) {
                        alt37 = 1;
                    }
                } else if ((LA37_0 == EQUALS)) {
                    int LA37_3 = input.LA(2);
                    if ((synpred9_DRL6Expressions())) {
                        alt37 = 1;
                    }
                } else if ((LA37_0 == NOT_EQUALS)) {
                    int LA37_4 = input.LA(2);
                    if ((synpred9_DRL6Expressions())) {
                        alt37 = 1;
                    }
                } else if ((LA37_0 == LESS)) {
                    int LA37_20 = input.LA(2);
                    if ((synpred9_DRL6Expressions())) {
                        alt37 = 1;
                    }
                } else if ((LA37_0 == GREATER)) {
                    int LA37_21 = input.LA(2);
                    if ((synpred9_DRL6Expressions())) {
                        alt37 = 1;
                    }
                } else if ((LA37_0 == TILDE) && (synpred9_DRL6Expressions())) {
                    alt37 = 1;
                } else if ((LA37_0 == LESS_EQUALS) && (synpred9_DRL6Expressions())) {
                    alt37 = 1;
                } else if ((LA37_0 == GREATER_EQUALS) && (synpred9_DRL6Expressions())) {
                    alt37 = 1;
                } else if ((LA37_0 == LEFT_PAREN) && (synpred9_DRL6Expressions())) {
                    alt37 = 1;
                }
                switch(alt37) {
                    case 1:
                        // src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:396:5: ( operator | LEFT_PAREN )=>right= orRestriction
                        {
                            pushFollow(FOLLOW_orRestriction_in_relationalExpression1857);
                            right = orRestriction();
                            state._fsp--;
                            if (state.failed)
                                return result;
                            if (state.backtracking == 0) {
                                if (buildDescr) {
                                    result = right;
                                    relationalExpression_stack.peek().lsd = result;
                                }
                            }
                        }
                        break;
                    default:
                        break loop37;
                }
            }
        }
    } catch (RecognitionException re) {
        throw re;
    } finally {
        // do for sure before leaving
        relationalExpression_stack.pop();
    }
    return result;
}
Also used : BindingDescr(org.drools.compiler.lang.descr.BindingDescr) BaseDescr(org.drools.compiler.lang.descr.BaseDescr) AnnotatedBaseDescr(org.drools.compiler.lang.descr.AnnotatedBaseDescr) AtomicExprDescr(org.drools.compiler.lang.descr.AtomicExprDescr)

Aggregations

BaseDescr (org.drools.compiler.lang.descr.BaseDescr)109 AnnotatedBaseDescr (org.drools.compiler.lang.descr.AnnotatedBaseDescr)60 ConstraintConnectiveDescr (org.drools.compiler.lang.descr.ConstraintConnectiveDescr)23 AtomicExprDescr (org.drools.compiler.lang.descr.AtomicExprDescr)17 ConditionalElementDescr (org.drools.compiler.lang.descr.ConditionalElementDescr)16 BindingDescr (org.drools.compiler.lang.descr.BindingDescr)12 AndDescr (org.drools.compiler.lang.descr.AndDescr)11 RelationalExprDescr (org.drools.compiler.lang.descr.RelationalExprDescr)11 DeclareDescrBuilder (org.drools.compiler.lang.api.DeclareDescrBuilder)9 PatternDescr (org.drools.compiler.lang.descr.PatternDescr)8 OrDescr (org.drools.compiler.lang.descr.OrDescr)7 ArrayList (java.util.ArrayList)6 AccumulateDescrBuilder (org.drools.compiler.lang.api.AccumulateDescrBuilder)6 AnnotatedDescrBuilder (org.drools.compiler.lang.api.AnnotatedDescrBuilder)6 AnnotationDescrBuilder (org.drools.compiler.lang.api.AnnotationDescrBuilder)6 AttributeDescrBuilder (org.drools.compiler.lang.api.AttributeDescrBuilder)6 BehaviorDescrBuilder (org.drools.compiler.lang.api.BehaviorDescrBuilder)6 CEDescrBuilder (org.drools.compiler.lang.api.CEDescrBuilder)6 CollectDescrBuilder (org.drools.compiler.lang.api.CollectDescrBuilder)6 ConditionalBranchDescrBuilder (org.drools.compiler.lang.api.ConditionalBranchDescrBuilder)6