-
Notifications
You must be signed in to change notification settings - Fork 2.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[incubator-kie-issues#1370] DMN: refactor BaseFEELFunction getCandidateMethod #6023
Merged
Merged
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
65ec7ba
[incubator-kie-issues#1370] Clean up signature/unused code
ea8371d
[incubator-kie-issues#1370] WIP. Implemented first unit test
4feb7f2
Merge remote-tracking branch 'origin/main' into incubator-kie-issues#…
fe59a99
[incubator-kie-issues#1370] WIP. Implemented unit tests
1ee265b
Merge remote-tracking branch 'origin/main' into incubator-kie-issues#…
3593a64
[incubator-kie-issues#1370] WIP. Further refactoring with unit tests.…
379664f
[incubator-kie-issues#1370] WIP. Begin ScorerHelper implementation. F…
07986f5
[incubator-kie-issues#1370] WIP. Implemented ScorerHelper with test. …
92568d7
Merge remote-tracking branch 'origin/main' into incubator-kie-issues#…
3d971b6
[incubator-kie-issues#1370] WIP. TODO: fix score logic - corner cases…
7d55494
[incubator-kie-issues#1370] Working. Implemented tests.
f454a17
[incubator-kie-issues#1370] Fully working. Fixing corner cases with O…
87e2e73
Merge remote-tracking branch 'origin/main' into incubator-kie-issues#…
14abbde
[incubator-kie-issues#1370] Implemented CustomFunction invocation test
ccd61e9
[incubator-kie-issues#1370] Improvement based on PR suggestion
b18ebba
[incubator-kie-issues#1370] Fix formatting
58dbabd
[incubator-kie-issues#1370] Benchmark improving - refactoring
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
389 changes: 120 additions & 269 deletions
389
kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/functions/BaseFEELFunction.java
Large diffs are not rendered by default.
Oops, something went wrong.
318 changes: 318 additions & 0 deletions
318
...kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/functions/BaseFEELFunctionHelper.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,318 @@ | ||
/** | ||
* Licensed to the Apache Software Foundation (ASF) under one | ||
* or more contributor license agreements. See the NOTICE file | ||
* distributed with this work for additional information | ||
* regarding copyright ownership. The ASF licenses this file | ||
* to you under the Apache License, Version 2.0 (the | ||
* "License"); you may not use this file except in compliance | ||
* with the License. You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, | ||
* software distributed under the License is distributed on an | ||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
* KIND, either express or implied. See the License for the | ||
* specific language governing permissions and limitations | ||
* under the License. | ||
*/ | ||
package org.kie.dmn.feel.runtime.functions; | ||
|
||
import java.lang.annotation.Annotation; | ||
import java.lang.reflect.Array; | ||
import java.lang.reflect.Method; | ||
import java.util.ArrayList; | ||
import java.util.Arrays; | ||
import java.util.List; | ||
import java.util.Optional; | ||
|
||
import org.kie.dmn.feel.lang.EvaluationContext; | ||
import org.kie.dmn.feel.lang.impl.NamedParameter; | ||
import org.kie.dmn.feel.util.NumberEvalHelper; | ||
import org.slf4j.Logger; | ||
import org.slf4j.LoggerFactory; | ||
|
||
import static org.kie.dmn.feel.util.CoerceUtil.coerceParams; | ||
|
||
public class BaseFEELFunctionHelper { | ||
|
||
private final static Logger logger = LoggerFactory.getLogger(BaseFEELFunctionHelper.class); | ||
|
||
static Object[] getAdjustedParametersForMethod(EvaluationContext ctx, Object[] params, boolean isNamedParams, | ||
Method m) { | ||
logger.trace("getAdjustedParametersForMethod {} {} {} {}", ctx, params, isNamedParams, m); | ||
Object[] toReturn = addCtxParamIfRequired(ctx, params, isNamedParams, m); | ||
Class<?>[] parameterTypes = m.getParameterTypes(); | ||
if (isNamedParams) { | ||
// This is inherently frail because it expects that, if, the first parameter is NamedParameter and the | ||
// function is a CustomFunction, then all parameters are NamedParameter | ||
NamedParameter[] namedParams = | ||
Arrays.stream(toReturn).map(NamedParameter.class::cast).toArray(NamedParameter[]::new); | ||
toReturn = BaseFEELFunctionHelper.calculateActualParams(m, namedParams); | ||
if (toReturn == null) { | ||
// incompatible method | ||
return null; | ||
} | ||
} else if (toReturn.length > 0) { | ||
// if named parameters, then it has been adjusted already in the calculateActualParams method, | ||
// otherwise adjust here | ||
toReturn = adjustForVariableParameters(toReturn, parameterTypes); | ||
} | ||
toReturn = adjustByCoercion(parameterTypes, toReturn); | ||
return toReturn; | ||
} | ||
|
||
/** | ||
* This method check if the input parameters, set inside the given <code>CandidateMethod</code>, | ||
* could match the given <code>parameterTypes</code>, eventually <b>coerced</b>. | ||
* In case of match with coercion, a new <code>Object[]</code> with coerced values is returned. | ||
* @param parameterTypes | ||
* @param actualParams | ||
* @return an <code>Object[]</code>, with values eventually coerced, or <code>null</code> for incompatible and not coercible values | ||
*/ | ||
static Object[] adjustByCoercion(Class<?>[] parameterTypes, Object[] actualParams) { | ||
logger.trace("adjustByCoercion {} {}", parameterTypes, actualParams); | ||
Object[] toReturn = actualParams; | ||
int counter = Math.min(parameterTypes.length, actualParams.length); | ||
for (int i = 0; i < counter; i++) { | ||
Class<?> expectedParameterType = parameterTypes[i]; | ||
Optional<Object[]> coercedParams; | ||
Object actualParam = actualParams[i]; | ||
if (actualParam != null) { | ||
Class<?> currentIdxActualParameterType = actualParam.getClass(); | ||
if (expectedParameterType.isAssignableFrom(currentIdxActualParameterType)) { | ||
// not null object assignable to expected type: no need to coerce | ||
coercedParams = Optional.of(toReturn); | ||
} else { | ||
// attempt to coerce | ||
coercedParams = coerceParams(currentIdxActualParameterType, | ||
expectedParameterType, toReturn, i); | ||
} | ||
} else { | ||
// null object - no need to coerce | ||
coercedParams = Optional.of(toReturn); | ||
} | ||
if (coercedParams.isPresent()) { | ||
toReturn = coercedParams.get(); | ||
continue; | ||
} | ||
return null; | ||
} | ||
return toReturn; | ||
} | ||
|
||
/** | ||
* This method insert <code>context</code> reference inside the given parameters, if the given | ||
* <code>Method</code> signature include it. | ||
* Depending on the <code>isNamedParams</code>, the reference could be the given <code>EvaluationContext</code> | ||
* itself, or a <code>NamedParameter</code> | ||
* @param ctx | ||
* @param params | ||
* @param isNamedParams | ||
* @param m | ||
* @return | ||
*/ | ||
static Object[] addCtxParamIfRequired(EvaluationContext ctx, Object[] params, boolean isNamedParams, Method m) { | ||
logger.trace("addCtxParamIfRequired {} {} {} {}", ctx, params, isNamedParams, m); | ||
Object[] actualParams; | ||
// Here, we check if any of the parameters is an EvaluationContext | ||
boolean injectCtx = Arrays.stream(m.getParameterTypes()).anyMatch(EvaluationContext.class::isAssignableFrom); | ||
if (injectCtx) { | ||
actualParams = new Object[params.length + 1]; | ||
int j = 0; | ||
for (int i = 0; i < m.getParameterCount(); i++) { | ||
if (EvaluationContext.class.isAssignableFrom(m.getParameterTypes()[i])) { | ||
if (isNamedParams) { | ||
actualParams[i] = new NamedParameter("ctx", ctx); | ||
} else { | ||
actualParams[i] = ctx; | ||
} | ||
} else if (j < params.length) { | ||
actualParams[i] = params[j]; | ||
j++; | ||
} | ||
} | ||
} else { | ||
actualParams = params; | ||
} | ||
return actualParams; | ||
} | ||
|
||
/** | ||
* Method to retrieve the actual parameters from the given <code>NamedParameter[]</code> | ||
* It returns <code>null</code> if the actual parameters does not match with the <code>Method</code> ones | ||
* @param m | ||
* @param params | ||
* @return an <code>Object[]</code> with mapped values, or <code>null</code> if the mapping has not been possible | ||
* for all <code>params</code> | ||
*/ | ||
static Object[] calculateActualParams(Method m, NamedParameter[] params) { | ||
logger.trace("calculateActualParams {} {}", m, params); | ||
List<String> names = getParametersNames(m); | ||
Object[] actualParams = new Object[names.size()]; | ||
boolean isVariableParameters = | ||
m.getParameterCount() > 0 && m.getParameterTypes()[m.getParameterCount() - 1].isArray(); | ||
String variableParamPrefix = isVariableParameters ? names.get(names.size() - 1) : null; | ||
List<Object> variableParams = isVariableParameters ? new ArrayList<>() : null; | ||
for (NamedParameter np : params) { | ||
if (!calculateActualParam(np, names, actualParams, isVariableParameters, variableParamPrefix, | ||
variableParams)) { | ||
return null; | ||
} | ||
} | ||
if (isVariableParameters) { | ||
actualParams[actualParams.length - 1] = variableParams.toArray(); | ||
} | ||
return actualParams; | ||
} | ||
|
||
/** | ||
* Method to populate the given <code>actualParams</code> or <code>variableParams</code> with values extracted | ||
* from <code>NamedParameter</code> | ||
* @param np | ||
* @param names | ||
* @param actualParams | ||
* @param isVariableParameters | ||
* @param variableParamPrefix | ||
* @param variableParams | ||
* @return <code>true</code> if a mapping has been found, <code>false</code> otherwise | ||
*/ | ||
static boolean calculateActualParam(NamedParameter np, List<String> names, Object[] actualParams, | ||
boolean isVariableParameters, String variableParamPrefix, | ||
List<Object> variableParams) { | ||
logger.trace("calculateActualParam {} {} {} {} {} {}", np, names, actualParams, isVariableParameters, variableParamPrefix, variableParams); | ||
if (names.contains(np.getName())) { | ||
actualParams[names.indexOf(np.getName())] = np.getValue(); | ||
return true; | ||
} else if (isVariableParameters) { | ||
return calculateActualParamVariableParameters(np, variableParamPrefix, variableParams); | ||
} else { | ||
// invalid parameter, method is incompatible | ||
return false; | ||
} | ||
} | ||
|
||
/** | ||
* Method to populate the given <code>variableParams</code> with values extracted from <code>NamedParameter</code> | ||
* @param np | ||
* @param variableParamPrefix | ||
* @param variableParams | ||
* @return <code>true</code> if a mapping has been found, <code>false</code> otherwise | ||
*/ | ||
static boolean calculateActualParamVariableParameters(NamedParameter np, String variableParamPrefix, | ||
List<Object> variableParams) { | ||
logger.trace("calculateActualParamVariableParameters {} {} {}", np, variableParamPrefix, variableParams); | ||
// check if it is a variable parameters method | ||
if (np.getName().matches(variableParamPrefix + "\\d+")) { | ||
int index = Integer.parseInt(np.getName().substring(variableParamPrefix.length())) - 1; | ||
if (variableParams.size() <= index) { | ||
for (int i = variableParams.size(); i < index; i++) { | ||
// need to add nulls in case the user skipped indexes | ||
variableParams.add(null); | ||
} | ||
variableParams.add(np.getValue()); | ||
} else { | ||
variableParams.set(index, np.getValue()); | ||
} | ||
} else { | ||
// invalid parameter, method is incompatible | ||
return false; | ||
} | ||
return true; | ||
} | ||
|
||
/** | ||
* Retrieves the names of the parameters from the given <code>Method</code>, | ||
* from the ones annotated with <code>ParameterName</code> | ||
* @param m | ||
* @return | ||
*/ | ||
static List<String> getParametersNames(Method m) { | ||
logger.trace("getParametersNames {}", m); | ||
Annotation[][] pas = m.getParameterAnnotations(); | ||
List<String> toReturn = new ArrayList<>(m.getParameterCount()); | ||
for (int i = 0; i < m.getParameterCount(); i++) { | ||
for (int p = 0; p < pas[i].length; i++) { | ||
if (pas[i][p] instanceof ParameterName) { | ||
toReturn.add(((ParameterName) pas[i][p]).value()); | ||
break; | ||
} | ||
} | ||
if (toReturn.get(i) == null) { | ||
// no name found | ||
return null; | ||
} | ||
} | ||
return toReturn; | ||
} | ||
|
||
/** | ||
* Method invoked by <code>CustomFunction</code>. | ||
* It refactors the input parameters to match the order defined in the <code>CustomFunction</code>, | ||
* returning the actual value of the given <code>params</code> | ||
* @param params | ||
* @param pnames the parameters defined in the <code>CustomFunction</code> | ||
* @return | ||
*/ | ||
static Object[] rearrangeParameters(NamedParameter[] params, List<String> pnames) { | ||
logger.trace("rearrangeParameters {} {}", params, pnames); | ||
if (pnames.isEmpty()) { | ||
return params; | ||
} else { | ||
Object[] actualParams = new Object[pnames.size()]; | ||
for (int i = 0; i < actualParams.length; i++) { | ||
for (int j = 0; j < params.length; j++) { | ||
if (params[j].getName().equals(pnames.get(i))) { | ||
actualParams[i] = params[j].getValue(); | ||
break; | ||
} | ||
} | ||
} | ||
return actualParams; | ||
} | ||
} | ||
|
||
/** | ||
* Adjust CandidateMethod considering var args signature. | ||
* It converts a series of object to an array, if the last parameter type is an array. | ||
* It is needed to differentiate function(list) from function(n0...nx), e.g. | ||
* sum([1,2,3]) = 6 | ||
* sum(1,2,3) = 6 | ||
*/ | ||
static Object[] adjustForVariableParameters(Object[] actualParams, Class<?>[] parameterTypes) { | ||
logger.trace("adjustForVariableParameters {} {}", actualParams, parameterTypes); | ||
if (parameterTypes.length > 0 && parameterTypes[parameterTypes.length - 1].isArray()) { | ||
// then it is a variable parameters function call | ||
Object[] toReturn = new Object[parameterTypes.length]; | ||
if (toReturn.length > 1) { | ||
System.arraycopy(actualParams, 0, toReturn, 0, toReturn.length - 1); | ||
} | ||
Object[] remaining = new Object[actualParams.length - parameterTypes.length + 1]; | ||
toReturn[toReturn.length - 1] = remaining; | ||
System.arraycopy(actualParams, parameterTypes.length - 1, remaining, 0, remaining.length); | ||
return toReturn; | ||
} else { | ||
return actualParams; | ||
} | ||
} | ||
|
||
/** | ||
* This method apply the <code>NumberEvalHelper.coerceNumber</code> to the given result or, | ||
* if it is an array, recursively to all its elements | ||
* @param result | ||
* @return | ||
*/ | ||
static Object normalizeResult(Object result) { | ||
logger.trace("normalizeResult {}", result); | ||
// this is to normalize types returned by external functions | ||
if (result != null && result.getClass().isArray()) { | ||
List<Object> objs = new ArrayList<>(); | ||
for (int i = 0; i < Array.getLength(result); i++) { | ||
objs.add(NumberEvalHelper.coerceNumber(Array.get(result, i))); | ||
} | ||
return objs; | ||
} else { | ||
return NumberEvalHelper.coerceNumber(result); | ||
} | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think as far as I understand it, this is by the specification. Please see section 10.3.1.2 Grammar rules, Rule 39 in the specification. The "parameters" are either "named parameters" or "positional parameters".