use of com.github.javaparser.ast.expr.ThisExpr in project javaparser by javaparser.
the class GenericsResolutionTest method typeParamOnReturnTypeStep1.
@Test
public void typeParamOnReturnTypeStep1() {
CompilationUnit cu = parseSample("TypeParamOnReturnType");
ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "TypeParamOnReturnType");
MethodDeclaration method = Navigator.demandMethod(clazz, "nodeEquals");
ThisExpr thisExpr = Navigator.findNodeOfGivenClass(method, ThisExpr.class);
ResolvedType type = JavaParserFacade.get(new ReflectionTypeSolver()).getType(thisExpr);
assertEquals(false, type.isTypeVariable());
assertEquals("TypeParamOnReturnType", type.describe());
}
use of com.github.javaparser.ast.expr.ThisExpr in project drools by kiegroup.
the class KiePMMLModelFactoryUtils method init.
/**
* Initialize the given <code>ClassOrInterfaceDeclaration</code> with all the <b>common</b> code needed to
* generate a <code>KiePMMLModel</code>
* @param compilationDTO
* @param modelTemplate
*/
public static void init(final CompilationDTO<? extends Model> compilationDTO, final ClassOrInterfaceDeclaration modelTemplate) {
final ConstructorDeclaration constructorDeclaration = modelTemplate.getDefaultConstructor().orElseThrow(() -> new KiePMMLInternalException(String.format(MISSING_DEFAULT_CONSTRUCTOR, modelTemplate.getName())));
final String name = compilationDTO.getModelName();
final String generatedClassName = compilationDTO.getSimpleClassName();
final List<MiningField> miningFields = compilationDTO.getKieMiningFields();
final List<OutputField> outputFields = compilationDTO.getKieOutputFields();
final List<TargetField> targetFields = compilationDTO.getKieTargetFields();
final Expression miningFunctionExpression;
if (compilationDTO.getMINING_FUNCTION() != null) {
MINING_FUNCTION miningFunction = compilationDTO.getMINING_FUNCTION();
miningFunctionExpression = new NameExpr(miningFunction.getClass().getName() + "." + miningFunction.name());
} else {
miningFunctionExpression = new NullLiteralExpr();
}
final PMML_MODEL pmmlModelEnum = compilationDTO.getPMML_MODEL();
final NameExpr pmmlMODELExpression = new NameExpr(pmmlModelEnum.getClass().getName() + "." + pmmlModelEnum.name());
String targetFieldName = compilationDTO.getTargetFieldName();
final Expression targetFieldExpression;
if (targetFieldName != null) {
targetFieldExpression = new StringLiteralExpr(targetFieldName);
} else {
targetFieldExpression = new NullLiteralExpr();
}
setKiePMMLModelConstructor(generatedClassName, constructorDeclaration, name, miningFields, outputFields, targetFields);
addTransformationsInClassOrInterfaceDeclaration(modelTemplate, compilationDTO.getTransformationDictionary(), compilationDTO.getLocalTransformations());
final BlockStmt body = constructorDeclaration.getBody();
CommonCodegenUtils.setAssignExpressionValue(body, "pmmlMODEL", pmmlMODELExpression);
CommonCodegenUtils.setAssignExpressionValue(body, "miningFunction", miningFunctionExpression);
CommonCodegenUtils.setAssignExpressionValue(body, "targetField", targetFieldExpression);
addGetCreatedKiePMMLMiningFieldsMethod(modelTemplate, compilationDTO.getMiningSchema().getMiningFields(), compilationDTO.getFields());
MethodCallExpr getCreatedKiePMMLMiningFieldsExpr = new MethodCallExpr();
getCreatedKiePMMLMiningFieldsExpr.setScope(new ThisExpr());
getCreatedKiePMMLMiningFieldsExpr.setName(GET_CREATED_KIEPMMLMININGFIELDS);
CommonCodegenUtils.setAssignExpressionValue(body, "kiePMMLMiningFields", getCreatedKiePMMLMiningFieldsExpr);
if (compilationDTO.getOutput() != null) {
addGetCreatedKiePMMLOutputFieldsMethod(modelTemplate, compilationDTO.getOutput().getOutputFields());
MethodCallExpr getCreatedKiePMMLOutputFieldsExpr = new MethodCallExpr();
getCreatedKiePMMLOutputFieldsExpr.setScope(new ThisExpr());
getCreatedKiePMMLOutputFieldsExpr.setName(GET_CREATED_KIEPMMLOUTPUTFIELDS);
CommonCodegenUtils.setAssignExpressionValue(body, "kiePMMLOutputFields", getCreatedKiePMMLOutputFieldsExpr);
}
}
use of com.github.javaparser.ast.expr.ThisExpr in project drools by kiegroup.
the class CommonCodegenUtilsTest method addMapPopulation.
@Test
public void addMapPopulation() {
final Map<String, MethodDeclaration> toAdd = IntStream.range(0, 5).boxed().collect(Collectors.toMap(index -> "KEY_" + index, index -> getMethodDeclaration("METHOD_" + index)));
BlockStmt body = new BlockStmt();
String mapName = "MAP_NAME";
CommonCodegenUtils.addMapPopulation(toAdd, body, mapName);
NodeList<Statement> statements = body.getStatements();
assertEquals(toAdd.size(), statements.size());
for (Statement statement : statements) {
assertTrue(statement instanceof ExpressionStmt);
ExpressionStmt expressionStmt = (ExpressionStmt) statement;
com.github.javaparser.ast.expr.Expression expression = expressionStmt.getExpression();
assertTrue(expression instanceof MethodCallExpr);
MethodCallExpr methodCallExpr = (MethodCallExpr) expression;
final NodeList<com.github.javaparser.ast.expr.Expression> arguments = methodCallExpr.getArguments();
assertEquals(2, arguments.size());
assertTrue(arguments.get(0) instanceof StringLiteralExpr);
assertTrue(arguments.get(1) instanceof MethodReferenceExpr);
MethodReferenceExpr methodReferenceExpr = (MethodReferenceExpr) arguments.get(1);
assertTrue(methodReferenceExpr.getScope() instanceof ThisExpr);
final com.github.javaparser.ast.expr.Expression scope = methodCallExpr.getScope().orElse(null);
assertNotNull(scope);
assertTrue(scope instanceof NameExpr);
assertEquals(mapName, ((NameExpr) scope).getNameAsString());
}
for (Map.Entry<String, MethodDeclaration> entry : toAdd.entrySet()) {
int matchingDeclarations = (int) statements.stream().filter(statement -> {
ExpressionStmt expressionStmt = (ExpressionStmt) statement;
com.github.javaparser.ast.expr.Expression expression = expressionStmt.getExpression();
MethodCallExpr methodCallExpr = (MethodCallExpr) expression;
final NodeList<com.github.javaparser.ast.expr.Expression> arguments = methodCallExpr.getArguments();
if (!entry.getKey().equals(((StringLiteralExpr) arguments.get(0)).getValue())) {
return false;
}
MethodReferenceExpr methodReferenceExpr = (MethodReferenceExpr) arguments.get(1);
return entry.getValue().getName().asString().equals(methodReferenceExpr.getIdentifier());
}).count();
assertEquals(1, matchingDeclarations);
}
}
use of com.github.javaparser.ast.expr.ThisExpr in project drools by kiegroup.
the class ConstraintParser method parseFunctionInEval.
private DrlxParseResult parseFunctionInEval(MethodCallExpr methodCallExpr, Class<?> patternType, String bindingId, boolean isPositional, Optional<MethodDeclaration> functionCall) {
// when the methodCallExpr will be placed in the model/DSL, any parameter being a "this" need to be implemented as _this by convention.
List<ThisExpr> rewriteThisExprs = recurseCollectArguments(methodCallExpr).stream().filter(ThisExpr.class::isInstance).map(ThisExpr.class::cast).collect(Collectors.toList());
for (ThisExpr t : rewriteThisExprs) {
methodCallExpr.replace(t, new NameExpr(THIS_PLACEHOLDER));
}
if (functionCall.isPresent()) {
Class<?> returnType = DrlxParseUtil.getClassFromContext(context.getTypeResolver(), functionCall.get().getType().asString());
NodeList<Expression> arguments = methodCallExpr.getArguments();
List<String> usedDeclarations = new ArrayList<>();
for (Expression arg : arguments) {
String argString = printNode(arg);
if (arg instanceof DrlNameExpr && !argString.equals(THIS_PLACEHOLDER)) {
usedDeclarations.add(argString);
} else if (arg instanceof CastExpr) {
String s = printNode(((CastExpr) arg).getExpression());
usedDeclarations.add(s);
} else if (arg instanceof MethodCallExpr) {
TypedExpressionResult typedExpressionResult = new ExpressionTyper(context, null, bindingId, isPositional).toTypedExpression(arg);
usedDeclarations.addAll(typedExpressionResult.getUsedDeclarations());
}
}
return new SingleDrlxParseSuccess(patternType, bindingId, methodCallExpr, returnType).setUsedDeclarations(usedDeclarations).setIsPredicate(isBooleanBoxedUnboxed(returnType));
} else {
throw new IllegalArgumentException("Specified function call is not present!");
}
}
use of com.github.javaparser.ast.expr.ThisExpr 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();
}
Aggregations