Skip to content

Commit

Permalink
8178701: Compile error with switch statement on protected enum define…
Browse files Browse the repository at this point in the history
…d in parent inner class

Reviewed-by: vromero
  • Loading branch information
lahodaj committed May 16, 2022
1 parent f4258a5 commit 77dfbb4
Show file tree
Hide file tree
Showing 4 changed files with 182 additions and 45 deletions.
@@ -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
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -149,6 +153,7 @@ AttrContext dup(WriteableScope scope) {
info.isNewClass = isNewClass;
info.preferredTreeForDiagnostics = preferredTreeForDiagnostics;
info.visitingServiceImplementation = visitingServiceImplementation;
info.allowProtectedAccess = allowProtectedAccess;
return info;
}

Expand Down
92 changes: 49 additions & 43 deletions src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Lower.java
Expand Up @@ -499,50 +499,56 @@ JCLiteral forConstant(VarSymbol v) {

// generate the field initializer for the map
void translate() {
make.at(pos.getStartPosition());
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));

// 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);
}
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));

// 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));
owner.defs = owner.defs
.prepend(make.Block(STATIC, stmts.toList()))
.prepend(make.VarDef(mapVar, mapVarInit));
} finally {
attrEnv.info.allowProtectedAccess = prevAllowProtectedAccess;
}
}
}

Expand Down
Expand Up @@ -359,7 +359,9 @@ public boolean isAccessible(Env<AttrContext> env, TypeSymbol c, boolean checkInn
||
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) ?
Expand Down
124 changes: 124 additions & 0 deletions test/langtools/tools/EnumAccessible.java
@@ -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);

}
}

}

1 comment on commit 77dfbb4

@openjdk-notifier
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.