use of com.github.javaparser.ast.expr.Expression in project drools by kiegroup.
the class ExpressionTyper method toTypedExpressionRec.
private Optional<TypedExpression> toTypedExpressionRec(Expression drlxExpr) {
Class<?> typeCursor = patternType;
if (drlxExpr instanceof FullyQualifiedInlineCastExpr) {
return toTypedExpressionRec(transformFullyQualifiedInlineCastExpr(ruleContext.getTypeResolver(), (FullyQualifiedInlineCastExpr) drlxExpr));
}
if (drlxExpr instanceof EnclosedExpr) {
Expression inner = ((EnclosedExpr) drlxExpr).getInner();
Optional<TypedExpression> typedExpression = toTypedExpressionRec(inner);
return typedExpression.map(t -> t.cloneWithNewExpression(new EnclosedExpr(t.getExpression())));
}
if (drlxExpr instanceof MethodCallExpr) {
MethodCallExpr methodExpr = (MethodCallExpr) drlxExpr;
Expression expr = methodExpr;
if (isEval(methodExpr.getNameAsString(), methodExpr.getScope(), methodExpr.getArguments())) {
expr = methodExpr.getArgument(0);
}
drlxExpr = expr;
}
if (drlxExpr instanceof NullSafeMethodCallExpr) {
NullSafeMethodCallExpr methodExpr = (NullSafeMethodCallExpr) drlxExpr;
Expression expr = methodExpr;
if (isEval(methodExpr.getNameAsString(), methodExpr.getScope(), methodExpr.getArguments())) {
expr = methodExpr.getArgument(0);
}
drlxExpr = expr;
}
if (drlxExpr instanceof UnaryExpr) {
UnaryExpr unaryExpr = (UnaryExpr) drlxExpr;
Optional<TypedExpression> optTypedExpr = toTypedExpressionRec(unaryExpr.getExpression());
return optTypedExpr.map(typedExpr -> new TypedExpression(new UnaryExpr(typedExpr.getExpression(), unaryExpr.getOperator()), typedExpr.getType()));
}
if (drlxExpr instanceof BinaryExpr) {
BinaryExpr binaryExpr = (BinaryExpr) drlxExpr;
BinaryExpr.Operator operator = binaryExpr.getOperator();
Optional<TypedExpression> optLeft = toTypedExpressionRec(binaryExpr.getLeft());
Optional<TypedExpression> optRight = toTypedExpressionRec(binaryExpr.getRight());
return optLeft.flatMap(left -> optRight.flatMap(right -> {
final BinaryExpr combo = new BinaryExpr(left.getExpression(), right.getExpression(), operator);
return of(new TypedExpression(combo, left.getType()));
}));
}
if (drlxExpr instanceof HalfBinaryExpr) {
final Expression binaryExpr = trasformHalfBinaryToBinary(drlxExpr);
if (binaryExpr instanceof BinaryExpr && ((BinaryExpr) binaryExpr).getLeft() == drlxExpr) {
throw new CannotTypeExpressionException("left leaf is the same : drlxExpr = " + drlxExpr + ", originalExpression = " + context.getOriginalExpression());
}
return toTypedExpressionRec(binaryExpr);
}
if (drlxExpr instanceof LiteralExpr) {
drlxExpr = normalizeDigit(drlxExpr);
return of(new TypedExpression(drlxExpr, getLiteralExpressionType((LiteralExpr) drlxExpr)));
}
if (drlxExpr instanceof ThisExpr || (drlxExpr instanceof NameExpr && THIS_PLACEHOLDER.equals(printNode(drlxExpr)))) {
return of(new TypedExpression(new NameExpr(THIS_PLACEHOLDER), patternType));
}
if (drlxExpr instanceof CastExpr) {
CastExpr castExpr = (CastExpr) drlxExpr;
Optional<TypedExpression> optTypedExpr = toTypedExpressionRec(castExpr.getExpression());
return optTypedExpr.map(typedExpr -> new TypedExpression(new CastExpr(castExpr.getType(), typedExpr.getExpression()), getClassFromContext(ruleContext.getTypeResolver(), castExpr.getType().asString())));
}
if (drlxExpr instanceof NameExpr) {
return nameExpr(((NameExpr) drlxExpr).getNameAsString(), typeCursor);
}
if (drlxExpr instanceof FieldAccessExpr || drlxExpr instanceof MethodCallExpr || drlxExpr instanceof ObjectCreationExpr || drlxExpr instanceof NullSafeFieldAccessExpr || drlxExpr instanceof NullSafeMethodCallExpr || drlxExpr instanceof MapCreationLiteralExpression || drlxExpr instanceof ListCreationLiteralExpression) {
return toTypedExpressionFromMethodCallOrField(drlxExpr).getTypedExpression();
}
if (drlxExpr instanceof PointFreeExpr) {
final PointFreeExpr pointFreeExpr = (PointFreeExpr) drlxExpr;
Optional<TypedExpression> optLeft = toTypedExpressionRec(pointFreeExpr.getLeft());
Optional<TypedExpression> optRight = pointFreeExpr.getRight().size() == 1 ? toTypedExpressionRec(pointFreeExpr.getRight().get(0)) : Optional.empty();
OperatorSpec opSpec = getOperatorSpec(pointFreeExpr.getRight(), pointFreeExpr.getOperator());
return optLeft.map(left -> new TypedExpression(opSpec.getExpression(ruleContext, pointFreeExpr, left, this), left.getType()).setStatic(opSpec.isStatic()).setLeft(left).setRight(optRight.orElse(null)));
}
if (drlxExpr instanceof HalfPointFreeExpr) {
final HalfPointFreeExpr halfPointFreeExpr = (HalfPointFreeExpr) drlxExpr;
Expression parentLeft = findLeftLeafOfNameExprTraversingParent(halfPointFreeExpr);
if (parentLeft == halfPointFreeExpr) {
throw new CannotTypeExpressionException("left leaf is the same : halfPointFreeExpr = " + halfPointFreeExpr + ", originalExpression = " + context.getOriginalExpression());
}
Optional<TypedExpression> optLeft = toTypedExpressionRec(parentLeft);
OperatorSpec opSpec = getOperatorSpec(halfPointFreeExpr.getRight(), halfPointFreeExpr.getOperator());
final PointFreeExpr transformedToPointFree = new PointFreeExpr(halfPointFreeExpr.getTokenRange().orElseThrow(() -> new IllegalStateException("Token range is not present!")), parentLeft, halfPointFreeExpr.getRight(), halfPointFreeExpr.getOperator(), halfPointFreeExpr.isNegated(), halfPointFreeExpr.getArg1(), halfPointFreeExpr.getArg2(), halfPointFreeExpr.getArg3(), halfPointFreeExpr.getArg4());
return optLeft.map(left -> new TypedExpression(opSpec.getExpression(ruleContext, transformedToPointFree, left, this), left.getType()).setStatic(opSpec.isStatic()).setLeft(left));
}
if (drlxExpr instanceof ArrayAccessExpr) {
final ArrayAccessExpr arrayAccessExpr = (ArrayAccessExpr) drlxExpr;
if (Map.class.isAssignableFrom(typeCursor)) {
return createMapAccessExpression(arrayAccessExpr.getIndex(), arrayAccessExpr.getName() instanceof ThisExpr ? new NameExpr(THIS_PLACEHOLDER) : arrayAccessExpr.getName(), Map.class);
} else if (arrayAccessExpr.getName() instanceof FieldAccessExpr) {
Optional<TypedExpression> typedExpression = toTypedExpressionFromMethodCallOrField(drlxExpr).getTypedExpression();
typedExpression.ifPresent(te -> {
final Expression originalExpression = te.getExpression();
DrlxParseUtil.removeRootNode(originalExpression);
});
return typedExpression;
} else {
String name = printNode(drlxExpr.asArrayAccessExpr().getName());
final Optional<TypedExpression> nameExpr = nameExpr(name, typeCursor);
Expression indexExpr = toTypedExpressionFromMethodCallOrField(arrayAccessExpr.getIndex()).getTypedExpression().orElseThrow(() -> new NoSuchElementException("TypedExpressionResult doesn't contain TypedExpression!")).getExpression();
return nameExpr.flatMap(te -> transformToArrayOrMapExpressionWithType(indexExpr, te));
}
}
if (drlxExpr instanceof InstanceOfExpr) {
InstanceOfExpr instanceOfExpr = (InstanceOfExpr) drlxExpr;
ruleContext.addInlineCastType(printNode(instanceOfExpr.getExpression()), instanceOfExpr.getType());
return toTypedExpressionRec(instanceOfExpr.getExpression()).map(e -> new TypedExpression(new InstanceOfExpr(e.getExpression(), instanceOfExpr.getType()), boolean.class));
}
if (drlxExpr instanceof ClassExpr) {
return of(new TypedExpression(drlxExpr, Class.class));
}
if (drlxExpr instanceof InlineCastExpr) {
return toTypedExpressionFromMethodCallOrField(drlxExpr).getTypedExpression();
}
if (drlxExpr instanceof OOPathExpr) {
Class<?> type = patternType;
for (OOPathChunk chunk : ((OOPathExpr) drlxExpr).getChunks()) {
final String fieldName = chunk.getField().toString();
final TypedExpression callExpr = DrlxParseUtil.nameExprToMethodCallExpr(fieldName, type, null, ruleContext);
if (callExpr == null) {
return empty();
}
Class<?> fieldType = (chunk.getInlineCast() != null) ? DrlxParseUtil.getClassFromContext(ruleContext.getTypeResolver(), chunk.getInlineCast().toString()) : callExpr.getRawClass();
if (!chunk.isSingleValue() && Iterable.class.isAssignableFrom(fieldType) || isDataSource(fieldType)) {
type = extractGenericType(type, ((MethodCallExpr) callExpr.getExpression()).getName().toString());
} else {
type = fieldType;
}
}
return of(new TypedExpression(drlxExpr, type));
}
if (drlxExpr.isAssignExpr()) {
AssignExpr assignExpr = drlxExpr.asAssignExpr();
final Expression rightSide = assignExpr.getValue();
return toTypedExpressionRec(rightSide).map(e -> {
final AssignExpr newExpression = new AssignExpr(assignExpr.getTarget(), e.getExpression(), assignExpr.getOperator());
return new TypedExpression(newExpression, e.getType());
});
}
throw new UnsupportedOperationException();
}
use of com.github.javaparser.ast.expr.Expression in project drools by kiegroup.
the class AccumulateVisitor method buildConstraintExpression.
protected Expression buildConstraintExpression(Expression expr, Collection<String> usedDeclarations) {
LambdaExpr lambdaExpr = new LambdaExpr();
lambdaExpr.setEnclosingParameters(true);
usedDeclarations.stream().map(s -> new Parameter(context.getDelarationType(s), s)).forEach(lambdaExpr::addParameter);
lambdaExpr.setBody(new ExpressionStmt(expr));
return lambdaExpr;
}
use of com.github.javaparser.ast.expr.Expression in project drools by kiegroup.
the class PatternDSL method addNullSafeExpr.
private void addNullSafeExpr(ConstraintParser constraintParser, String patternIdentifier, List<PatternConstraintParseResult> patternConstraintParseResults) {
final List<Expression> nullSafeExpressions = patternConstraintParseResults.stream().flatMap(r -> r.getDrlxParseResult().acceptWithReturnValue(new ParseResultVisitor<List<Expression>>() {
@Override
public List<Expression> onSuccess(DrlxParseSuccess t) {
return t.getNullSafeExpressions();
}
@Override
public List<Expression> onFail(DrlxParseFail failure) {
return Collections.emptyList();
}
}).stream()).collect(Collectors.toList());
List<Expression> newNullSafeExpressions = reverseDistinct(nullSafeExpressions);
newNullSafeExpressions.forEach(expr -> {
String nullSafeExpression = printNode(expr);
DrlxParseResult nullSafeExpressionParsed = constraintParser.drlxParse(patternType, patternIdentifier, nullSafeExpression, false);
patternConstraintParseResults.add(0, new PatternConstraintParseResult(nullSafeExpression, patternIdentifier, nullSafeExpressionParsed));
});
}
use of com.github.javaparser.ast.expr.Expression in project drools by kiegroup.
the class AccumulateVisitor method replaceBindingWithPatternBinding.
private MethodCallExpr replaceBindingWithPatternBinding(MethodCallExpr bindExpression, MethodCallExpr lastPattern) {
// This method links a binding expression, used to evaluate the accumulated value,
// to the last pattern in a multi-pattern accumulate like the following
//
// accumulate( $c : Child( age < 10 ) and $a : Adult( name == $c.parent ) and $s : String( this == $a.name ),
// $sum : sum($a.getAge() + $c.getAge() + $s.length()) )
//
// In the case the bindExpression, that will have to be linked to the $s pattern, is originally generated as
//
// bind(var_$sum, var_$a, var_$c, var_$s, (Adult $a, Child $c, String $s) -> $a.getAge() + $c.getAge() + $s.length())
final Expression bindingId = lastPattern.getArgument(0);
bindExpression.findFirst(NameExpr.class, e -> e.equals(bindingId)).ifPresent(name -> {
// since the bind has to be linked to $s, the corresponding variable should be removed from the arguments list so it becomes
// bind(var_$sum, var_$a, var_$c, (Adult $a, Child $c, String $s) -> $a.getAge() + $c.getAge() + $s.length())
bindExpression.remove(name);
// also the first formal parameter in the binding lambda has to be $s so it becomes
// bind(var_$sum, var_$a, var_$c, (String $s, Adult $a, Child $c) -> $a.getAge() + $c.getAge() + $s.length())
LambdaExpr lambda = (LambdaExpr) bindExpression.getArgument(bindExpression.getArguments().size() - 1);
if (lambda.getParameters().size() > 1) {
String formalArg = context.fromVar(name.getNameAsString());
for (Parameter param : lambda.getParameters()) {
if (param.getNameAsString().equals(formalArg)) {
lambda.getParameters().remove(param);
lambda.getParameters().add(0, param);
break;
}
}
}
});
return bindExpression;
}
use of com.github.javaparser.ast.expr.Expression in project drools by kiegroup.
the class AccumulateVisitor method binaryExprParameter.
private Optional<NewBinding> binaryExprParameter(PatternDescr basePattern, AccumulateDescr.AccumulateFunctionCallDescr function, MethodCallExpr functionDSL, String bindingId, String accumulateFunctionParameterStr) {
final DrlxParseResult parseResult = ConstraintParser.defaultConstraintParser(context, packageModel).drlxParse(Object.class, bindingId, accumulateFunctionParameterStr);
Optional<NewBinding> optNewBinding = parseResult.acceptWithReturnValue(new ParseResultVisitor<Optional<NewBinding>>() {
@Override
public Optional<NewBinding> onSuccess(DrlxParseSuccess drlxParseResult) {
SingleDrlxParseSuccess singleResult = (SingleDrlxParseSuccess) drlxParseResult;
Class<?> exprRawClass = singleResult.getExprRawClass();
AccumulateFunction accumulateFunction = getAccumulateFunction(function, exprRawClass);
validateAccFunctionTypeAgainstPatternType(context, basePattern, accumulateFunction);
final String bindExpressionVariable = context.getExprId(accumulateFunction.getResultType(), singleResult.getLeft().toString());
singleResult.setExprBinding(bindExpressionVariable);
context.addDeclarationReplacing(new DeclarationSpec(singleResult.getPatternBinding(), exprRawClass));
context.getExpressions().forEach(expression -> replaceTypeInExprLambda(bindingId, exprRawClass, expression));
functionDSL.addArgument(createAccSupplierExpr(accumulateFunction));
final MethodCallExpr newBindingFromBinary = AccumulateVisitor.this.buildBinding(bindExpressionVariable, singleResult.getUsedDeclarations(), singleResult.getExpr());
context.addDeclarationReplacing(new DeclarationSpec(bindExpressionVariable, exprRawClass));
functionDSL.addArgument(context.getVarExpr(bindExpressionVariable));
return Optional.of(new NewBinding(Collections.emptyList(), newBindingFromBinary));
}
@Override
public Optional<NewBinding> onFail(DrlxParseFail failure) {
return Optional.empty();
}
});
return optNewBinding;
}
Aggregations