8071961: Add javac lint warning when a default constructor is created

Reviewed-by: jjg, jlahoda, abuckley, erikj, mcimadamore
This commit is contained in:
Joe Darcy 2020-08-17 18:58:20 -07:00
parent 39c9560cbf
commit 61e42ed85d
12 changed files with 603 additions and 2 deletions

View File

@ -76,6 +76,7 @@ java.datatransfer_COPY += flavormap.properties
################################################################################
java.desktop_DISABLED_WARNINGS += missing-explicit-ctor
java.desktop_DOCLINT += -Xdoclint:all/protected,-reference \
'-Xdoclint/package:java.*,javax.*'
java.desktop_COPY += .gif .png .wav .txt .xml .css .pf
@ -298,6 +299,10 @@ java.xml.crypto_CLEAN += .properties
################################################################################
jdk.accessibility_DISABLED_WARNINGS += missing-explicit-ctor
################################################################################
jdk.charsets_COPY += .dat
################################################################################
@ -347,10 +352,19 @@ jdk.javadoc_COPY += .xml .css .js .png
################################################################################
jdk.jartool_DISABLED_WARNINGS += missing-explicit-ctor
jdk.jartool_JAVAC_FLAGS += -XDstringConcat=inline
################################################################################
jdk.httpserver_DISABLED_WARNINGS += missing-explicit-ctor
################################################################################
jdk.unsupported.desktop_DISABLED_WARNINGS += missing-explicit-ctor
################################################################################
# No SCTP implementation on Mac OS X or AIX. These classes should be excluded.
SCTP_IMPL_CLASSES = \
$(TOPDIR)/src/jdk.sctp/unix/classes/sun/nio/ch/sctp/AssociationChange.java \

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2005, 2020, 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
@ -210,6 +210,11 @@ public class Lint
*/
FINALLY("finally"),
/**
* Warn about compiler generation of a default constructor.
*/
MISSING_EXPLICIT_CTOR("missing-explicit-ctor"),
/**
* Warn about module system related issues.
*/

View File

@ -29,6 +29,7 @@ import java.util.*;
import java.util.function.Supplier;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.NestingKind;
import javax.tools.JavaFileManager;
import com.sun.tools.javac.code.*;
@ -3827,6 +3828,59 @@ public class Check {
}
}
/**
* Check for a default constructor in an exported package.
*/
void checkDefaultConstructor(ClassSymbol c, DiagnosticPosition pos) {
if (lint.isEnabled(LintCategory.MISSING_EXPLICIT_CTOR) &&
((c.flags() & (ENUM | RECORD)) == 0) &&
!c.isAnonymous() &&
((c.flags() & PUBLIC) != 0) &&
Feature.MODULES.allowedInSource(source)) {
NestingKind nestingKind = c.getNestingKind();
switch (nestingKind) {
case ANONYMOUS,
LOCAL -> {return;}
case TOP_LEVEL -> {;} // No additional checks needed
case MEMBER -> {
// For nested member classes, all the enclosing
// classes must be public.
Symbol owner = c.owner;
while (owner != null && owner.kind == TYP) {
if ((owner.flags() & PUBLIC) == 0)
return;
owner = owner.owner;
}
}
}
// Only check classes in named packages exported by its module
PackageSymbol pkg = c.packge();
if (!pkg.isUnnamed()) {
ModuleSymbol modle = pkg.modle;
for (ExportsDirective exportDir : modle.exports) {
// Report warning only if the containing
// package is unconditionally exported
if (exportDir.packge.equals(pkg)) {
if (exportDir.modules == null || exportDir.modules.isEmpty()) {
// Warning may be suppressed by
// annotations; check again for being
// enabled in the deferred context.
deferredLintHandler.report(() -> {
if (lint.isEnabled(LintCategory.MISSING_EXPLICIT_CTOR))
log.warning(LintCategory.MISSING_EXPLICIT_CTOR,
pos, Warnings.MissingExplicitCtor(c, pkg, modle));
});
} else {
return;
}
}
}
}
}
return;
}
private class ConversionWarner extends Warner {
final String uncheckedKey;
final Type found;

View File

@ -1000,6 +1000,7 @@ public class TypeEnter implements Completer {
// Add default constructor if needed.
DefaultConstructorHelper helper = getDefaultConstructorHelper(env);
if (helper != null) {
chk.checkDefaultConstructor(sym, tree.pos());
defaultConstructor = defaultConstructor(make.at(tree.pos), helper);
tree.defs = tree.defs.prepend(defaultConstructor);
}

View File

@ -1760,6 +1760,10 @@ compiler.warn.dir.path.element.not.found=\
compiler.warn.dir.path.element.not.directory=\
bad path element "{0}": not a directory
# 0: symbol, 1: symbol, 2: symbol
compiler.warn.missing-explicit-ctor=\
class {0} in exported package {1} declares no explicit constructors, thereby exposing a default constructor to clients of module {2}
compiler.warn.finally.cannot.complete=\
finally clause cannot complete normally

View File

@ -1,5 +1,5 @@
#
# Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 1999, 2020, 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
@ -182,6 +182,9 @@ javac.opt.Xlint.desc.cast=\
javac.opt.Xlint.desc.classfile=\
Warn about issues related to classfile contents.
javac.opt.Xlint.desc.missing-explicit-ctor=\
Warn about missing explicit constructors in public classes in exported packages.
javac.opt.Xlint.desc.deprecation=\
Warn about use of deprecated items.

View File

@ -0,0 +1,25 @@
/*
* Copyright (c) 2020, 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.warn.missing-explicit-ctor
// options: -Xlint:missing-explicit-ctor

View File

@ -0,0 +1,26 @@
/*
* Copyright (c) 2020, 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.
*/
module defaultctor {
exports pkg;
}

View File

@ -0,0 +1,28 @@
/*
* Copyright (c) 2020, 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.
*/
package pkg;
public class Foo {
// No explicit constructor.
}

View File

@ -0,0 +1,369 @@
/*
* Copyright (c) 2019, 2020, 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.
*/
/*
* @test
* @bug 8071961
* @summary Verify expected default constructor warnings are producted or not produced
* @library /tools/lib
* @modules jdk.compiler/com.sun.tools.javac.api
* jdk.compiler/com.sun.tools.javac.main
* @build toolbox.ToolBox toolbox.JavacTask toolbox.TestRunner
* @run main DefaultCtorWarningToolBox
*/
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.EnumSet;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;
import toolbox.JavacTask;
import toolbox.Task;
import toolbox.Task.Expect;
import toolbox.TestRunner;
import toolbox.ToolBox;
public class DefaultCtorWarningToolBox extends TestRunner {
private final ToolBox tb = new ToolBox();
private final String fileSep = System.getProperty("file.separator");
public DefaultCtorWarningToolBox() {
super(System.err);
}
public static void main(String... args) throws Exception {
new DefaultCtorWarningToolBox().runTests();
}
@Test
public void testWithAndWithOutLint(Path base) throws IOException {
Path src = base.resolve("src");
tb.writeJavaFiles(src,
MOD_INFO_SRC,
PKG1_BAR_SRC, PKG1_FOO_SRC,
PKG2_BAZ_SRC, PKG2_QUUX_SRC,
PKG3_CORGE_SRC, PKG3_GRAULT_SRC
);
Path classes = base.resolve("classes");
tb.createDirectories(classes);
List<String> log;
List<String> expected = List.of("");
// Warning disabled, no messages expected
log = new JavacTask(tb)
.options("-Xlint:-missing-explicit-ctor", "-Werror")
.outdir(classes)
.files(tb.findJavaFiles(src))
.run(Expect.SUCCESS)
.writeAll()
.getOutputLines(Task.OutputKind.DIRECT);
if (!expected.equals(log)) {
throw new AssertionError("Unexpected output: " + log);
}
expected =
List.of("Foo.java:4:8: compiler.warn.missing-explicit-ctor: pkg1.Foo, pkg1, mod",
"Foo.java:12:12: compiler.warn.missing-explicit-ctor: pkg1.Foo.FooNest, pkg1, mod",
"Foo.java:16:19: compiler.warn.missing-explicit-ctor: pkg1.Foo.StaticFooNest, pkg1, mod",
"3 warnings");
// Warning enable,
log = new JavacTask(tb)
.options("-Xlint:missing-explicit-ctor", "-XDrawDiagnostics")
.outdir(classes)
.files(tb.findJavaFiles(src))
.run(Expect.SUCCESS)
.writeAll()
.getOutputLines(Task.OutputKind.DIRECT);
if (!expected.equals(log)) {
throw new AssertionError("Unexpected output: " + log);
}
}
protected void runTests() throws Exception {
runTests(m -> new Object[] { Paths.get(m.getName()).toAbsolutePath() });
}
private static final String MOD_INFO_SRC =
"""
module mod {
exports pkg1;
// Do *not* export pkg2.
exports pkg3 to java.base;
}
""";
private static final String PKG1_BAR_SRC =
"""
package pkg1;
// Neither the top-level class nor the nested classes should generate
// a warning since Bar is not public.
// No explicit constructor; use a default.
class Bar {
// No explicit constructor; use a default.
public class FooNest {
}
// No explicit constructor; use a default.
public static class StaticFooNest {
}
// Package-access classes
// No explicit constructor; use a default.
/*package*/ class PkgFooNest {
}
// No explicit constructor; use a default.
/*package*/ static class PkgStaticFooNest {
}
// Private classes
// No explicit constructor; use a default.
private class PrvFooNest {
}
// No explicit constructor; use a default.
private static class PrvStaticFooNest {
}
}
""";
private static final String PKG1_FOO_SRC =
"""
package pkg1;
// No explicit constructor; use a default.
public class Foo {
/*
* Of the nexted classes, only FooNest and StaticFooNest should
* generate warnings.
*/
// No explicit constructor; use a default.
public class FooNest {
}
// No explicit constructor; use a default.
public static class StaticFooNest {
}
// No explicit constructor; use a default.
@SuppressWarnings("missing-explicit-ctor")
public static class SuppressedStaticFooNest {
}
// Package-access classes
// No explicit constructor; use a default.
/*package*/ class PkgFooNest {
}
// No explicit constructor; use a default.
/*package*/ static class PkgStaticFooNest {
}
// Private classes
// No explicit constructor; use a default.
private class PrvFooNest {
}
// No explicit constructor; use a default.
private static class PrvStaticFooNest {
}
}
""";
private static final String PKG2_BAZ_SRC =
"""
package pkg2;
// None of these classes should generate warnings since pkg2 is not
// exported unconditionally.
// No explicit constructor; use a default.
public class Baz {
// No explicit constructor; use a default.
public class FooNest {
}
// No explicit constructor; use a default.
public static class StaticFooNest {
}
// Package-access classes
// No explicit constructor; use a default.
/*package*/ class PkgFooNest {
}
// No explicit constructor; use a default.
/*package*/ static class PkgStaticFooNest {
}
// Private classes
// No explicit constructor; use a default.
private class PrvFooNest {
}
// No explicit constructor; use a default.
private static class PrvStaticFooNest {
}
}
""";
private static final String PKG2_QUUX_SRC =
"""
package pkg2;
// Neither the top-level class nor the nested classes should generate
// a warning since Bar is not public.
// No explicit constructor; use a default.
class Quux {
// No explicit constructor; use a default.
public class FooNest {
}
// No explicit constructor; use a default.
public static class StaticFooNest {
}
// Package-access classes
// No explicit constructor; use a default.
/*package*/ class PkgFooNest {
}
// No explicit constructor; use a default.
/*package*/ static class PkgStaticFooNest {
}
// Private classes
// No explicit constructor; use a default.
private class PrvFooNest {
}
// No explicit constructor; use a default.
private static class PrvStaticFooNest {
}
}
""";
private static final String PKG3_CORGE_SRC =
"""
package pkg3;
// None of these classes should generate warnings since pkg3 is not
// exported unconditionally.
// No explicit constructor; use a default.
public class Corge {
// No explicit constructor; use a default.
public class FooNest {
}
// No explicit constructor; use a default.
public static class StaticFooNest {
}
// Package-access classes
// No explicit constructor; use a default.
/*package*/ class PkgFooNest {
}
// No explicit constructor; use a default.
/*package*/ static class PkgStaticFooNest {
}
// Private classes
// No explicit constructor; use a default.
private class PrvFooNest {
}
// No explicit constructor; use a default.
private static class PrvStaticFooNest {
}
}
""";
private static final String PKG3_GRAULT_SRC =
"""
package pkg3;
// None of these classes should generate warnings since pkg3 is not
// exported unconditionally.
// No explicit constructor; use a default.
class Grault {
// No explicit constructor; use a default.
public class FooNest {
}
// No explicit constructor; use a default.
public static class StaticFooNest {
}
// Package-access classes
// No explicit constructor; use a default.
/*package*/ class PkgFooNest {
}
// No explicit constructor; use a default.
/*package*/ static class PkgStaticFooNest {
}
// Private classes
// No explicit constructor; use a default.
private class PrvFooNest {
}
// No explicit constructor; use a default.
private static class PrvStaticFooNest {
}
}
""";
}

View File

@ -0,0 +1,39 @@
/*
* Copyright (c) 2020, 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.
*/
/*
* @test
* @bug 8071961
* @compile -Xlint:missing-explicit-ctor -Werror --release 8 NoWarningCases.java
* @compile -Xlint:missing-explicit-ctor -Werror NoWarningCases.java
*/
public class NoWarningCases {
// No explicit constructor; use a default.
public enum NestedEnum {
FOO,
BAR;
// No explicit constructor; use implicit one.
}
}

View File

@ -0,0 +1,33 @@
/*
* Copyright (c) 2020, 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.
*/
/*
* @test
* @bug 8071961
* @compile -Xlint:missing-explicit-ctor -Werror
* --enable-preview -source ${jdk.version} NoWarningRecord.java
*/
public record NoWarningRecord(/* no components */) {
// No explicit constructor; use canonical one.
}