From 385b813a64d4ef7f5f9300e36e16bc80c6695f7d Mon Sep 17 00:00:00 2001 From: Angelos Bimpoudis Date: Wed, 28 Feb 2024 14:41:03 +0100 Subject: [PATCH] Overloading checkpoint --- .../com/sun/tools/javac/comp/Attr.java | 74 ++++++++++-- .../sun/tools/javac/comp/TransPatterns.java | 10 +- .../tools/javac/resources/compiler.properties | 6 + .../com/sun/tools/javac/tree/Pretty.java | 5 +- .../examples/MatcherOverloadingAmbiguity.java | 46 ++++++++ .../examples/NoCompatibleMatcherFound.java | 48 ++++++++ .../patterns/DeconstructionPatternErrors.out | 4 +- .../patterns/matchers/OverloadedMatchers.java | 106 ++++++++++++++++++ .../matchers/OverloadedMatchersErrors.java | 41 +++++++ .../matchers/OverloadedMatchersErrors.out | 6 + .../matchers/OverloadedPrimitiveMatchers.java | 57 ++++++++++ 11 files changed, 389 insertions(+), 14 deletions(-) create mode 100644 test/langtools/tools/javac/diags/examples/MatcherOverloadingAmbiguity.java create mode 100644 test/langtools/tools/javac/diags/examples/NoCompatibleMatcherFound.java create mode 100644 test/langtools/tools/javac/patterns/matchers/OverloadedMatchers.java create mode 100644 test/langtools/tools/javac/patterns/matchers/OverloadedMatchersErrors.java create mode 100644 test/langtools/tools/javac/patterns/matchers/OverloadedMatchersErrors.out create mode 100644 test/langtools/tools/javac/patterns/matchers/OverloadedPrimitiveMatchers.java diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java index 456bac6e663..93f4d11a90b 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java @@ -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 @@ -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; @@ -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 matchersIt = matchers.iterator(); - if (matchersIt.hasNext()) { - MethodSymbol matcher = (MethodSymbol) matchers.iterator().next(); + // precalculate types of pattern components (as in method invocation) + ListBuffer 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 patternTypes = patternTypesBuffer.toList(); + + var matchersIt = site.tsym.members() + .getSymbols(sym -> (sym.flags() & MATCHER) != 0 && sym.type.getParameterTypes().size() == nestedPatternCount) + .iterator(); + List matchers = Stream.generate(() -> null) + .takeWhile(x -> matchersIt.hasNext()) + .map(n -> (MethodSymbol) matchersIt.next()) + .collect(List.collector()); + + if (matchers.size() >= 1) { + ListBuffer score = new ListBuffer(); + + // overload resolution of matcher + for (MethodSymbol matcher : matchers) { + int scoreForMatcher = 0; + + List 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 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() diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TransPatterns.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TransPatterns.java index 470f68f19bc..9d0a3006997 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TransPatterns.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TransPatterns.java @@ -1248,14 +1248,14 @@ 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 params = List.nil(); List 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))); } @@ -1263,12 +1263,14 @@ public void visitMethodDef(JCMethodDecl tree) { 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)); diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/compiler.properties b/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/compiler.properties index e50765b5668..fb61c7e1f99 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/compiler.properties +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/compiler.properties @@ -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 diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/Pretty.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/Pretty.java index 06a8f6f143f..4b8ae818119 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/Pretty.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/Pretty.java @@ -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); diff --git a/test/langtools/tools/javac/diags/examples/MatcherOverloadingAmbiguity.java b/test/langtools/tools/javac/diags/examples/MatcherOverloadingAmbiguity.java new file mode 100644 index 00000000000..5abb3bdd9b9 --- /dev/null +++ b/test/langtools/tools/javac/diags/examples/MatcherOverloadingAmbiguity.java @@ -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; + } + } +} \ No newline at end of file diff --git a/test/langtools/tools/javac/diags/examples/NoCompatibleMatcherFound.java b/test/langtools/tools/javac/diags/examples/NoCompatibleMatcherFound.java new file mode 100644 index 00000000000..32e62fc52f3 --- /dev/null +++ b/test/langtools/tools/javac/diags/examples/NoCompatibleMatcherFound.java @@ -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; + } + } +} \ No newline at end of file diff --git a/test/langtools/tools/javac/patterns/DeconstructionPatternErrors.out b/test/langtools/tools/javac/patterns/DeconstructionPatternErrors.out index f947142cd66..3efaa6a5fa8 100644 --- a/test/langtools/tools/javac/patterns/DeconstructionPatternErrors.out +++ b/test/langtools/tools/javac/patterns/DeconstructionPatternErrors.out @@ -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 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 \ No newline at end of file diff --git a/test/langtools/tools/javac/patterns/matchers/OverloadedMatchers.java b/test/langtools/tools/javac/patterns/matchers/OverloadedMatchers.java new file mode 100644 index 00000000000..322271519b1 --- /dev/null +++ b/test/langtools/tools/javac/patterns/matchers/OverloadedMatchers.java @@ -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); + } + } +} diff --git a/test/langtools/tools/javac/patterns/matchers/OverloadedMatchersErrors.java b/test/langtools/tools/javac/patterns/matchers/OverloadedMatchersErrors.java new file mode 100644 index 00000000000..11dabd25be2 --- /dev/null +++ b/test/langtools/tools/javac/patterns/matchers/OverloadedMatchersErrors.java @@ -0,0 +1,41 @@ +/* + * @test /nodynamiccopyright/ + * @summary Verify error related to annotations and patterns + * @enablePreview + * @compile/fail/ref=OverloadedMatchersErrors.out -XDrawDiagnostics OverloadedMatchersErrors.java + */ +public class OverloadedMatchersErrors { + private static int test(D o) { + if (o instanceof D(String data, Integer out)) { // no compatible matcher found + return out; + } + return -1; + } + + private static int test2(D2 o) { + if (o instanceof D2(String data, Integer out)) { // ambiguous + 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; + } + } + + public record D2() { + public __matcher D2(Object v, Integer out) { + out = 1; + } + + public __matcher D2(CharSequence v, Integer out) { + out = 2; + } + } +} diff --git a/test/langtools/tools/javac/patterns/matchers/OverloadedMatchersErrors.out b/test/langtools/tools/javac/patterns/matchers/OverloadedMatchersErrors.out new file mode 100644 index 00000000000..5a0a18c364e --- /dev/null +++ b/test/langtools/tools/javac/patterns/matchers/OverloadedMatchersErrors.out @@ -0,0 +1,6 @@ +OverloadedMatchersErrors.java:9:26: compiler.err.no.compatible.matcher.found +OverloadedMatchersErrors.java:16:26: compiler.err.matcher.overloading.ambiguity +OverloadedMatchersErrors.java:28:19: compiler.err.prob.found.req: (compiler.misc.inconvertible.types: int, java.lang.Float) +- compiler.note.preview.filename: OverloadedMatchersErrors.java, DEFAULT +- compiler.note.preview.recompile +3 errors \ No newline at end of file diff --git a/test/langtools/tools/javac/patterns/matchers/OverloadedPrimitiveMatchers.java b/test/langtools/tools/javac/patterns/matchers/OverloadedPrimitiveMatchers.java new file mode 100644 index 00000000000..806ecc32c6f --- /dev/null +++ b/test/langtools/tools/javac/patterns/matchers/OverloadedPrimitiveMatchers.java @@ -0,0 +1,57 @@ +/* + * 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 OverloadedPrimitiveMatchers.java + * @run main OverloadedPrimitiveMatchers + */ + +public class OverloadedPrimitiveMatchers { + public static void main(String... args) { + assertEquals( 1, testBoxing(new D())); + } + + private static int testBoxing(D o) { + if (o instanceof D(String data, Integer outI)) { + return outI; + } + return -1; + } + + public record D() { + public __matcher D(String out, int outI) { + out = "42"; + outI = 1; + } + } + + private static void assertEquals(int expected, int actual) { + if (!Objects.equals(expected, actual)) { + throw new AssertionError("Expected: " + expected + ", but got: " + actual); + } + } +}