Search in sources :

Example 1 with MVELDialect

use of org.drools.compiler.rule.builder.dialect.mvel.MVELDialect in project drools by kiegroup.

the class TypeDeclarationConfigurator method getMvelAnalysisResult.

private static MVELAnalysisResult getMvelAnalysisResult(KnowledgeBuilderImpl kbuilder, BaseDescr typeDescr, TypeDeclaration type, PackageRegistry pkgRegistry, String durationField, InternalKnowledgePackage pkg) {
    MVELDialect dialect = (MVELDialect) pkgRegistry.getDialectCompiletimeRegistry().getDialect("mvel");
    PackageBuildContext context = new PackageBuildContext();
    context.init(kbuilder, pkg, typeDescr, pkgRegistry.getDialectCompiletimeRegistry(), dialect, null);
    if (!type.isTypesafe()) {
        context.setTypesafe(false);
    }
    return (MVELAnalysisResult) context.getDialect().analyzeExpression(context, typeDescr, durationField, new BoundIdentifiers(type.getTypeClass()));
}
Also used : PackageBuildContext(org.drools.compiler.rule.builder.PackageBuildContext) MVELAnalysisResult(org.drools.compiler.rule.builder.dialect.mvel.MVELAnalysisResult) MVELDialect(org.drools.compiler.rule.builder.dialect.mvel.MVELDialect) BoundIdentifiers(org.drools.compiler.compiler.BoundIdentifiers)

Example 2 with MVELDialect

use of org.drools.compiler.rule.builder.dialect.mvel.MVELDialect in project drools by kiegroup.

the class MVELConstraintBuilder method buildCompilationUnit.

public MVELCompilationUnit buildCompilationUnit(final RuleBuildContext context, final Declaration[] previousDeclarations, final Declaration[] localDeclarations, final PredicateDescr predicateDescr, final AnalysisResult analysis) {
    if (context.isTypesafe() && analysis instanceof MVELAnalysisResult) {
        Class<?> returnClass = ((MVELAnalysisResult) analysis).getReturnType();
        if (returnClass != Boolean.class && returnClass != Boolean.TYPE) {
            context.addError(new DescrBuildError(context.getParentDescr(), predicateDescr, null, "Predicate '" + predicateDescr.getContent() + "' must be a Boolean expression\n" + predicateDescr.positionAsString()));
        }
    }
    MVELDialect dialect = (MVELDialect) context.getDialect("mvel");
    MVELCompilationUnit unit = null;
    try {
        Map<String, Class<?>> declIds = context.getDeclarationResolver().getDeclarationClasses(context.getRule());
        Pattern p = (Pattern) context.getDeclarationResolver().peekBuildStack();
        if (p.getObjectType() instanceof ClassObjectType) {
            declIds.put("this", ((ClassObjectType) p.getObjectType()).getClassType());
        }
        unit = dialect.getMVELCompilationUnit((String) predicateDescr.getContent(), analysis, previousDeclarations, localDeclarations, null, context, "drools", KnowledgeHelper.class, context.isInXpath(), MVELCompilationUnit.Scope.CONSTRAINT);
    } catch (final Exception e) {
        copyErrorLocation(e, predicateDescr);
        context.addError(new DescrBuildError(context.getParentDescr(), predicateDescr, e, "Unable to build expression for 'inline-eval' : " + e.getMessage() + "'" + predicateDescr.getContent() + "'\n" + e.getMessage()));
    }
    return unit;
}
Also used : Pattern(org.drools.core.rule.Pattern) ClassObjectType(org.drools.core.base.ClassObjectType) MVELCompilationUnit(org.drools.core.base.mvel.MVELCompilationUnit) MVELDialect(org.drools.compiler.rule.builder.dialect.mvel.MVELDialect) DescrBuildError(org.drools.compiler.compiler.DescrBuildError) MVELAnalysisResult(org.drools.compiler.rule.builder.dialect.mvel.MVELAnalysisResult) KnowledgeHelper(org.drools.core.spi.KnowledgeHelper)

Example 3 with MVELDialect

use of org.drools.compiler.rule.builder.dialect.mvel.MVELDialect in project drools by kiegroup.

the class DialectUtil method fixBlockDescr.

public static String fixBlockDescr(final RuleBuildContext context, final JavaAnalysisResult analysis, Map<String, Declaration> decls, List<JavaBlockDescr> blocks) {
    MVELDialect mvel = (MVELDialect) context.getDialect("mvel");
    String originalCode = analysis.getAnalyzedExpr();
    BoundIdentifiers bindings = analysis.getBoundIdentifiers();
    // sorting exit points for correct order iteration
    Collections.sort(blocks, new Comparator<JavaBlockDescr>() {

        public int compare(JavaBlockDescr o1, JavaBlockDescr o2) {
            return o1.getStart() - o2.getStart();
        }
    });
    StringBuilder consequence = new StringBuilder();
    int lastAdded = 0;
    for (JavaBlockDescr block : blocks) {
        if (block.getEnd() == 0 || block.getEnd() > originalCode.length()) {
            // do nothing, it was incorrectly parsed, but this error should be picked up else where
            continue;
        }
        // adding chunk
        consequence.append(originalCode.substring(lastAdded, block.getStart() - 1));
        lastAdded = block.getEnd();
        switch(block.getType()) {
            case MODIFY:
            case UPDATE:
            case DELETE:
                rewriteDescr(context, originalCode, mvel, consequence, block, bindings, decls);
                break;
            case ENTRY:
            case EXIT:
            case CHANNEL:
                rewriteInterfacePoint(context, originalCode, consequence, (JavaInterfacePointsDescr) block);
                break;
            case INSERT:
                parseInsertDescr(context, block);
            default:
                consequence.append(originalCode.substring(block.getStart() - 1, lastAdded));
        }
    }
    consequence.append(originalCode.substring(lastAdded));
    return consequence.toString();
}
Also used : MVELDialect(org.drools.compiler.rule.builder.dialect.mvel.MVELDialect) BoundIdentifiers(org.drools.compiler.compiler.BoundIdentifiers) JavaBlockDescr(org.drools.compiler.rule.builder.dialect.java.parser.JavaBlockDescr)

Example 4 with MVELDialect

use of org.drools.compiler.rule.builder.dialect.mvel.MVELDialect in project drools by kiegroup.

the class DialectUtil method getInputs.

private static Map<String, Class<?>> getInputs(final RuleBuildContext context, String code, BoundIdentifiers bindings, Map<String, Class<?>> parentVars) {
    MVELDialect mvel = (MVELDialect) context.getDialect("mvel");
    MVELAnalysisResult mvelAnalysis = null;
    try {
        mvelAnalysis = (MVELAnalysisResult) mvel.analyzeBlock(context, code, bindings, parentVars, "drools", KnowledgeHelper.class);
    } catch (Exception e) {
    // swallow this as the error will be reported else where
    }
    return (mvelAnalysis != null) ? mvelAnalysis.getMvelVariables() : new HashMap<String, Class<?>>();
}
Also used : MVELAnalysisResult(org.drools.compiler.rule.builder.dialect.mvel.MVELAnalysisResult) MVELDialect(org.drools.compiler.rule.builder.dialect.mvel.MVELDialect) CompileException(org.mvel2.CompileException)

Example 5 with MVELDialect

use of org.drools.compiler.rule.builder.dialect.mvel.MVELDialect 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)

Aggregations

MVELDialect (org.drools.compiler.rule.builder.dialect.mvel.MVELDialect)6 MVELAnalysisResult (org.drools.compiler.rule.builder.dialect.mvel.MVELAnalysisResult)4 BoundIdentifiers (org.drools.compiler.compiler.BoundIdentifiers)3 Dialect (org.drools.compiler.compiler.Dialect)2 JavaDialect (org.drools.compiler.rule.builder.dialect.java.JavaDialect)2 AnalysisResult (org.drools.compiler.compiler.AnalysisResult)1 DescrBuildError (org.drools.compiler.compiler.DescrBuildError)1 DroolsErrorWrapper (org.drools.compiler.compiler.DroolsErrorWrapper)1 DroolsParserException (org.drools.compiler.compiler.DroolsParserException)1 DroolsWarningWrapper (org.drools.compiler.compiler.DroolsWarningWrapper)1 BindingDescr (org.drools.compiler.lang.descr.BindingDescr)1 PredicateDescr (org.drools.compiler.lang.descr.PredicateDescr)1 PackageBuildContext (org.drools.compiler.rule.builder.PackageBuildContext)1 JavaBlockDescr (org.drools.compiler.rule.builder.dialect.java.parser.JavaBlockDescr)1 ClassFieldReader (org.drools.core.base.ClassFieldReader)1 ClassObjectType (org.drools.core.base.ClassObjectType)1 MVELCompilationUnit (org.drools.core.base.mvel.MVELCompilationUnit)1 MVELCompileable (org.drools.core.base.mvel.MVELCompileable)1 FactTemplate (org.drools.core.facttemplates.FactTemplate)1 FactTemplateFieldExtractor (org.drools.core.facttemplates.FactTemplateFieldExtractor)1