Search in sources :

Example 81 with Declaration

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

the class JavaAccumulateBuilder method buildInlineAccumulate.

private Accumulate buildInlineAccumulate(final RuleBuildContext context, final AccumulateDescr accumDescr, final RuleConditionElement source, Map<String, Declaration> decls, Map<String, Class<?>> declCls, final boolean readLocalsFromTuple) {
    // ELSE, if it is not an external function, build it using the regular java builder
    final String className = "Accumulate" + context.getNextId();
    accumDescr.setClassName(className);
    BoundIdentifiers available = new BoundIdentifiers(declCls, context);
    final JavaAnalysisResult initCodeAnalysis = (JavaAnalysisResult) context.getDialect().analyzeBlock(context, accumDescr, accumDescr.getInitCode(), available);
    final AnalysisResult actionCodeAnalysis = context.getDialect().analyzeBlock(context, accumDescr, accumDescr.getActionCode(), available);
    final AnalysisResult resultCodeAnalysis = context.getDialect().analyzeExpression(context, accumDescr, accumDescr.getResultCode(), available);
    if (initCodeAnalysis == null || actionCodeAnalysis == null || resultCodeAnalysis == null) {
        // not possible to get the analysis results - compilation error has been already logged
        return null;
    }
    final Set<String> requiredDeclarations = new HashSet<String>(initCodeAnalysis.getBoundIdentifiers().getDeclrClasses().keySet());
    requiredDeclarations.addAll(actionCodeAnalysis.getBoundIdentifiers().getDeclrClasses().keySet());
    requiredDeclarations.addAll(resultCodeAnalysis.getBoundIdentifiers().getDeclrClasses().keySet());
    final Map<String, Class<?>> requiredGlobals = new HashMap<String, Class<?>>(initCodeAnalysis.getBoundIdentifiers().getGlobals());
    requiredGlobals.putAll(actionCodeAnalysis.getBoundIdentifiers().getGlobals());
    requiredGlobals.putAll(resultCodeAnalysis.getBoundIdentifiers().getGlobals());
    if (accumDescr.getReverseCode() != null) {
        final AnalysisResult reverseCodeAnalysis = context.getDialect().analyzeBlock(context, accumDescr, accumDescr.getActionCode(), available);
        requiredDeclarations.addAll(reverseCodeAnalysis.getBoundIdentifiers().getDeclrClasses().keySet());
        requiredGlobals.putAll(reverseCodeAnalysis.getBoundIdentifiers().getGlobals());
    }
    final Declaration[] declarations = new Declaration[requiredDeclarations.size()];
    int i = 0;
    for (Iterator<String> it = requiredDeclarations.iterator(); it.hasNext(); i++) {
        declarations[i] = decls.get(it.next());
    }
    final Declaration[] sourceDeclArr = source.getOuterDeclarations().values().toArray(new Declaration[source.getOuterDeclarations().size()]);
    Arrays.sort(sourceDeclArr, RuleTerminalNode.SortDeclarations.instance);
    final Map<String, Object> map = createVariableContext(className, null, context, declarations, null, requiredGlobals);
    map.put("className", accumDescr.getClassName());
    map.put("innerDeclarations", sourceDeclArr);
    map.put("isMultiPattern", readLocalsFromTuple ? Boolean.TRUE : Boolean.FALSE);
    final String initCode = this.fixInitCode(initCodeAnalysis, accumDescr.getInitCode());
    final String actionCode = accumDescr.getActionCode();
    final String resultCode = accumDescr.getResultCode();
    String[] attributesTypes = new String[initCodeAnalysis.getLocalVariablesMap().size()];
    String[] attributes = new String[initCodeAnalysis.getLocalVariablesMap().size()];
    int index = 0;
    for (Map.Entry<String, JavaLocalDeclarationDescr> entry : initCodeAnalysis.getLocalVariablesMap().entrySet()) {
        attributes[index] = entry.getKey();
        attributesTypes[index] = entry.getValue().getType();
        index++;
    }
    map.put("attributes", attributes);
    map.put("attributesTypes", attributesTypes);
    map.put("initCode", initCode);
    map.put("actionCode", actionCode);
    map.put("resultCode", resultCode);
    if (accumDescr.getReverseCode() == null) {
        map.put("reverseCode", "");
        map.put("supportsReverse", "false");
    } else {
        map.put("reverseCode", accumDescr.getReverseCode());
        map.put("supportsReverse", "true");
    }
    map.put("hashCode", actionCode.hashCode());
    SingleAccumulate accumulate = new SingleAccumulate(source, declarations);
    generateTemplates("accumulateInnerClass", "accumulateInvoker", context, className, map, accumulate.new Wirer(), accumDescr);
    return accumulate;
}
Also used : HashMap(java.util.HashMap) SingleAccumulate(org.drools.core.rule.SingleAccumulate) AnalysisResult(org.drools.compiler.compiler.AnalysisResult) MutableTypeConstraint(org.drools.core.rule.MutableTypeConstraint) MvelConstraint(org.drools.core.rule.constraint.MvelConstraint) Constraint(org.drools.core.spi.Constraint) BoundIdentifiers(org.drools.compiler.compiler.BoundIdentifiers) JavaLocalDeclarationDescr(org.drools.compiler.rule.builder.dialect.java.parser.JavaLocalDeclarationDescr) Declaration(org.drools.core.rule.Declaration) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet)

Example 82 with Declaration

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

the class JavaRuleBuilderHelper method createConsequenceContext.

public static Map<String, Object> createConsequenceContext(final RuleBuildContext context, String consequenceName, String className, String consequenceText, Map<String, Declaration> decls, final BoundIdentifiers usedIdentifiers) {
    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, RuleTerminalNode.SortDeclarations.instance);
    for (int i = 0; i < declrStr.length; i++) {
        declrStr[i] = declarations[i].getIdentifier();
    }
    context.getRule().setRequiredDeclarationsForConsequence(consequenceName, declrStr);
    final Map<String, Object> map = createVariableContext(className, consequenceText, context, declarations, null, usedIdentifiers.getGlobals());
    map.put("consequenceName", consequenceName);
    // final int[] indexes = new int[declarations.length];
    final Integer[] indexes = new Integer[declarations.length];
    final Boolean[] notPatterns = new Boolean[declarations.length];
    for (int i = 0, length = declarations.length; i < length; i++) {
        indexes[i] = i;
        notPatterns[i] = (declarations[i].getExtractor() instanceof AcceptsClassObjectType) ? Boolean.FALSE : Boolean.TRUE;
        if (indexes[i] == -1) {
            context.addError(new DescrBuildError(context.getParentDescr(), context.getRuleDescr(), null, "Internal Error : Unable to find declaration in list while generating the consequence invoker"));
        }
    }
    map.put("indexes", indexes);
    map.put("notPatterns", notPatterns);
    return map;
}
Also used : DescrBuildError(org.drools.compiler.compiler.DescrBuildError) AcceptsClassObjectType(org.drools.core.spi.AcceptsClassObjectType) Declaration(org.drools.core.rule.Declaration)

Example 83 with Declaration

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

the class MVELEnabledBuilder method build.

public void build(RuleBuildContext context) {
    // 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, Class<?>> otherVars = new HashMap<String, Class<?>>();
        otherVars.put("rule", RuleImpl.class);
        Map<String, Declaration> declrs = context.getDeclarationResolver().getDeclarations(context.getRule());
        AnalysisResult analysis = dialect.analyzeExpression(context, context.getRuleDescr(), context.getRuleDescr().getEnabled(), new BoundIdentifiers(DeclarationScopeResolver.getDeclarationClasses(declrs), context), otherVars);
        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++] = declrs.get(id);
        }
        Arrays.sort(previousDeclarations, SortDeclarations.instance);
        String exprStr = context.getRuleDescr().getEnabled();
        exprStr = exprStr.substring(1, exprStr.length() - 1) + " ";
        MVELCompilationUnit unit = dialect.getMVELCompilationUnit(exprStr, analysis, previousDeclarations, null, otherVars, context, "drools", KnowledgeHelper.class, false, MVELCompilationUnit.Scope.EXPRESSION);
        MVELEnabledExpression expr = new MVELEnabledExpression(unit, dialect.getId());
        context.getRule().setEnabled(KiePolicyHelper.isPolicyEnabled() ? new SafeEnabled(expr) : expr);
        MVELDialectRuntimeData data = (MVELDialectRuntimeData) context.getPkg().getDialectRuntimeRegistry().getDialectData("mvel");
        data.addCompileable(context.getRule(), expr);
        expr.compile(data, context.getRule());
    } catch (final Exception e) {
        DialectUtil.copyErrorLocation(e, context.getRuleDescr());
        context.addError(new DescrBuildError(context.getParentDescr(), context.getRuleDescr(), null, "Unable to build expression for 'enabled' : " + e.getMessage() + " '" + context.getRuleDescr().getEnabled() + "'"));
    }
}
Also used : HashMap(java.util.HashMap) MVELCompilationUnit(org.drools.core.base.mvel.MVELCompilationUnit) SafeEnabled(org.drools.core.definitions.rule.impl.RuleImpl.SafeEnabled) AnalysisResult(org.drools.compiler.compiler.AnalysisResult) BoundIdentifiers(org.drools.compiler.compiler.BoundIdentifiers) MVELDialectRuntimeData(org.drools.core.rule.MVELDialectRuntimeData) DescrBuildError(org.drools.compiler.compiler.DescrBuildError) MVELEnabledExpression(org.drools.core.base.mvel.MVELEnabledExpression) Declaration(org.drools.core.rule.Declaration)

Example 84 with Declaration

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

the class MVELExprAnalyzer method getExpressionType.

public static Class<?> getExpressionType(PackageBuildContext context, Map<String, Class<?>> declCls, RuleConditionElement source, String expression) {
    MVELDialectRuntimeData data = (MVELDialectRuntimeData) context.getPkg().getDialectRuntimeRegistry().getDialectData("mvel");
    ParserConfiguration conf = data.getParserConfiguration();
    conf.setClassLoader(context.getKnowledgeBuilder().getRootClassLoader());
    ParserContext pctx = new ParserContext(conf);
    pctx.setStrongTyping(true);
    pctx.setStrictTypeEnforcement(true);
    for (Map.Entry<String, Class<?>> entry : declCls.entrySet()) {
        pctx.addInput(entry.getKey(), entry.getValue());
    }
    for (Declaration decl : source.getOuterDeclarations().values()) {
        pctx.addInput(decl.getBindingName(), decl.getDeclarationClass());
    }
    try {
        return MVEL.analyze(expression, pctx);
    } catch (Exception e) {
        log.warn("Unable to parse expression: " + expression, e);
    }
    return null;
}
Also used : MVELDialectRuntimeData(org.drools.core.rule.MVELDialectRuntimeData) Declaration(org.drools.core.rule.Declaration) ParserContext(org.mvel2.ParserContext) HashMap(java.util.HashMap) Map(java.util.Map) CompileException(org.mvel2.CompileException) RecognitionException(org.antlr.runtime.RecognitionException) ParserConfiguration(org.mvel2.ParserConfiguration)

Example 85 with Declaration

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

the class MVELObjectExpressionBuilder method build.

public static MVELObjectExpression build(String expression, 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(), expression, 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, RuleTerminalNode.SortDeclarations.instance);
        MVELCompilationUnit unit = dialect.getMVELCompilationUnit(expression, analysis, previousDeclarations, null, null, context, "drools", KnowledgeHelper.class, false, MVELCompilationUnit.Scope.EXPRESSION);
        MVELObjectExpression expr = new MVELObjectExpression(unit, dialect.getId());
        MVELDialectRuntimeData data = (MVELDialectRuntimeData) context.getPkg().getDialectRuntimeRegistry().getDialectData("mvel");
        data.addCompileable(context.getRule(), expr);
        expr.compile(data);
        return expr;
    } catch (final Exception e) {
        DialectUtil.copyErrorLocation(e, context.getRuleDescr());
        context.addError(new DescrBuildError(context.getParentDescr(), context.getRuleDescr(), null, "Unable to build expression : " + e.getMessage() + "'" + expression + "'"));
        return null;
    } finally {
        context.setTypesafe(typesafe);
    }
}
Also used : MVELCompilationUnit(org.drools.core.base.mvel.MVELCompilationUnit) BoundIdentifiers(org.drools.compiler.compiler.BoundIdentifiers) MVELDialectRuntimeData(org.drools.core.rule.MVELDialectRuntimeData) MVELObjectExpression(org.drools.core.base.mvel.MVELObjectExpression) DescrBuildError(org.drools.compiler.compiler.DescrBuildError) Declaration(org.drools.core.rule.Declaration)

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