Skip to content

Commit

Permalink
Overloading checkpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
biboudis committed Feb 28, 2024
1 parent 0e23911 commit 385b813
Show file tree
Hide file tree
Showing 11 changed files with 389 additions and 14 deletions.
74 changes: 67 additions & 7 deletions src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1999, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
Expand Down Expand Up @@ -28,7 +28,9 @@
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

import javax.lang.model.element.ElementKind;
import javax.tools.JavaFileObject;
Expand Down Expand Up @@ -4250,14 +4252,72 @@ public void visitRecordPattern(JCRecordPattern tree) {

if (site.tsym.kind == Kind.TYP) {
int nestedPatternCount = tree.nested.size();
var matchers = site.tsym.members().getSymbols(sym -> (sym.flags() & MATCHER) != 0 && sym.type.getParameterTypes().size() == nestedPatternCount);
Iterator<Symbol> matchersIt = matchers.iterator();

if (matchersIt.hasNext()) {
MethodSymbol matcher = (MethodSymbol) matchers.iterator().next();
// precalculate types of pattern components (as in method invocation)
ListBuffer<Type> patternTypesBuffer = new ListBuffer<>();
for (JCTree arg : tree.nested.map(p -> p.getTree())) {
Type argtype = chk.checkNonVoid(arg, attribTree(arg, env, resultInfo));
patternTypesBuffer.append(argtype);
}
List<Type> patternTypes = patternTypesBuffer.toList();

var matchersIt = site.tsym.members()
.getSymbols(sym -> (sym.flags() & MATCHER) != 0 && sym.type.getParameterTypes().size() == nestedPatternCount)
.iterator();
List<MethodSymbol> matchers = Stream.generate(() -> null)
.takeWhile(x -> matchersIt.hasNext())
.map(n -> (MethodSymbol) matchersIt.next())
.collect(List.collector());

if (matchers.size() >= 1) {
ListBuffer<Integer> score = new ListBuffer<Integer>();

// overload resolution of matcher
for (MethodSymbol matcher : matchers) {
int scoreForMatcher = 0;

List<Type> matcherComponentTypes = matcher.getParameters()
.stream()
.map(rc -> types.memberType(site, rc))
.map(t -> types.upward(t, types.captures(t)).baseType())
.collect(List.collector());

boolean applicable = true;
for (int i = 0; applicable && i < patternTypes.size(); i++) {
applicable &= types.isCastable(patternTypes.get(i), matcherComponentTypes.get(i));
}

if (applicable) {
// todo: need to separate scores for each parameter
for (int i = 0; i < patternTypes.size(); i++) {
if (types.isSameType(patternTypes.get(i), matcherComponentTypes.get(i))) {
scoreForMatcher += 2;
} else if (types.isCastable(patternTypes.get(i), matcherComponentTypes.get(i))) {
scoreForMatcher += 1;
}
}
score.add(scoreForMatcher);
} else {
score.add(-1);
}
}

tree.matcher = matcher;
expectedRecordTypes = types.memberType(site, matcher).getParameterTypes();
var maxScore = Collections.max(score);
List<Integer> scoreList = score.toList();
var indexOfMaxScore = scoreList.indexOf(maxScore);

if (maxScore == -1) {
log.error(tree.pos(),
Errors.NoCompatibleMatcherFound);
} else if (scoreList.stream().filter(s -> s == maxScore).count() > 1) {
log.error(tree.pos(),
Errors.MatcherOverloadingAmbiguity);
} else {
MethodSymbol matcher = matchers.get(indexOfMaxScore);
tree.matcher = matcher;

expectedRecordTypes = types.memberType(site, matcher).getParameterTypes();
}
} else if (((ClassSymbol) site.tsym).isRecord()) {
ClassSymbol record = (ClassSymbol) site.tsym;
expectedRecordTypes = record.getRecordComponents()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1248,27 +1248,29 @@ public void visitMethodDef(JCMethodDecl tree) {
if (tree.sym.isDeconstructor()) {
// Generate (without the bindings)
// 1. calculate the returnType MethodType as Constant_MethodType_info
// 2. generate factory code on carrier for the types we want (e.g., Object carrier = Carriers.factory(returnType);)
// 2. generate factory code on carrier for the types we want (e.g., Object carrier = Carriers.initializingConstructor(returnType);)
// 3. generate invoke call to pass the bindings (e.g, return carrier.invoke(x, y);)

List<Type> params = List.nil();
List<JCExpression> invokeMethodParam = List.nil();

for (int i = 0; i < tree.params.length(); i++) {
params = params.append(types.boxedTypeOrType(tree.params.get(i).type));
params = params.append(tree.params.get(i).type);
invokeMethodParam = invokeMethodParam.append(make.Ident(tree.params.get(i)));
}

MethodSymbol factoryMethodSym =
rs.resolveInternalMethod(tree.pos(),
env,
syms.carriersType,
names.fromString("factory"),
names.fromString("initializingConstructor"),
List.of(syms.methodTypeType),
List.nil());

DynamicVarSymbol factoryMethodDynamicVar =
(DynamicVarSymbol) invokeMethodWrapper(tree.pos(),
(DynamicVarSymbol) invokeMethodWrapper(
names.fromString("carrier"),
tree.pos(),
factoryMethodSym.asHandle(),
new MethodType(params, syms.objectType, List.nil(), syms.methodClass));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -448,6 +448,12 @@ compiler.err.concrete.inheritance.conflict=\
compiler.err.default.allowed.in.intf.annotation.member=\
default value only allowed in an annotation interface declaration

compiler.err.matcher.overloading.ambiguity=\
matcher overloading ambiguity

compiler.err.no.compatible.matcher.found=\
no compatible matcher found

# 0: symbol
compiler.err.doesnt.exist=\
package {0} does not exist
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -609,7 +609,10 @@ public void visitMethodDef(JCMethodDecl tree) {
printDocComment(tree);
printExpr(tree.mods);
printTypeParameters(tree.typarams);
if (tree.name == tree.name.table.names.init) {
if (tree.sym.isMatcher()) {
print("__matcher ");
}
if (tree.name == tree.name.table.names.init || tree.sym.isMatcher()) {
print(enclClassName != null ? enclClassName : tree.name);
} else {
printExpr(tree.restype);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
* Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/

// key: compiler.err.matcher.overloading.ambiguity
// key: compiler.misc.feature.matchers
// key: compiler.warn.preview.feature.use.plural
// options: --enable-preview -source ${jdk.version} -Xlint:preview

public class MatcherOverloadingAmbiguity {
private static int test(D o) {
if (o instanceof D(String data, Integer out)) {
return out;
}
return -1;
}

public record D() {
public __matcher D(Object v, Integer out) {
out = 1;
}

public __matcher D(CharSequence v, Integer out) {
out = 2;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*
* Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/

// key: compiler.err.no.compatible.matcher.found
// key: compiler.err.prob.found.req
// key: compiler.misc.inconvertible.types
// key: compiler.misc.feature.matchers
// key: compiler.warn.preview.feature.use.plural
// options: --enable-preview -source ${jdk.version} -Xlint:preview

public class NoCompatibleMatcherFound {
private static int test(D o) {
if (o instanceof D(String data, Integer out)) {
return out;
}
return -1;
}

public record D() {
public __matcher D(Object v1, Float out) {
out = 10.0f;
}

public __matcher D(Float out, Integer v1) {
out = 2;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,6 @@ DeconstructionPatternErrors.java:26:29: compiler.err.instanceof.reifiable.not.sa
DeconstructionPatternErrors.java:27:44: compiler.err.prob.found.req: (compiler.misc.inconvertible.types: java.lang.String, java.lang.Integer)
DeconstructionPatternErrors.java:27:13: compiler.err.instanceof.reifiable.not.safe: java.lang.Object, DeconstructionPatternErrors.GenRecord<java.lang.String>
DeconstructionPatternErrors.java:28:40: compiler.err.match.binding.exists
DeconstructionPatternErrors.java:29:56: compiler.err.already.defined: kindname.variable, v1, kindname.method, meth()
DeconstructionPatternErrors.java:29:64: compiler.err.already.defined: kindname.variable, v2, kindname.method, meth()
DeconstructionPatternErrors.java:29:56: compiler.err.match.binding.exists
DeconstructionPatternErrors.java:29:64: compiler.err.match.binding.exists
22 errors
106 changes: 106 additions & 0 deletions test/langtools/tools/javac/patterns/matchers/OverloadedMatchers.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
/*
* Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/

import java.util.Objects;

/**
* @test
* @enablePreview
* @compile OverloadedMatchers.java
* @run main OverloadedMatchers
*/
public class OverloadedMatchers {
public static void main(String... args) {
assertEquals( 2, test1(new D()));
assertEquals( 1, test2(new D()));
assertEquals( 1, test3(new D()));
assertEquals( 3, test4(new D()));
assertEquals( 4, test5(new D()));
}

private static int test1(D o) {
if (o instanceof D(String data, Integer outI)) {
return outI;
}
return -1;
}

private static int test2(D o) {
if (o instanceof D(Object data, Integer outI)) {
return outI;
}
return -1;
}

private static int test3(D o) {
if (o instanceof D(Integer data, Integer outI)) {
return outI;
}
return -1;
}

private static int test4(D o) {
if (o instanceof D(A data, Integer outI)) {
return outI;
}
return -1;
}

private static Integer test5(D o) {
if (o instanceof D(B data, Integer outI)) {
return outI;
}
return null;
}

static class A {}
static class B extends A {}

public record D() {
public __matcher D(Object out, Integer outI) {
out = 42;
outI = 1;
}

public __matcher D(String out, Integer outI) {
out = "2";
outI = 2;
}

public __matcher D(A out, Integer outI) {
out = new A();
outI = 3;
}

public __matcher D(B out, Integer outI) {
out = new B();
outI = 4;
}
}

private static void assertEquals(int expected, int actual) {
if (!Objects.equals(expected, actual)) {
throw new AssertionError("Expected: " + expected + ", but got: " + actual);
}
}
}
Loading

0 comments on commit 385b813

Please sign in to comment.