use of org.drools.core.base.mvel.MVELCompilationUnit in project drools by kiegroup.
the class MVELAccumulateBuilder method buildCustomAccumulate.
private Accumulator[] buildCustomAccumulate(final RuleBuildContext context, final AccumulateDescr accumDescr, MVELDialect dialect, Map<String, Declaration> decls, Map<String, Declaration> sourceOuterDeclr, BoundIdentifiers boundIds, boolean readLocalsFromTuple) {
Accumulator[] accumulators;
final MVELAnalysisResult initCodeAnalysis = (MVELAnalysisResult) dialect.analyzeBlock(context, accumDescr, accumDescr.getInitCode(), boundIds);
// need to copy boundIds, as this as a "this" object.
final MVELAnalysisResult actionCodeAnalysis = (MVELAnalysisResult) dialect.analyzeBlock(context, accumDescr.getActionCode(), boundIds, initCodeAnalysis.getMvelVariables(), "drools", KnowledgeHelper.class);
final MVELAnalysisResult resultCodeAnalysis = (MVELAnalysisResult) dialect.analyzeExpression(context, accumDescr, accumDescr.getResultCode(), boundIds, initCodeAnalysis.getMvelVariables());
context.setTypesafe(initCodeAnalysis.isTypesafe());
MVELCompilationUnit initUnit = dialect.getMVELCompilationUnit(accumDescr.getInitCode(), initCodeAnalysis, getUsedDeclarations(decls, initCodeAnalysis), getUsedDeclarations(sourceOuterDeclr, initCodeAnalysis), initCodeAnalysis.getMvelVariables(), context, "drools", KnowledgeHelper.class, readLocalsFromTuple, MVELCompilationUnit.Scope.CONSTRAINT);
context.setTypesafe(actionCodeAnalysis.isTypesafe());
MVELCompilationUnit actionUnit = dialect.getMVELCompilationUnit(accumDescr.getActionCode(), actionCodeAnalysis, getUsedDeclarations(decls, actionCodeAnalysis), getUsedDeclarations(sourceOuterDeclr, actionCodeAnalysis), initCodeAnalysis.getMvelVariables(), context, "drools", KnowledgeHelper.class, readLocalsFromTuple, MVELCompilationUnit.Scope.CONSTRAINT);
MVELCompilationUnit reverseUnit = null;
if (accumDescr.getReverseCode() != null) {
context.setTypesafe(actionCodeAnalysis.isTypesafe());
reverseUnit = dialect.getMVELCompilationUnit(accumDescr.getReverseCode(), actionCodeAnalysis, getUsedDeclarations(decls, actionCodeAnalysis), getUsedDeclarations(sourceOuterDeclr, actionCodeAnalysis), initCodeAnalysis.getMvelVariables(), context, "drools", KnowledgeHelper.class, readLocalsFromTuple, MVELCompilationUnit.Scope.CONSTRAINT);
}
context.setTypesafe(resultCodeAnalysis.isTypesafe());
MVELCompilationUnit resultUnit = dialect.getMVELCompilationUnit(accumDescr.getResultCode(), resultCodeAnalysis, getUsedDeclarations(decls, resultCodeAnalysis), getUsedDeclarations(sourceOuterDeclr, resultCodeAnalysis), initCodeAnalysis.getMvelVariables(), context, "drools", KnowledgeHelper.class, readLocalsFromTuple, MVELCompilationUnit.Scope.CONSTRAINT);
accumulators = new Accumulator[] { new MVELAccumulator(initUnit, actionUnit, reverseUnit, resultUnit) };
return accumulators;
}
use of org.drools.core.base.mvel.MVELCompilationUnit in project drools by kiegroup.
the class MVELEvalBuilder method build.
/**
* Builds and returns an Eval Conditional Element
*
* @param context The current build context
* @param descr The Eval Descriptor to build the eval conditional element from
*
* @return the Eval Conditional Element
*/
public RuleConditionElement build(final RuleBuildContext context, final BaseDescr descr, final Pattern prefixPattern) {
boolean typesafe = context.isTypesafe();
// it must be an EvalDescr
final EvalDescr evalDescr = (EvalDescr) descr;
try {
MVELDialect dialect = (MVELDialect) context.getDialect("mvel");
Map<String, Declaration> decls = context.getDeclarationResolver().getDeclarations(context.getRule());
AnalysisResult analysis = context.getDialect().analyzeExpression(context, evalDescr, evalDescr.getContent(), new BoundIdentifiers(DeclarationScopeResolver.getDeclarationClasses(decls), context));
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, SortDeclarations.instance);
MVELCompilationUnit unit = dialect.getMVELCompilationUnit((String) evalDescr.getContent(), analysis, previousDeclarations, null, null, context, "drools", KnowledgeHelper.class, false, MVELCompilationUnit.Scope.EXPRESSION);
final EvalCondition eval = new EvalCondition(previousDeclarations);
MVELEvalExpression expr = new MVELEvalExpression(unit, dialect.getId());
eval.setEvalExpression(KiePolicyHelper.isPolicyEnabled() ? new SafeEvalExpression(expr) : expr);
MVELDialectRuntimeData data = (MVELDialectRuntimeData) context.getPkg().getDialectRuntimeRegistry().getDialectData("mvel");
data.addCompileable(eval, expr);
expr.compile(data, context.getRule());
return eval;
} catch (final Exception e) {
copyErrorLocation(e, evalDescr);
context.addError(new DescrBuildError(context.getParentDescr(), evalDescr, e, "Unable to build expression for 'eval':" + e.getMessage() + " '" + evalDescr.getContent() + "'"));
return null;
} finally {
context.setTypesafe(typesafe);
}
}
use of org.drools.core.base.mvel.MVELCompilationUnit in project drools by kiegroup.
the class MVELFromBuilder method build.
public RuleConditionElement build(final RuleBuildContext context, final BaseDescr descr, final Pattern prefixPattern) {
String text = ((FromDescr) descr).getExpression();
Optional<EntryPointId> entryPointId = context.getEntryPointId(text);
if (entryPointId.isPresent()) {
return entryPointId.get();
}
// This builder is re-usable in other dialects, so specify by name
MVELDialect dialect = (MVELDialect) context.getDialect("mvel");
boolean typeSafe = context.isTypesafe();
if (!dialect.isStrictMode()) {
context.setTypesafe(false);
}
try {
Map<String, Declaration> decls = context.getDeclarationResolver().getDeclarations(context.getRule());
AnalysisResult analysis = dialect.analyzeExpression(context, descr, text, new BoundIdentifiers(DeclarationScopeResolver.getDeclarationClasses(decls), context));
if (analysis == null) {
// something bad happened
return null;
}
Class<?> returnType = ((MVELAnalysisResult) analysis).getReturnType();
if (prefixPattern != null && !prefixPattern.isCompatibleWithFromReturnType(returnType)) {
context.addError(new DescrBuildError(descr, context.getRuleDescr(), null, "Pattern of type: '" + prefixPattern.getObjectType() + "' on rule '" + context.getRuleDescr().getName() + "' is not compatible with type " + returnType.getCanonicalName() + " returned by source"));
return null;
}
final BoundIdentifiers usedIdentifiers = analysis.getBoundIdentifiers();
final Declaration[] declarations = new Declaration[usedIdentifiers.getDeclrClasses().size()];
int j = 0;
for (String str : usedIdentifiers.getDeclrClasses().keySet()) {
declarations[j++] = decls.get(str);
}
Arrays.sort(declarations, SortDeclarations.instance);
MVELCompilationUnit unit = dialect.getMVELCompilationUnit(text, analysis, declarations, null, null, context, "drools", KnowledgeHelper.class, false, MVELCompilationUnit.Scope.CONSEQUENCE);
MVELDataProvider dataProvider = new MVELDataProvider(unit, context.getDialect().getId());
From from = new From(dataProvider);
from.setResultPattern(prefixPattern);
MVELDialectRuntimeData data = (MVELDialectRuntimeData) context.getPkg().getDialectRuntimeRegistry().getDialectData("mvel");
data.addCompileable(from, dataProvider);
dataProvider.compile(data, context.getRule());
return from;
} catch (final Exception e) {
DialectUtil.copyErrorLocation(e, descr);
context.addError(new DescrBuildError(context.getParentDescr(), descr, null, "Unable to build expression for 'from' : " + e.getMessage() + " '" + text + "'"));
return null;
} finally {
context.setTypesafe(typeSafe);
}
}
use of org.drools.core.base.mvel.MVELCompilationUnit in project drools by kiegroup.
the class MVELReturnValueBuilder method build.
public void build(final RuleBuildContext context, final BoundIdentifiers usedIdentifiers, final Declaration[] previousDeclarations, final Declaration[] localDeclarations, final ReturnValueRestriction returnValueRestriction, final ReturnValueRestrictionDescr returnValueRestrictionDescr, final AnalysisResult analysis) {
boolean typesafe = context.isTypesafe();
try {
MVELDialect dialect = (MVELDialect) context.getDialect("mvel");
context.setTypesafe(((MVELAnalysisResult) analysis).isTypesafe());
MVELCompilationUnit unit = dialect.getMVELCompilationUnit((String) returnValueRestrictionDescr.getContent(), analysis, previousDeclarations, localDeclarations, null, context, "drools", KnowledgeHelper.class, false, MVELCompilationUnit.Scope.EXPRESSION);
MVELReturnValueExpression expr = new MVELReturnValueExpression(unit, context.getDialect().getId());
returnValueRestriction.setReturnValueExpression(expr);
MVELDialectRuntimeData data = (MVELDialectRuntimeData) context.getPkg().getDialectRuntimeRegistry().getDialectData("mvel");
data.addCompileable(returnValueRestriction, 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 'returnValue' : " + e.getMessage() + "'" + context.getRuleDescr().getSalience() + "'"));
} finally {
context.setTypesafe(typesafe);
}
}
use of org.drools.core.base.mvel.MVELCompilationUnit in project drools by kiegroup.
the class MVELConsequence method evaluate.
@Override
public void evaluate(KnowledgeHelper knowledgeHelper, WorkingMemory workingMemory) throws Exception {
// same as lambda consequence...
Tuple tuple = knowledgeHelper.getTuple();
Declaration[] declarations = ((RuleTerminalNode) knowledgeHelper.getMatch().getTuple().getTupleSink()).getRequiredDeclarations();
Variable[] vars = consequence.getVariables();
// ...but the facts are association of Variable and its value, preserving order.
Map<Variable, Object> facts = new LinkedHashMap<>();
int declrCounter = 0;
for (Variable var : vars) {
if (var.isFact()) {
Declaration declaration = declarations[declrCounter++];
InternalFactHandle fh = tuple.get(declaration);
facts.put(var, declaration.getValue((InternalWorkingMemory) workingMemory, fh.getObject()));
} else {
facts.put(var, workingMemory.getGlobal(var.getName()));
}
}
ScriptBlock scriptBlock = null;
try {
scriptBlock = (ScriptBlock) consequence.getBlock();
} catch (ClassCastException e) {
throw new RuntimeException("I tried to access a ScriptBlock but it was not. So something is thinking is a MVEL consequence but did not set the MVEL script textual representation", e);
}
String originalRHS = scriptBlock.getScript();
String name = context.getRule().getPackageName() + "." + context.getRule().getName();
String expression = MVELConsequenceBuilder.processMacros(originalRHS);
String[] globalIdentifiers = new String[] {};
String[] default_inputIdentifiers = new String[] { "this", "drools", "kcontext", "rule" };
String[] inputIdentifiers = Stream.concat(Arrays.asList(default_inputIdentifiers).stream(), facts.entrySet().stream().map(kv -> kv.getKey().getName())).collect(Collectors.toList()).toArray(new String[] {});
String[] default_inputTypes = new String[] { "org.drools.core.spi.KnowledgeHelper", "org.drools.core.spi.KnowledgeHelper", "org.drools.core.spi.KnowledgeHelper", "org.kie.api.definition.rule.Rule" };
String[] inputTypes = Stream.concat(Arrays.asList(default_inputTypes).stream(), facts.entrySet().stream().map(kv -> kv.getKey().getType().getName())).collect(Collectors.toList()).toArray(new String[] {});
// ^^ please notice about inputTypes, it is to use the Class.getName(), because is later used by the Classloader internally in MVEL to load the class,
// do NOT replace with getCanonicalName() otherwise inner classes will not be loaded correctly.
int languageLevel = 4;
boolean strictMode = true;
boolean readLocalsFromTuple = false;
EvaluatorWrapper[] operators = new EvaluatorWrapper[] {};
Declaration[] previousDeclarations = new Declaration[] {};
Declaration[] localDeclarations = new Declaration[] {};
String[] otherIdentifiers = new String[] {};
MVELCompilationUnit cu = new MVELCompilationUnit(name, expression, globalIdentifiers, operators, previousDeclarations, localDeclarations, otherIdentifiers, inputIdentifiers, inputTypes, languageLevel, strictMode, readLocalsFromTuple);
// TODO unfortunately the MVELDialectRuntimeData would be the one of compile time
// the one from runtime is not helpful, in fact the dialect registry for runtime is empty:
// MVELDialectRuntimeData runtimeData = (MVELDialectRuntimeData) context.getPkg().getDialectRuntimeRegistry().getDialectData("mvel");
MVELDialectRuntimeData runtimeData = new MVELDialectRuntimeData();
// this classloader will be used by the CompilationUnit to load the imports.
runtimeData.onAdd(null, Thread.currentThread().getContextClassLoader());
runtimeData.addPackageImport(context.getPkg().getName());
runtimeData.addPackageImport("java.lang");
// therefore we assume for the ScriptBlock all available KBPackages are the default available and imported for the scope of the Script itself.
for (KiePackage kp : context.getKnowledgePackages()) {
if (!kp.getName().equals(context.getPkg().getName())) {
runtimeData.addPackageImport(kp.getName());
}
}
// sometimes here it was passed as a 2nd argument a String?? similar to `rule R in file file.drl`
Serializable cuResult = cu.getCompiledExpression(runtimeData);
ExecutableStatement compiledExpression = (ExecutableStatement) cuResult;
// TODO the part above up to the ExecutableStatement compiledExpression should be cached.
Map<String, Object> mvelContext = new HashMap<>();
mvelContext.put("this", knowledgeHelper);
mvelContext.put("drools", knowledgeHelper);
mvelContext.put("kcontext", knowledgeHelper);
mvelContext.put("rule", knowledgeHelper.getRule());
for (Entry<Variable, Object> kv : facts.entrySet()) {
mvelContext.put(kv.getKey().getName(), kv.getValue());
}
CachingMapVariableResolverFactory cachingFactory = new CachingMapVariableResolverFactory(mvelContext);
VariableResolverFactory factory = cu.getFactory(knowledgeHelper, ((AgendaItem) knowledgeHelper.getMatch()).getTerminalNode().getRequiredDeclarations(), knowledgeHelper.getRule(), knowledgeHelper.getTuple(), null, (InternalWorkingMemory) workingMemory, workingMemory.getGlobalResolver());
cachingFactory.setNextFactory(factory);
MVEL.executeExpression(compiledExpression, knowledgeHelper, cachingFactory);
}
Aggregations