8178701: Compile error with switch statement on protected enum defined in parent inner class

Reviewed-by: vromero
This commit is contained in:
Jan Lahoda 2022-05-16 11:53:09 +00:00
parent f4258a50e0
commit 77dfbb4570
4 changed files with 180 additions and 43 deletions

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1999, 2022, 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
@ -92,6 +92,10 @@ public class AttrContext {
*/
boolean visitingServiceImplementation = false;
/** Indicate protected access should be unconditionally allowed.
*/
boolean allowProtectedAccess = false;
/** Are arguments to current function applications boxed into an array for varargs?
*/
Resolve.MethodResolutionPhase pendingResolutionPhase = null;
@ -149,6 +153,7 @@ public class AttrContext {
info.isNewClass = isNewClass;
info.preferredTreeForDiagnostics = preferredTreeForDiagnostics;
info.visitingServiceImplementation = visitingServiceImplementation;
info.allowProtectedAccess = allowProtectedAccess;
return info;
}

View File

@ -499,50 +499,56 @@ public class Lower extends TreeTranslator {
// generate the field initializer for the map
void translate() {
make.at(pos.getStartPosition());
JCClassDecl owner = classDef((ClassSymbol)mapVar.owner);
boolean prevAllowProtectedAccess = attrEnv.info.allowProtectedAccess;
try {
make.at(pos.getStartPosition());
attrEnv.info.allowProtectedAccess = true;
JCClassDecl owner = classDef((ClassSymbol)mapVar.owner);
// synthetic static final int[] $SwitchMap$Color = new int[Color.values().length];
MethodSymbol valuesMethod = lookupMethod(pos,
names.values,
forEnum.type,
List.nil());
JCExpression size = make // Color.values().length
.Select(make.App(make.QualIdent(valuesMethod)),
syms.lengthVar);
JCExpression mapVarInit = make
.NewArray(make.Type(syms.intType), List.of(size), null)
.setType(new ArrayType(syms.intType, syms.arrayClass));
// synthetic static final int[] $SwitchMap$Color = new int[Color.values().length];
MethodSymbol valuesMethod = lookupMethod(pos,
names.values,
forEnum.type,
List.nil());
JCExpression size = make // Color.values().length
.Select(make.App(make.QualIdent(valuesMethod)),
syms.lengthVar);
JCExpression mapVarInit = make
.NewArray(make.Type(syms.intType), List.of(size), null)
.setType(new ArrayType(syms.intType, syms.arrayClass));
// try { $SwitchMap$Color[red.ordinal()] = 1; } catch (java.lang.NoSuchFieldError ex) {}
ListBuffer<JCStatement> stmts = new ListBuffer<>();
Symbol ordinalMethod = lookupMethod(pos,
names.ordinal,
forEnum.type,
List.nil());
List<JCCatch> catcher = List.<JCCatch>nil()
.prepend(make.Catch(make.VarDef(new VarSymbol(PARAMETER, names.ex,
syms.noSuchFieldErrorType,
syms.noSymbol),
null),
make.Block(0, List.nil())));
for (Map.Entry<VarSymbol,Integer> e : values.entrySet()) {
VarSymbol enumerator = e.getKey();
Integer mappedValue = e.getValue();
JCExpression assign = make
.Assign(make.Indexed(mapVar,
make.App(make.Select(make.QualIdent(enumerator),
ordinalMethod))),
make.Literal(mappedValue))
.setType(syms.intType);
JCStatement exec = make.Exec(assign);
JCStatement _try = make.Try(make.Block(0, List.of(exec)), catcher, null);
stmts.append(_try);
// try { $SwitchMap$Color[red.ordinal()] = 1; } catch (java.lang.NoSuchFieldError ex) {}
ListBuffer<JCStatement> stmts = new ListBuffer<>();
Symbol ordinalMethod = lookupMethod(pos,
names.ordinal,
forEnum.type,
List.nil());
List<JCCatch> catcher = List.<JCCatch>nil()
.prepend(make.Catch(make.VarDef(new VarSymbol(PARAMETER, names.ex,
syms.noSuchFieldErrorType,
syms.noSymbol),
null),
make.Block(0, List.nil())));
for (Map.Entry<VarSymbol,Integer> e : values.entrySet()) {
VarSymbol enumerator = e.getKey();
Integer mappedValue = e.getValue();
JCExpression assign = make
.Assign(make.Indexed(mapVar,
make.App(make.Select(make.QualIdent(enumerator),
ordinalMethod))),
make.Literal(mappedValue))
.setType(syms.intType);
JCStatement exec = make.Exec(assign);
JCStatement _try = make.Try(make.Block(0, List.of(exec)), catcher, null);
stmts.append(_try);
}
owner.defs = owner.defs
.prepend(make.Block(STATIC, stmts.toList()))
.prepend(make.VarDef(mapVar, mapVarInit));
} finally {
attrEnv.info.allowProtectedAccess = prevAllowProtectedAccess;
}
owner.defs = owner.defs
.prepend(make.Block(STATIC, stmts.toList()))
.prepend(make.VarDef(mapVar, mapVarInit));
}
}

View File

@ -359,7 +359,9 @@ public class Resolve {
||
env.toplevel.packge == c.packge()
||
isInnerSubClass(env.enclClass.sym, c.owner);
isInnerSubClass(env.enclClass.sym, c.owner)
||
env.info.allowProtectedAccess;
break;
}
return (checkInner == false || c.type.getEnclosingType() == Type.noType) ?

View File

@ -0,0 +1,124 @@
/*
* Copyright (c) 2022, 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 8178701
* @summary Check javac can generate code for protected enums accessible through subclassing.
* @library /tools/lib
* @modules jdk.compiler/com.sun.tools.javac.api
* jdk.compiler/com.sun.tools.javac.main
* jdk.compiler/com.sun.tools.javac.util
* @build toolbox.ToolBox toolbox.JavacTask
* @run main EnumAccessible
*/
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Objects;
import toolbox.TestRunner;
import toolbox.JavacTask;
import toolbox.JavaTask;
import toolbox.Task;
import toolbox.ToolBox;
public class EnumAccessible extends TestRunner {
ToolBox tb;
public static void main(String... args) throws Exception {
new EnumAccessible().runTests();
}
EnumAccessible() {
super(System.err);
tb = new ToolBox();
}
public void runTests() throws Exception {
runTests(m -> new Object[] { Paths.get(m.getName()) });
}
@Test
public void testPattern(Path base) throws Exception {
Path current = base.resolve(".");
Path src = current.resolve("src");
Path classes = current.resolve("classes");
tb.writeJavaFiles(src,
"""
package foo;
import bar.D.E;
public class A {
public static class B {
protected enum C {
X, Y, Z
}
}
public static void main(String... args) {
new E().run(B.C.X);
}
}
""",
"""
package bar;
import foo.A.B;
public class D {
public static class E extends B {
public void run(C arg) {
switch (arg) {
default: System.out.println("OK");
}
}
}
}
""");
Files.createDirectories(classes);
new JavacTask(tb)
.options("-doe")
.outdir(classes)
.files(tb.findJavaFiles(src))
.run(Task.Expect.SUCCESS)
.writeAll();
var out = new JavaTask(tb)
.classpath(classes.toString())
.className("foo.A")
.run()
.writeAll()
.getOutputLines(Task.OutputKind.STDOUT);
var expectedOut = List.of("OK");
if (!Objects.equals(expectedOut, out)) {
throw new AssertionError("Incorrect Output, expected: " + expectedOut +
", actual: " + out);
}
}
}