use of org.codehaus.groovy.ast.expr.MethodPointerExpression in project groovy by apache.
the class StaticTypeCheckingVisitor method convertClosureTypeToSAMType.
/**
* Converts a Closure type to the appropriate SAM type, which can be used to
* infer return type generics.
*
* @param expression the argument expression
* @param closureType the inferred type of {@code expression}
* @param samType the target type for the argument expression
* @return SAM type augmented using information from the argument expression
*/
private static ClassNode convertClosureTypeToSAMType(final Expression expression, final ClassNode closureType, final MethodNode sam, final ClassNode samType) {
Map<GenericsTypeName, GenericsType> samTypeConnections = GenericsUtils.extractPlaceholders(samType);
samTypeConnections.replaceAll((// GROOVY-9762, GROOVY-9803: reduce "? super T" to "T"
xx, // GROOVY-9762, GROOVY-9803: reduce "? super T" to "T"
gt) -> Optional.ofNullable(gt.getLowerBound()).map(GenericsType::new).orElse(gt));
ClassNode closureReturnType = closureType.getGenericsTypes()[0].getType();
Parameter[] parameters = sam.getParameters();
if (parameters.length > 0 && expression instanceof MethodPointerExpression && GenericsUtils.hasUnresolvedGenerics(closureReturnType)) {
// try to resolve referenced method type parameters in return type
MethodPointerExpression mp = (MethodPointerExpression) expression;
List<MethodNode> candidates = mp.getNodeMetaData(MethodNode.class);
if (candidates != null && !candidates.isEmpty()) {
ClassNode[] paramTypes = applyGenericsContext(samTypeConnections, extractTypesFromParameters(parameters));
ClassNode[] matchTypes = candidates.stream().map(candidate -> collateMethodReferenceParameterTypes(mp, candidate)).filter(candidate -> checkSignatureSuitability(candidate, paramTypes)).findFirst().orElse(// TODO: order signatures by param distance
null);
if (matchTypes != null) {
Map<GenericsTypeName, GenericsType> connections = new HashMap<>();
for (int i = 0, n = parameters.length; i < n; i += 1) {
// SAM parameters should align with the referenced method's parameters
extractGenericsConnections(connections, paramTypes[i], matchTypes[i]);
}
// convert the method reference's generics into the SAM's generics domain
closureReturnType = applyGenericsContext(connections, closureReturnType);
// apply known generics connections to the SAM's placeholders in the return type
closureReturnType = applyGenericsContext(samTypeConnections, closureReturnType);
}
}
}
// the SAM's return type exactly corresponds to the inferred closure return type
extractGenericsConnections(samTypeConnections, closureReturnType, sam.getReturnType());
// repeat the same for each parameter given in the ClosureExpression
if (parameters.length > 0 && expression instanceof ClosureExpression) {
// TODO
return closureType;
}
return applyGenericsContext(samTypeConnections, samType.redirect());
}
use of org.codehaus.groovy.ast.expr.MethodPointerExpression in project groovy by apache.
the class StaticTypeCheckingVisitor method visitMethodPointerExpression.
@Override
public void visitMethodPointerExpression(final MethodPointerExpression expression) {
super.visitMethodPointerExpression(expression);
Expression nameExpr = expression.getMethodName();
if (nameExpr instanceof ConstantExpression && isStringType(getType(nameExpr))) {
String nameText = nameExpr.getText();
if ("new".equals(nameText)) {
ClassNode receiverType = getType(expression.getExpression());
if (isClassClassNodeWrappingConcreteType(receiverType)) {
storeType(expression, wrapClosureType(receiverType));
}
return;
}
List<Receiver<String>> receivers = new ArrayList<>();
addReceivers(receivers, makeOwnerList(expression.getExpression()), false);
ClassNode receiverType = null;
List<MethodNode> candidates = EMPTY_METHODNODE_LIST;
for (Receiver<String> currentReceiver : receivers) {
receiverType = wrapTypeIfNecessary(currentReceiver.getType());
candidates = findMethodsWithGenerated(receiverType, nameText);
if (isBeingCompiled(receiverType))
candidates.addAll(GROOVY_OBJECT_TYPE.getMethods(nameText));
candidates.addAll(findDGMMethodsForClassNode(getSourceUnit().getClassLoader(), receiverType, nameText));
candidates = filterMethodsByVisibility(candidates, typeCheckingContext.getEnclosingClassNode());
if (!candidates.isEmpty()) {
break;
}
}
if (candidates.isEmpty()) {
candidates = extension.handleMissingMethod(getType(expression.getExpression()), nameText, null, null, null);
} else if (candidates.size() > 1) {
candidates = extension.handleAmbiguousMethods(candidates, expression);
}
if (!candidates.isEmpty()) {
Map<GenericsTypeName, GenericsType> gts = GenericsUtils.extractPlaceholders(receiverType);
candidates.stream().map(candidate -> applyGenericsContext(gts, candidate.getReturnType())).reduce(WideningCategories::lowestUpperBound).ifPresent(returnType -> {
storeType(expression, wrapClosureType(returnType));
});
expression.putNodeMetaData(MethodNode.class, candidates);
} else if (!(expression instanceof MethodReferenceExpression)) {
ClassNode type = wrapTypeIfNecessary(getType(expression.getExpression()));
if (isClassClassNodeWrappingConcreteType(type))
type = type.getGenericsTypes()[0].getType();
addStaticTypeError("Cannot find matching method " + prettyPrintTypeName(type) + "#" + nameText + ". Please check if the declared type is correct and if the method exists.", nameExpr);
}
}
}
use of org.codehaus.groovy.ast.expr.MethodPointerExpression in project groovy by apache.
the class AstBuilder method visitPathElement.
@Override
public Expression visitPathElement(final PathElementContext ctx) {
Expression baseExpr = ctx.getNodeMetaData(PATH_EXPRESSION_BASE_EXPR);
Objects.requireNonNull(baseExpr, "baseExpr is required!");
if (asBoolean(ctx.namePart())) {
Expression namePartExpr = this.visitNamePart(ctx.namePart());
GenericsType[] genericsTypes = this.visitNonWildcardTypeArguments(ctx.nonWildcardTypeArguments());
if (asBoolean(ctx.DOT())) {
boolean isSafeChain = this.isTrue(baseExpr, PATH_EXPRESSION_BASE_EXPR_SAFE_CHAIN);
return this.createDotExpression(ctx, baseExpr, namePartExpr, genericsTypes, isSafeChain);
} else if (asBoolean(ctx.SAFE_DOT())) {
return this.createDotExpression(ctx, baseExpr, namePartExpr, genericsTypes, true);
} else if (asBoolean(ctx.SAFE_CHAIN_DOT())) {
// e.g. obj??.a OR obj??.@a
Expression expression = createDotExpression(ctx, baseExpr, namePartExpr, genericsTypes, true);
expression.putNodeMetaData(PATH_EXPRESSION_BASE_EXPR_SAFE_CHAIN, true);
return expression;
} else if (asBoolean(ctx.METHOD_POINTER())) {
// e.g. obj.&m
return configureAST(new MethodPointerExpression(baseExpr, namePartExpr), ctx);
} else if (asBoolean(ctx.METHOD_REFERENCE())) {
// e.g. obj::m
return configureAST(new MethodReferenceExpression(baseExpr, namePartExpr), ctx);
} else if (asBoolean(ctx.SPREAD_DOT())) {
if (asBoolean(ctx.AT())) {
// e.g. obj*.@a
AttributeExpression attributeExpression = new AttributeExpression(baseExpr, namePartExpr, true);
attributeExpression.setSpreadSafe(true);
return configureAST(attributeExpression, ctx);
} else {
// e.g. obj*.p
PropertyExpression propertyExpression = new PropertyExpression(baseExpr, namePartExpr, true);
propertyExpression.putNodeMetaData(PATH_EXPRESSION_BASE_EXPR_GENERICS_TYPES, genericsTypes);
propertyExpression.setSpreadSafe(true);
return configureAST(propertyExpression, ctx);
}
}
} else if (asBoolean(ctx.creator())) {
CreatorContext creatorContext = ctx.creator();
creatorContext.putNodeMetaData(ENCLOSING_INSTANCE_EXPRESSION, baseExpr);
return configureAST(this.visitCreator(creatorContext), ctx);
} else if (asBoolean(ctx.indexPropertyArgs())) {
// e.g. list[1, 3, 5]
Tuple2<Token, Expression> tuple = this.visitIndexPropertyArgs(ctx.indexPropertyArgs());
boolean isSafeChain = this.isTrue(baseExpr, PATH_EXPRESSION_BASE_EXPR_SAFE_CHAIN);
return configureAST(new BinaryExpression(baseExpr, createGroovyToken(tuple.getV1()), tuple.getV2(), isSafeChain || asBoolean(ctx.indexPropertyArgs().SAFE_INDEX())), ctx);
} else if (asBoolean(ctx.namedPropertyArgs())) {
// this is a special way to signify a cast, e.g. Person[name: 'Daniel.Sun', location: 'Shanghai']
List<MapEntryExpression> mapEntryExpressionList = this.visitNamedPropertyArgs(ctx.namedPropertyArgs());
Expression right;
Expression firstKeyExpression;
int mapEntryExpressionListSize = mapEntryExpressionList.size();
if (mapEntryExpressionListSize == 0) {
// expecting list of MapEntryExpressions later so use SpreadMap to smuggle empty MapExpression to later stages
right = configureAST(new SpreadMapExpression(configureAST(new MapExpression(), ctx.namedPropertyArgs())), ctx.namedPropertyArgs());
} else if (mapEntryExpressionListSize == 1 && (firstKeyExpression = mapEntryExpressionList.get(0).getKeyExpression()) instanceof SpreadMapExpression) {
right = firstKeyExpression;
} else {
ListExpression listExpression = configureAST(new ListExpression(mapEntryExpressionList.stream().map(e -> {
if (e.getKeyExpression() instanceof SpreadMapExpression) {
return e.getKeyExpression();
}
return e;
}).collect(Collectors.toList())), ctx.namedPropertyArgs());
listExpression.setWrapped(true);
right = listExpression;
}
NamedPropertyArgsContext namedPropertyArgsContext = ctx.namedPropertyArgs();
Token token = (namedPropertyArgsContext.LBRACK() == null ? namedPropertyArgsContext.SAFE_INDEX() : namedPropertyArgsContext.LBRACK()).getSymbol();
return configureAST(new BinaryExpression(baseExpr, createGroovyToken(token), right), ctx);
} else if (asBoolean(ctx.arguments())) {
Expression argumentsExpr = this.visitArguments(ctx.arguments());
configureAST(argumentsExpr, ctx);
if (isInsideParentheses(baseExpr)) {
// e.g. (obj.x)(), (obj.@x)()
return configureAST(createCallMethodCallExpression(baseExpr, argumentsExpr), ctx);
}
if (baseExpr instanceof AttributeExpression) {
// e.g. obj.@a(1, 2)
AttributeExpression attributeExpression = (AttributeExpression) baseExpr;
// whether attributeExpression is spread safe or not, we must reset it as false
attributeExpression.setSpreadSafe(false);
return configureAST(createCallMethodCallExpression(attributeExpression, argumentsExpr, true), ctx);
}
if (baseExpr instanceof PropertyExpression) {
// e.g. obj.a(1, 2)
MethodCallExpression methodCallExpression = this.createMethodCallExpression((PropertyExpression) baseExpr, argumentsExpr);
return configureAST(methodCallExpression, ctx);
}
if (baseExpr instanceof VariableExpression) {
// void and primitive type AST node must be an instance of VariableExpression
String baseExprText = baseExpr.getText();
if (VOID_STR.equals(baseExprText)) {
// e.g. void()
return configureAST(this.createCallMethodCallExpression(this.createConstantExpression(baseExpr), argumentsExpr), ctx);
} else if (isPrimitiveType(baseExprText)) {
// e.g. int(), long(), float(), etc.
throw this.createParsingFailedException("Primitive type literal: " + baseExprText + " cannot be used as a method name", ctx);
}
}
if (// e.g. m()
baseExpr instanceof VariableExpression || // e.g. "$m"()
baseExpr instanceof GStringExpression || (baseExpr instanceof ConstantExpression && this.isTrue(baseExpr, IS_STRING))) {
// e.g. "m"()
String baseExprText = baseExpr.getText();
if (THIS_STR.equals(baseExprText) || SUPER_STR.equals(baseExprText)) {
// @MapConstructor(pre={ super(args?.first, args?.last); args = args ?: [:] }, post = { first = first?.toUpperCase() })
if (visitingClosureCount > 0) {
return configureAST(new MethodCallExpression(baseExpr, baseExprText, argumentsExpr), ctx);
}
return configureAST(new ConstructorCallExpression(SUPER_STR.equals(baseExprText) ? ClassNode.SUPER : ClassNode.THIS, argumentsExpr), ctx);
}
MethodCallExpression methodCallExpression = this.createMethodCallExpression(baseExpr, argumentsExpr);
return configureAST(methodCallExpression, ctx);
}
// e.g. 1(), 1.1(), ((int) 1 / 2)(1, 2), {a, b -> a + b }(1, 2), m()()
return configureAST(this.createCallMethodCallExpression(baseExpr, argumentsExpr), ctx);
} else if (asBoolean(ctx.closureOrLambdaExpression())) {
ClosureExpression closureExpression = this.visitClosureOrLambdaExpression(ctx.closureOrLambdaExpression());
if (baseExpr instanceof MethodCallExpression) {
MethodCallExpression methodCallExpression = (MethodCallExpression) baseExpr;
Expression argumentsExpression = methodCallExpression.getArguments();
if (argumentsExpression instanceof ArgumentListExpression) {
// normal arguments, e.g. 1, 2
ArgumentListExpression argumentListExpression = (ArgumentListExpression) argumentsExpression;
argumentListExpression.getExpressions().add(closureExpression);
return configureAST(methodCallExpression, ctx);
}
if (argumentsExpression instanceof TupleExpression) {
// named arguments, e.g. x: 1, y: 2
TupleExpression tupleExpression = (TupleExpression) argumentsExpression;
NamedArgumentListExpression namedArgumentListExpression = (NamedArgumentListExpression) tupleExpression.getExpression(0);
if (asBoolean(tupleExpression.getExpressions())) {
methodCallExpression.setArguments(configureAST(new ArgumentListExpression(configureAST(new MapExpression(namedArgumentListExpression.getMapEntryExpressions()), namedArgumentListExpression), closureExpression), tupleExpression));
} else {
// the branch should never reach, because named arguments must not be empty
methodCallExpression.setArguments(configureAST(new ArgumentListExpression(closureExpression), tupleExpression));
}
return configureAST(methodCallExpression, ctx);
}
}
if (baseExpr instanceof PropertyExpression) {
// e.g. obj.m { }
MethodCallExpression methodCallExpression = this.createMethodCallExpression((PropertyExpression) baseExpr, configureAST(new ArgumentListExpression(closureExpression), closureExpression));
return configureAST(methodCallExpression, ctx);
}
if (// e.g. m { }
baseExpr instanceof VariableExpression || // e.g. "$m" { }
baseExpr instanceof GStringExpression || (baseExpr instanceof ConstantExpression && this.isTrue(baseExpr, IS_STRING))) {
// e.g. "m" { }
MethodCallExpression methodCallExpression = this.createMethodCallExpression(baseExpr, configureAST(new ArgumentListExpression(closureExpression), closureExpression));
return configureAST(methodCallExpression, ctx);
}
// e.g. 1 { }, 1.1 { }, (1 / 2) { }, m() { }, { -> ... } { }
MethodCallExpression methodCallExpression = this.createCallMethodCallExpression(baseExpr, configureAST(new ArgumentListExpression(closureExpression), closureExpression));
return configureAST(methodCallExpression, ctx);
}
throw createParsingFailedException("Unsupported path element: " + ctx.getText(), ctx);
}
use of org.codehaus.groovy.ast.expr.MethodPointerExpression in project gradle by gradle.
the class ExpressionReplacingVisitorSupport method visitMethodPointerExpression.
@Override
public void visitMethodPointerExpression(MethodPointerExpression expr) {
MethodPointerExpression result = new MethodPointerExpression(replaceExpr(expr.getExpression()), expr.getMethodName());
result.setType(expr.getType());
result.setSourcePosition(expr);
replaceVisitedExpressionWith(result);
}
Aggregations