Search in sources :

Example 11 with Declaration

use of org.drools.core.rule.Declaration in project drools by kiegroup.

the class JavaConsequenceBuilderTest method setupTest.

private void setupTest(String consequence, Map<String, Object> namedConsequences) {
    InternalKnowledgePackage pkg = new KnowledgePackageImpl("org.drools");
    pkg.addImport(new ImportDeclaration("org.drools.compiler.Cheese"));
    KnowledgeBuilderConfigurationImpl conf = new KnowledgeBuilderConfigurationImpl();
    // this test was originally intended with PropertyReactive.ALLOWED:
    conf.setOption(PropertySpecificOption.ALLOWED);
    KnowledgeBuilderImpl kBuilder = new KnowledgeBuilderImpl(pkg, conf);
    ruleDescr = new RuleDescr("test consequence builder");
    ruleDescr.setConsequence(consequence);
    for (Entry<String, Object> entry : namedConsequences.entrySet()) {
        ruleDescr.addNamedConsequences(entry.getKey(), entry.getValue());
    }
    RuleImpl rule = ruleDescr.toRule();
    PackageRegistry pkgRegistry = kBuilder.getPackageRegistry(pkg.getName());
    DialectCompiletimeRegistry reg = kBuilder.getPackageRegistry(pkg.getName()).getDialectCompiletimeRegistry();
    context = new RuleBuildContext(kBuilder, ruleDescr, reg, pkg, reg.getDialect(pkgRegistry.getDialect()));
    rule.addPattern(new Pattern(0, new ClassObjectType(Cheese.class), "$cheese"));
    Pattern p = new Pattern(1, new ClassObjectType(Person.class), "$persone");
    Declaration declr = p.addDeclaration("age");
    final InternalReadAccessor extractor = PatternBuilder.getFieldReadAccessor(context, new BindingDescr("age", "age"), p, "age", declr, true);
    rule.addPattern(p);
    context.getDeclarationResolver().pushOnBuildStack(rule.getLhs());
    context.getDialect().getConsequenceBuilder().build(context, RuleImpl.DEFAULT_CONSEQUENCE_NAME);
    for (String name : namedConsequences.keySet()) {
        context.getDialect().getConsequenceBuilder().build(context, name);
    }
    context.getDialect().addRule(context);
    pkgRegistry.getPackage().addRule(context.getRule());
    kBuilder.compileAll();
    kBuilder.reloadAll();
}
Also used : Pattern(org.drools.core.rule.Pattern) BindingDescr(org.drools.compiler.lang.descr.BindingDescr) RuleBuildContext(org.drools.compiler.rule.builder.RuleBuildContext) ClassObjectType(org.drools.core.base.ClassObjectType) KnowledgeBuilderConfigurationImpl(org.drools.compiler.builder.impl.KnowledgeBuilderConfigurationImpl) DialectCompiletimeRegistry(org.drools.compiler.compiler.DialectCompiletimeRegistry) RuleImpl(org.drools.core.definitions.rule.impl.RuleImpl) PackageRegistry(org.drools.compiler.compiler.PackageRegistry) KnowledgeBuilderImpl(org.drools.compiler.builder.impl.KnowledgeBuilderImpl) ImportDeclaration(org.drools.core.rule.ImportDeclaration) RuleDescr(org.drools.compiler.lang.descr.RuleDescr) InternalReadAccessor(org.drools.core.spi.InternalReadAccessor) Declaration(org.drools.core.rule.Declaration) ImportDeclaration(org.drools.core.rule.ImportDeclaration) KnowledgePackageImpl(org.drools.core.definitions.impl.KnowledgePackageImpl) Person(org.drools.compiler.Person) InternalKnowledgePackage(org.drools.core.definitions.InternalKnowledgePackage)

Example 12 with Declaration

use of org.drools.core.rule.Declaration in project drools by kiegroup.

the class QueryElementBuilder method analyzeExpression.

private AnalysisResult analyzeExpression(RuleBuildContext context, BaseDescr base, String expression) {
    Map<String, Declaration> decls = context.getDeclarationResolver().getDeclarations(context.getRule());
    Map<String, Class<?>> declarationClasses = DeclarationScopeResolver.getDeclarationClasses(decls);
    BoundIdentifiers boundIds = new BoundIdentifiers(declarationClasses, context);
    return context.getDialect().analyzeBlock(context, base, expression, boundIds);
}
Also used : Declaration(org.drools.core.rule.Declaration) BoundIdentifiers(org.drools.compiler.compiler.BoundIdentifiers)

Example 13 with Declaration

use of org.drools.core.rule.Declaration in project drools by kiegroup.

the class PatternBuilder method getFieldReadAccessor.

public static InternalReadAccessor getFieldReadAccessor(final RuleBuildContext context, final BaseDescr descr, final Pattern pattern, final ObjectType objectType, String fieldName, final AcceptsReadAccessor target, final boolean reportError) {
    // reportError is needed as some times failure to build accessor is not a failure, just an indication that building is not possible so try something else.
    InternalReadAccessor reader;
    if (ValueType.FACTTEMPLATE_TYPE.equals(objectType.getValueType())) {
        // @todo use accessor cache
        final FactTemplate factTemplate = ((FactTemplateObjectType) objectType).getFactTemplate();
        reader = new FactTemplateFieldExtractor(factTemplate, factTemplate.getFieldTemplateIndex(fieldName));
        if (target != null) {
            target.setReadAccessor(reader);
        }
        return reader;
    }
    boolean isGetter = getterRegexp.matcher(fieldName).matches();
    if (isGetter) {
        fieldName = fieldName.substring(3, fieldName.indexOf('(')).trim();
    }
    if (isGetter || identifierRegexp.matcher(fieldName).matches()) {
        Declaration decl = context.getDeclarationResolver().getDeclarations(context.getRule()).get(fieldName);
        if (decl != null && decl.getExtractor() instanceof ClassFieldReader && "this".equals(((ClassFieldReader) decl.getExtractor()).getFieldName())) {
            return decl.getExtractor();
        }
        try {
            reader = context.getPkg().getClassFieldAccessorStore().getReader(objectType.getClassName(), fieldName, target);
        } catch (final Exception e) {
            if (reportError && context.isTypesafe()) {
                DialectUtil.copyErrorLocation(e, descr);
                registerDescrBuildError(context, descr, e, "Unable to create Field Extractor for '" + fieldName + "'" + e.getMessage());
            }
            // if there was an error, set the reader back to null
            reader = null;
        } finally {
            if (reportError) {
                Collection<KnowledgeBuilderResult> results = context.getPkg().getClassFieldAccessorStore().getWiringResults(objectType.getClassType(), fieldName);
                if (!results.isEmpty()) {
                    for (KnowledgeBuilderResult res : results) {
                        if (res.getSeverity() == ResultSeverity.ERROR) {
                            context.addError(new DroolsErrorWrapper(res));
                        } else {
                            context.addWarning(new DroolsWarningWrapper(res));
                        }
                    }
                }
            }
        }
    } else {
        // we need MVEL extractor for expressions
        Dialect dialect = context.getDialect();
        try {
            MVELDialect mvelDialect = (MVELDialect) context.getDialect("mvel");
            context.setDialect(mvelDialect);
            final AnalysisResult analysis = context.getDialect().analyzeExpression(context, descr, fieldName, new BoundIdentifiers(pattern, context, Collections.EMPTY_MAP, objectType.getClassType()));
            if (analysis == null) {
                // something bad happened
                if (reportError) {
                    registerDescrBuildError(context, descr, "Unable to analyze expression '" + fieldName + "'");
                }
                return null;
            }
            final BoundIdentifiers usedIdentifiers = analysis.getBoundIdentifiers();
            if (!usedIdentifiers.getDeclrClasses().isEmpty()) {
                if (reportError && descr instanceof BindingDescr) {
                    registerDescrBuildError(context, descr, "Variables can not be used inside bindings. Variable " + usedIdentifiers.getDeclrClasses().keySet() + " is being used in binding '" + fieldName + "'");
                }
                return null;
            }
            reader = context.getPkg().getClassFieldAccessorStore().getMVELReader(context.getPkg().getName(), objectType.getClassName(), fieldName, context.isTypesafe(), ((MVELAnalysisResult) analysis).getReturnType());
            MVELDialectRuntimeData data = (MVELDialectRuntimeData) context.getPkg().getDialectRuntimeRegistry().getDialectData("mvel");
            ((MVELCompileable) reader).compile(data, context.getRule());
            data.addCompileable((MVELCompileable) reader);
        } catch (final Exception e) {
            int dotPos = fieldName.indexOf('.');
            String varName = dotPos > 0 ? fieldName.substring(0, dotPos).trim() : fieldName;
            if (context.getKnowledgeBuilder().getGlobals().containsKey(varName)) {
                return null;
            }
            if (reportError) {
                DialectUtil.copyErrorLocation(e, descr);
                registerDescrBuildError(context, descr, e, "Unable to create reader for '" + fieldName + "':" + e.getMessage());
            }
            // if there was an error, set the reader back to null
            reader = null;
        } finally {
            context.setDialect(dialect);
        }
    }
    return reader;
}
Also used : FactTemplateFieldExtractor(org.drools.core.facttemplates.FactTemplateFieldExtractor) BindingDescr(org.drools.compiler.lang.descr.BindingDescr) MVELCompileable(org.drools.core.base.mvel.MVELCompileable) DroolsErrorWrapper(org.drools.compiler.compiler.DroolsErrorWrapper) MVELDialect(org.drools.compiler.rule.builder.dialect.mvel.MVELDialect) DroolsParserException(org.drools.compiler.compiler.DroolsParserException) AnalysisResult(org.drools.compiler.compiler.AnalysisResult) MVELAnalysisResult(org.drools.compiler.rule.builder.dialect.mvel.MVELAnalysisResult) BoundIdentifiers(org.drools.compiler.compiler.BoundIdentifiers) MVELDialectRuntimeData(org.drools.core.rule.MVELDialectRuntimeData) MVELAnalysisResult(org.drools.compiler.rule.builder.dialect.mvel.MVELAnalysisResult) ClassFieldReader(org.drools.core.base.ClassFieldReader) InternalReadAccessor(org.drools.core.spi.InternalReadAccessor) Dialect(org.drools.compiler.compiler.Dialect) MVELDialect(org.drools.compiler.rule.builder.dialect.mvel.MVELDialect) JavaDialect(org.drools.compiler.rule.builder.dialect.java.JavaDialect) FactTemplateObjectType(org.drools.core.facttemplates.FactTemplateObjectType) DroolsWarningWrapper(org.drools.compiler.compiler.DroolsWarningWrapper) Declaration(org.drools.core.rule.Declaration) TypeDeclaration(org.drools.core.rule.TypeDeclaration) FactTemplate(org.drools.core.facttemplates.FactTemplate) KnowledgeBuilderResult(org.kie.internal.builder.KnowledgeBuilderResult)

Example 14 with Declaration

use of org.drools.core.rule.Declaration 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 15 with Declaration

use of org.drools.core.rule.Declaration in project drools by kiegroup.

the class PatternBuilder method lookupObjectType.

private void lookupObjectType(RuleBuildContext context, PatternDescr patternDescr) {
    List<? extends BaseDescr> descrs = patternDescr.getConstraint().getDescrs();
    if (descrs.size() != 1 || !(descrs.get(0) instanceof ExprConstraintDescr)) {
        return;
    }
    ExprConstraintDescr descr = (ExprConstraintDescr) descrs.get(0);
    String expr = descr.getExpression();
    if (expr.charAt(0) != '/') {
        return;
    }
    XpathAnalysis xpathAnalysis = XpathAnalysis.analyze(expr);
    if (xpathAnalysis.hasError()) {
        registerDescrBuildError(context, patternDescr, "Invalid xpath expression '" + expr + "': " + xpathAnalysis.getError());
        return;
    }
    XpathPart firstXpathChunk = xpathAnalysis.getPart(0);
    String identifier = firstXpathChunk.getField();
    DeclarationScopeResolver resolver = context.getDeclarationResolver();
    if (resolver.hasDataSource(identifier)) {
        patternDescr.setObjectType(findObjectType(context, firstXpathChunk, identifier));
        FromDescr fromDescr = new FromDescr();
        fromDescr.setDataSource(new MVELExprDescr(identifier));
        patternDescr.setSource(fromDescr);
        patternDescr.removeAllConstraint();
        firstXpathChunk.getConstraints().forEach(s -> patternDescr.addConstraint(new ExprConstraintDescr(s)));
        if (!xpathAnalysis.isSinglePart()) {
            patternDescr.addConstraint(new ExprConstraintDescr(patternDescr.getIdentifier() + " : " + expr.substring(xpathAnalysis.getPart(1).getStart())));
            patternDescr.setIdentifier("$void$");
        }
    } else {
        Declaration declr = resolver.getDeclaration(identifier);
        patternDescr.setXpathStartDeclaration(declr);
        patternDescr.setObjectType(declr.getExtractor().getExtractToClassName());
        expr = patternDescr.getIdentifier() + (patternDescr.isUnification() ? " := " : " : ") + expr.substring(identifier.length() + 1);
        descr.setExpression(expr);
    }
}
Also used : XpathPart(org.drools.compiler.rule.builder.XpathAnalysis.XpathPart) DeclarationScopeResolver(org.drools.core.spi.DeclarationScopeResolver) FromDescr(org.drools.compiler.lang.descr.FromDescr) MVELExprDescr(org.drools.compiler.lang.descr.MVELExprDescr) Declaration(org.drools.core.rule.Declaration) TypeDeclaration(org.drools.core.rule.TypeDeclaration) ExprConstraintDescr(org.drools.compiler.lang.descr.ExprConstraintDescr)

Aggregations

Declaration (org.drools.core.rule.Declaration)115 Pattern (org.drools.core.rule.Pattern)42 ClassObjectType (org.drools.core.base.ClassObjectType)29 InternalReadAccessor (org.drools.core.spi.InternalReadAccessor)27 TypeDeclaration (org.drools.core.rule.TypeDeclaration)24 InternalFactHandle (org.drools.core.common.InternalFactHandle)22 ArrayList (java.util.ArrayList)19 HashMap (java.util.HashMap)17 BoundIdentifiers (org.drools.compiler.compiler.BoundIdentifiers)17 DescrBuildError (org.drools.compiler.compiler.DescrBuildError)16 Test (org.junit.Test)16 KnowledgeHelper (org.drools.core.spi.KnowledgeHelper)14 InternalWorkingMemory (org.drools.core.common.InternalWorkingMemory)12 WorkingMemory (org.drools.core.WorkingMemory)11 MVELCompilationUnit (org.drools.core.base.mvel.MVELCompilationUnit)11 RuleImpl (org.drools.core.definitions.rule.impl.RuleImpl)11 MvelConstraint (org.drools.core.rule.constraint.MvelConstraint)10 Consequence (org.drools.core.spi.Consequence)10 Constraint (org.drools.core.spi.Constraint)10 AnalysisResult (org.drools.compiler.compiler.AnalysisResult)9