8256266: Binding variables don't correctly support declaration annotations and the final modifier

Reviewed-by: mcimadamore
This commit is contained in:
Jan Lahoda 2021-01-05 11:40:25 +00:00
parent 216c2ec077
commit 4ffbe841fc
10 changed files with 237 additions and 12 deletions

View File

@ -1865,8 +1865,8 @@ public abstract class Symbol extends AnnoConstruct implements PoolConstant, Elem
public static class BindingSymbol extends VarSymbol {
public BindingSymbol(Name name, Type type, Symbol owner) {
super(Flags.HASINIT | Flags.MATCH_BINDING, name, type, owner);
public BindingSymbol(long flags, Name name, Type type, Symbol owner) {
super(flags | Flags.HASINIT | Flags.MATCH_BINDING, name, type, owner);
}
public boolean isAliasFor(BindingSymbol b) {

View File

@ -389,7 +389,8 @@ public class TypeAnnotations {
if (sym.getKind() == ElementKind.PARAMETER ||
sym.getKind() == ElementKind.LOCAL_VARIABLE ||
sym.getKind() == ElementKind.RESOURCE_VARIABLE ||
sym.getKind() == ElementKind.EXCEPTION_PARAMETER) {
sym.getKind() == ElementKind.EXCEPTION_PARAMETER ||
sym.getKind() == ElementKind.BINDING_VARIABLE) {
appendTypeAnnotationsToOwner(sym, typeAnnotations);
}
}
@ -1264,6 +1265,11 @@ public class TypeAnnotations {
if (!tree.isImplicitlyTyped()) {
separateAnnotationsKinds(tree.vartype, tree.sym.type, tree.sym, pos);
}
} else if (tree.sym.getKind() == ElementKind.BINDING_VARIABLE) {
final TypeAnnotationPosition pos =
TypeAnnotationPosition.localVariable(currentLambda,
tree.pos);
separateAnnotationsKinds(tree.vartype, tree.sym.type, tree.sym, pos);
} else if (tree.sym.getKind() == ElementKind.EXCEPTION_PARAMETER) {
final TypeAnnotationPosition pos =
TypeAnnotationPosition.exceptionParameter(currentLambda,

View File

@ -4000,12 +4000,13 @@ public class Attr extends JCTree.Visitor {
public void visitBindingPattern(JCBindingPattern tree) {
ResultInfo varInfo = new ResultInfo(KindSelector.TYP, resultInfo.pt, resultInfo.checkContext);
tree.type = tree.var.type = attribTree(tree.var.vartype, env, varInfo);
BindingSymbol v = new BindingSymbol(tree.var.name, tree.var.vartype.type, env.info.scope.owner);
BindingSymbol v = new BindingSymbol(tree.var.mods.flags, tree.var.name, tree.var.vartype.type, env.info.scope.owner);
v.pos = tree.pos;
tree.var.sym = v;
if (chk.checkUnique(tree.var.pos(), v, env.info.scope)) {
chk.checkTransparentVar(tree.var.pos(), v, env.info.scope);
}
annotate.annotateLater(tree.var.mods.annotations, env, v, tree.pos());
annotate.queueScanTreeAndTypeAnnotate(tree.var.vartype, env, v, tree.var.pos());
annotate.flush();
result = tree.type;
@ -5761,7 +5762,7 @@ public class Attr extends JCTree.Visitor {
@Override
public void visitBindingPattern(JCBindingPattern that) {
if (that.var.sym == null) {
that.var.sym = new BindingSymbol(that.var.name, that.var.type, syms.noSymbol);
that.var.sym = new BindingSymbol(0, that.var.name, that.var.type, syms.noSymbol);
that.var.sym.adr = 0;
}
super.visitBindingPattern(that);

View File

@ -490,9 +490,13 @@ public class JavacParser implements Parser {
/** Diagnose a modifier flag from the set, if any. */
protected void checkNoMods(long mods) {
checkNoMods(token.pos, mods);
}
protected void checkNoMods(int pos, long mods) {
if (mods != 0) {
long lowestMod = mods & -mods;
log.error(DiagnosticFlag.SYNTAX, token.pos, Errors.ModNotAllowedHere(Flags.asFlagSet(lowestMod)));
log.error(DiagnosticFlag.SYNTAX, pos, Errors.ModNotAllowedHere(Flags.asFlagSet(lowestMod)));
}
}
@ -932,17 +936,30 @@ public class JavacParser implements Parser {
if (token.kind == INSTANCEOF) {
int pos = token.pos;
nextToken();
int patternPos = token.pos;
JCModifiers mods = optFinal(0);
int typePos = token.pos;
JCExpression type = parseType();
JCExpression type = unannotatedType(false);
JCTree pattern;
if (token.kind == IDENTIFIER) {
checkSourceLevel(token.pos, Feature.PATTERN_MATCHING_IN_INSTANCEOF);
JCModifiers mods = F.at(Position.NOPOS).Modifiers(0);
JCVariableDecl var = toP(F.at(token.pos).VarDef(mods, ident(), type, null));
TreeInfo.getStartPos(var);
pattern = toP(F.at(typePos).BindingPattern(var));
TreeInfo.getStartPos(pattern);
pattern = toP(F.at(patternPos).BindingPattern(var));
} else {
checkNoMods(typePos, mods.flags & ~Flags.DEPRECATED);
if (mods.annotations.nonEmpty()) {
checkSourceLevel(mods.annotations.head.pos, Feature.TYPE_ANNOTATIONS);
List<JCAnnotation> typeAnnos =
mods.annotations
.map(decl -> {
JCAnnotation typeAnno = F.at(decl.pos)
.TypeAnnotation(decl.annotationType,
decl.args);
endPosTable.replaceTree(decl, typeAnno);
return typeAnno;
});
type = insertAnnotationsToMostInner(type, typeAnnos, false);
}
pattern = type;
}
odStack[top] = F.at(pos).TypeTest(odStack[top], pattern);

View File

@ -0,0 +1,152 @@
/*
* 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 8256266
* @summary Verify annotations work correctly on binding variables
* @library /tools/javac/lib
* @modules java.compiler
* jdk.compiler
* jdk.jdeps/com.sun.tools.classfile
* @build JavacTestingAbstractProcessor
* @compile Annotations.java
* @compile -processor Annotations -proc:only Annotations.java
* @run main Annotations
*/
import com.sun.source.tree.InstanceOfTree;
import com.sun.source.util.TreePath;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
import java.util.Set;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeMirror;
import com.sun.source.tree.BindingPatternTree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.TreePathScanner;
import com.sun.source.util.Trees;
import com.sun.tools.classfile.*;
import java.io.InputStream;
import java.util.Arrays;
public class Annotations extends JavacTestingAbstractProcessor {
public static void main(String... args) throws Exception {
new Annotations().run();
}
void run() throws Exception {
InputStream annotationsClass =
Annotations.class.getResourceAsStream("Annotations.class");
ClassFile cf = ClassFile.read(annotationsClass);
for (Method m : cf.methods) {
if ("test".equals(cf.constant_pool.getUTF8Value(m.name_index))) {
Code_attribute codeAttr =
(Code_attribute) m.attributes.map.get(Attribute.Code);
Attribute annoAttr =
codeAttr.attributes.map.get(Attribute.RuntimeInvisibleTypeAnnotations);
RuntimeInvisibleTypeAnnotations_attribute annotations =
(RuntimeInvisibleTypeAnnotations_attribute) annoAttr;
String expected = "[@Annotations$DTA; pos: [LOCAL_VARIABLE, {start_pc = 35, length = 7, index = 1}, pos = -1], " +
"@Annotations$TA; pos: [LOCAL_VARIABLE, {start_pc = 56, length = 7, index = 1}, pos = -1]]";
String actual = Arrays.toString(annotations.annotations);
if (!expected.equals(actual)) {
throw new AssertionError("Unexpected type annotations: " +
actual);
}
}
}
}
private static void test(Object o) {
if (o instanceof @DA String da) {
System.err.println(da);
}
if (o instanceof @DTA String dta) {
System.err.println(dta);
}
if (o instanceof @TA String ta) {
System.err.println(ta);
}
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
Trees trees = Trees.instance(processingEnv);
for (Element root : roundEnv.getRootElements()) {
TreePath tp = trees.getPath(root);
new TreePathScanner<Void, Void>() {
@Override
public Void visitInstanceOf(InstanceOfTree node, Void p) {
BindingPatternTree bpt = (BindingPatternTree) node.getPattern();
VariableTree var = bpt.getVariable();
Element varEl = trees.getElement(new TreePath(getCurrentPath(), var));
String expectedDeclAnnos;
String expectedType;
switch (var.getName().toString()) {
case "da" -> {
expectedDeclAnnos = "@Annotations.DA";
expectedType = "java.lang.String";
}
case "dta" -> {
expectedDeclAnnos = "@Annotations.DTA";
expectedType = "@Annotations.DTA java.lang.String";
}
case "ta" -> {
expectedDeclAnnos = "";
expectedType = "@Annotations.TA java.lang.String";
}
default -> {
throw new AssertionError("Unexpected variable: " + var);
}
}
String declAnnos = varEl.getAnnotationMirrors().toString();
if (!expectedDeclAnnos.equals(declAnnos)) {
throw new AssertionError("Unexpected modifiers: " + declAnnos +
" for: " + var.getName());
}
TypeMirror varType = varEl.asType();
String type = varType.toString();
if (!expectedType.equals(type)) {
throw new AssertionError("Unexpected type: " + type +
" for: " + var.getName());
}
return super.visitInstanceOf(node, p);
}
}.scan(tp.getCompilationUnit(), null);
}
return false;
}
@Target(ElementType.LOCAL_VARIABLE)
@interface DA {}
@Target({ElementType.TYPE_USE, ElementType.LOCAL_VARIABLE})
@interface DTA {}
@Target(ElementType.TYPE_USE)
@interface TA {}
}

View File

@ -185,6 +185,21 @@ public class BindingsTest1 {
String s2 = s;
}
if (o1 instanceof final String s) {
Runnable r1 = new Runnable() {
@Override
public void run() {
s.length();
}
};
r1.run();
Runnable r2 = () -> {
s.length();
};
r2.run();
String s2 = s;
}
boolean result = (o1 instanceof String a1) ? (o1 instanceof String a2) : (!(o1 instanceof String a3));
boolean result2 = (o1 instanceof String a1) ? (o1 instanceof String a2) : (!(switch (0) { default -> false; }));

View File

@ -241,5 +241,11 @@ public class BindingsTest2 {
s.length();
}
}
{
if (o1 instanceof final String s) {
s = "";
}
}
}
}

View File

@ -46,7 +46,8 @@ BindingsTest2.java:212:13: compiler.err.cant.resolve.location: kindname.variable
BindingsTest2.java:221:17: compiler.err.cant.resolve.location: kindname.variable, s, , , (compiler.misc.location: kindname.class, BindingsTest2, null)
BindingsTest2.java:231:17: compiler.err.cant.resolve.location: kindname.variable, s, , , (compiler.misc.location: kindname.class, BindingsTest2, null)
BindingsTest2.java:241:17: compiler.err.cant.resolve.location: kindname.variable, s, , , (compiler.misc.location: kindname.class, BindingsTest2, null)
BindingsTest2.java:247:17: compiler.err.cant.assign.val.to.final.var: s
BindingsTest2.java:135:17: compiler.err.unreachable.stmt
BindingsTest2.java:160:17: compiler.err.unreachable.stmt
BindingsTest2.java:185:17: compiler.err.unreachable.stmt
51 errors
52 errors

View File

@ -0,0 +1,24 @@
/* @test /nodynamiccopyright/
* @bug 8256266
* @summary Binding variables cannot have (non-annotation) modifiers.
* @compile/fail/ref=NoModifiersOnBinding.out -XDrawDiagnostics NoModifiersOnBinding.java
*/
public class NoModifiersOnBinding {
private static void test(Object o) {
if (o instanceof final String) {
System.err.println(s);
}
if (o instanceof /**@deprecated*/ String) {
System.err.println(s);
}
if (o instanceof static String s) {
System.err.println(s);
}
if (o instanceof /**@deprecated*/ String s) {
System.err.println(s);
}
}
}

View File

@ -0,0 +1,3 @@
NoModifiersOnBinding.java:10:32: compiler.err.mod.not.allowed.here: final
NoModifiersOnBinding.java:16:33: compiler.err.mod.not.allowed.here: static
2 errors