8265900: Use pattern matching for instanceof at module jdk.compiler(part 2)

Reviewed-by: mcimadamore
This commit is contained in:
Guoxiong Li 2021-04-26 17:31:45 +00:00 committed by Maurizio Cimadamore
parent 851b219d74
commit 082abbdaf7
29 changed files with 204 additions and 276 deletions

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2005, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -168,8 +168,8 @@ public abstract class AnnoConstruct implements AnnotatedConstruct {
ListBuffer<Attribute.Compound> compounds = new ListBuffer<>(); ListBuffer<Attribute.Compound> compounds = new ListBuffer<>();
if (contained0 != null) { if (contained0 != null) {
for (Attribute a : contained0) for (Attribute a : contained0)
if (a instanceof Attribute.Compound) if (a instanceof Attribute.Compound attributeCompound)
compounds = compounds.append((Attribute.Compound)a); compounds = compounds.append(attributeCompound);
} }
return compounds.toArray(new Attribute.Compound[compounds.size()]); return compounds.toArray(new Attribute.Compound[compounds.size()]);
} }

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -87,8 +87,8 @@ public abstract class Attribute implements AnnotationValue {
} }
@DefinedBy(Api.LANGUAGE_MODEL) @DefinedBy(Api.LANGUAGE_MODEL)
public <R, P> R accept(AnnotationValueVisitor<R, P> v, P p) { public <R, P> R accept(AnnotationValueVisitor<R, P> v, P p) {
if (value instanceof String) if (value instanceof String str)
return v.visitString((String) value, p); return v.visitString(str, p);
if (value instanceof Integer) { if (value instanceof Integer) {
int i = (Integer) value; int i = (Integer) value;
switch (type.getTag()) { switch (type.getTag()) {
@ -198,12 +198,10 @@ public abstract class Attribute implements AnnotationValue {
if (values.size() == 1) { if (values.size() == 1) {
Pair<MethodSymbol, Attribute> val = values.get(0); Pair<MethodSymbol, Attribute> val = values.get(0);
if (val.fst.getSimpleName().contentEquals("value") if (val.fst.getSimpleName().contentEquals("value")
&& val.snd instanceof Array) { && val.snd instanceof Array arr
Array arr = (Array) val.snd; && arr.values.length != 0
if (arr.values.length != 0 && arr.values[0] instanceof Attribute.TypeCompound compound)
&& arr.values[0] instanceof Attribute.TypeCompound) return compound;
return (Attribute.TypeCompound) arr.values[0];
}
} }
return null; return null;
} }

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 1999, 2016, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -209,12 +209,11 @@ public class ClassFinder {
// Temporary, until more info is available from the module system. // Temporary, until more info is available from the module system.
boolean useCtProps; boolean useCtProps;
JavaFileManager fm = context.get(JavaFileManager.class); JavaFileManager fm = context.get(JavaFileManager.class);
if (fm instanceof DelegatingJavaFileManager) { if (fm instanceof DelegatingJavaFileManager delegatingJavaFileManager) {
fm = ((DelegatingJavaFileManager) fm).getBaseFileManager(); fm = delegatingJavaFileManager.getBaseFileManager();
} }
if (fm instanceof JavacFileManager) { if (fm instanceof JavacFileManager javacFileManager) {
JavacFileManager jfm = (JavacFileManager) fm; useCtProps = javacFileManager.isDefaultBootClassPath() && javacFileManager.isSymbolFileEnabled();
useCtProps = jfm.isDefaultBootClassPath() && jfm.isSymbolFileEnabled();
} else if (fm.getClass().getName().equals("com.sun.tools.sjavac.comp.SmartFileManager")) { } else if (fm.getClass().getName().equals("com.sun.tools.sjavac.comp.SmartFileManager")) {
useCtProps = !options.isSet("ignore.symbol.file"); useCtProps = !options.isSet("ignore.symbol.file");
} else { } else {
@ -642,27 +641,26 @@ public class ClassFinder {
if (verbose && verbosePath) { if (verbose && verbosePath) {
verbosePath = false; // print once per compile verbosePath = false; // print once per compile
if (fileManager instanceof StandardJavaFileManager) { if (fileManager instanceof StandardJavaFileManager standardJavaFileManager) {
StandardJavaFileManager fm = (StandardJavaFileManager)fileManager;
if (haveSourcePath && wantSourceFiles) { if (haveSourcePath && wantSourceFiles) {
List<Path> path = List.nil(); List<Path> path = List.nil();
for (Path sourcePath : fm.getLocationAsPaths(SOURCE_PATH)) { for (Path sourcePath : standardJavaFileManager.getLocationAsPaths(SOURCE_PATH)) {
path = path.prepend(sourcePath); path = path.prepend(sourcePath);
} }
log.printVerbose("sourcepath", path.reverse().toString()); log.printVerbose("sourcepath", path.reverse().toString());
} else if (wantSourceFiles) { } else if (wantSourceFiles) {
List<Path> path = List.nil(); List<Path> path = List.nil();
for (Path classPath : fm.getLocationAsPaths(CLASS_PATH)) { for (Path classPath : standardJavaFileManager.getLocationAsPaths(CLASS_PATH)) {
path = path.prepend(classPath); path = path.prepend(classPath);
} }
log.printVerbose("sourcepath", path.reverse().toString()); log.printVerbose("sourcepath", path.reverse().toString());
} }
if (wantClassFiles) { if (wantClassFiles) {
List<Path> path = List.nil(); List<Path> path = List.nil();
for (Path platformPath : fm.getLocationAsPaths(PLATFORM_CLASS_PATH)) { for (Path platformPath : standardJavaFileManager.getLocationAsPaths(PLATFORM_CLASS_PATH)) {
path = path.prepend(platformPath); path = path.prepend(platformPath);
} }
for (Path classPath : fm.getLocationAsPaths(CLASS_PATH)) { for (Path classPath : standardJavaFileManager.getLocationAsPaths(CLASS_PATH)) {
path = path.prepend(classPath); path = path.prepend(classPath);
} }
log.printVerbose("classpath", path.reverse().toString()); log.printVerbose("classpath", path.reverse().toString());

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2009, 2019, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2009, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -263,11 +263,9 @@ public abstract class Directive implements ModuleElement.Directive {
// TODO: delete? // TODO: delete?
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (!(obj instanceof ProvidesDirective)) { return (obj instanceof ProvidesDirective directive)
return false; && service == directive.service
} && impls.equals(directive.impls);
ProvidesDirective other = (ProvidesDirective)obj;
return service == other.service && impls.equals(other.impls);
} }
// TODO: delete? // TODO: delete?
@ -359,11 +357,8 @@ public abstract class Directive implements ModuleElement.Directive {
// TODO: delete? // TODO: delete?
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (!(obj instanceof UsesDirective)) { return (obj instanceof UsesDirective directive)
return false; && service == directive.service;
}
UsesDirective other = (UsesDirective)obj;
return service == other.service;
} }
// TODO: delete? // TODO: delete?

@ -753,8 +753,9 @@ public abstract class Scope {
} }
protected Scope finalizeSingleScope(Scope impScope) { protected Scope finalizeSingleScope(Scope impScope) {
if (impScope instanceof FilterImportScope && impScope.owner.kind == Kind.TYP && if (impScope instanceof FilterImportScope filterImportScope
((FilterImportScope) impScope).isStaticallyImported()) { && impScope.owner.kind == Kind.TYP
&& filterImportScope.isStaticallyImported()) {
WriteableScope finalized = WriteableScope.create(impScope.owner); WriteableScope finalized = WriteableScope.create(impScope.owner);
for (Symbol sym : impScope.getSymbols()) { for (Symbol sym : impScope.getSymbols()) {

@ -1420,13 +1420,12 @@ public abstract class Symbol extends AnnoConstruct implements PoolConstant, Elem
@DefinedBy(Api.LANGUAGE_MODEL) @DefinedBy(Api.LANGUAGE_MODEL)
public List<Type> getInterfaces() { public List<Type> getInterfaces() {
apiComplete(); apiComplete();
if (type instanceof ClassType) { if (type instanceof ClassType classType) {
ClassType t = (ClassType)type; if (classType.interfaces_field == null) // FIXME: shouldn't be null
if (t.interfaces_field == null) // FIXME: shouldn't be null classType.interfaces_field = List.nil();
t.interfaces_field = List.nil(); if (classType.all_interfaces_field != null)
if (t.all_interfaces_field != null) return Type.getModelTypes(classType.all_interfaces_field);
return Type.getModelTypes(t.all_interfaces_field); return classType.interfaces_field;
return t.interfaces_field;
} else { } else {
return List.nil(); return List.nil();
} }
@ -1435,14 +1434,13 @@ public abstract class Symbol extends AnnoConstruct implements PoolConstant, Elem
@DefinedBy(Api.LANGUAGE_MODEL) @DefinedBy(Api.LANGUAGE_MODEL)
public Type getSuperclass() { public Type getSuperclass() {
apiComplete(); apiComplete();
if (type instanceof ClassType) { if (type instanceof ClassType classType) {
ClassType t = (ClassType)type; if (classType.supertype_field == null) // FIXME: shouldn't be null
if (t.supertype_field == null) // FIXME: shouldn't be null classType.supertype_field = Type.noType;
t.supertype_field = Type.noType;
// An interface has no superclass; its supertype is Object. // An interface has no superclass; its supertype is Object.
return t.isInterface() return classType.isInterface()
? Type.noType ? Type.noType
: t.supertype_field.getModelType(); : classType.supertype_field.getModelType();
} else { } else {
return Type.noType; return Type.noType;
} }
@ -1585,15 +1583,14 @@ public abstract class Symbol extends AnnoConstruct implements PoolConstant, Elem
erasure_field = null; erasure_field = null;
members_field = null; members_field = null;
flags_field = 0; flags_field = 0;
if (type instanceof ClassType) { if (type instanceof ClassType classType) {
ClassType t = (ClassType)type; classType.setEnclosingType(Type.noType);
t.setEnclosingType(Type.noType); classType.rank_field = -1;
t.rank_field = -1; classType.typarams_field = null;
t.typarams_field = null; classType.allparams_field = null;
t.allparams_field = null; classType.supertype_field = null;
t.supertype_field = null; classType.interfaces_field = null;
t.interfaces_field = null; classType.all_interfaces_field = null;
t.all_interfaces_field = null;
} }
clearAnnotationMetadata(); clearAnnotationMetadata();
} }
@ -1754,13 +1751,12 @@ public abstract class Symbol extends AnnoConstruct implements PoolConstant, Elem
if (data == ElementKind.EXCEPTION_PARAMETER || if (data == ElementKind.EXCEPTION_PARAMETER ||
data == ElementKind.RESOURCE_VARIABLE) { data == ElementKind.RESOURCE_VARIABLE) {
return null; return null;
} else if (data instanceof Callable<?>) { } else if (data instanceof Callable<?> callableData) {
// In this case, this is a final variable, with an as // In this case, this is a final variable, with an as
// yet unevaluated initializer. // yet unevaluated initializer.
Callable<?> eval = (Callable<?>)data;
data = null; // to make sure we don't evaluate this twice. data = null; // to make sure we don't evaluate this twice.
try { try {
data = eval.call(); data = callableData.call();
} catch (Exception ex) { } catch (Exception ex) {
throw new AssertionError(ex); throw new AssertionError(ex);
} }

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2012, 2020, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2012, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -276,8 +276,7 @@ public class SymbolMetadata {
if (attrCompound.isSynthesized() && !attrCompound.values.isEmpty()) { if (attrCompound.isSynthesized() && !attrCompound.values.isEmpty()) {
Pair<Symbol.MethodSymbol, Attribute> val = attrCompound.values.get(0); Pair<Symbol.MethodSymbol, Attribute> val = attrCompound.values.get(0);
if (val.fst.getSimpleName().contentEquals("value") && if (val.fst.getSimpleName().contentEquals("value") &&
val.snd instanceof Attribute.Array) { val.snd instanceof Attribute.Array arr) {
Attribute.Array arr = (Attribute.Array) val.snd;
if (arr.values.length != 0 if (arr.values.length != 0
&& arr.values[0] instanceof Attribute.Compound && arr.values[0] instanceof Attribute.Compound
&& arr.values[0].type == compound.type) { && arr.values[0].type == compound.type) {

@ -1359,13 +1359,8 @@ public abstract class Type extends AnnoConstruct implements TypeMirror, PoolCons
@Override @DefinedBy(Api.LANGUAGE_MODEL) @Override @DefinedBy(Api.LANGUAGE_MODEL)
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (obj instanceof ArrayType) { return (obj instanceof ArrayType arrayType)
ArrayType that = (ArrayType)obj; && (this == arrayType || elemtype.equals(arrayType.elemtype));
return this == that ||
elemtype.equals(that.elemtype);
}
return false;
} }
@DefinedBy(Api.LANGUAGE_MODEL) @DefinedBy(Api.LANGUAGE_MODEL)

@ -103,11 +103,9 @@ public class TypeAnnotationPosition {
@Override @Override
public boolean equals(Object other) { public boolean equals(Object other) {
if (! (other instanceof TypePathEntry)) { return (other instanceof TypePathEntry entry)
return false; && this.tag == entry.tag
} && this.arg == entry.arg;
TypePathEntry tpe = (TypePathEntry) other;
return this.tag == tpe.tag && this.arg == tpe.arg;
} }
@Override @Override

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2009, 2020, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2009, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -155,11 +155,11 @@ public class TypeAnnotations {
} }
Attribute atValue = atTarget.member(names.value); Attribute atValue = atTarget.member(names.value);
if (!(atValue instanceof Attribute.Array)) { if (!(atValue instanceof Attribute.Array arrayVal)) {
return null; return null;
} }
List<Attribute> targets = ((Array)atValue).getValue(); List<Attribute> targets = arrayVal.getValue();
if (targets.stream().anyMatch(a -> !(a instanceof Attribute.Enum))) { if (targets.stream().anyMatch(a -> !(a instanceof Attribute.Enum))) {
return null; return null;
} }

@ -3161,12 +3161,9 @@ public class Types {
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (obj instanceof Entry) { return (obj instanceof Entry entry)
Entry e = (Entry)obj; && entry.msym == msym
return e.msym == msym && isSameType(site, e.site); && isSameType(site, entry.site);
} else {
return false;
}
} }
@Override @Override
@ -3850,10 +3847,8 @@ public class Types {
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (!(obj instanceof TypePair)) return (obj instanceof TypePair typePair)
return false; && isSameType(t1, typePair.t1)
TypePair typePair = (TypePair)obj;
return isSameType(t1, typePair.t1)
&& isSameType(t2, typePair.t2); && isSameType(t2, typePair.t2);
} }
} }
@ -4877,8 +4872,8 @@ public class Types {
} }
public boolean equals(Object obj) { public boolean equals(Object obj) {
return (obj instanceof UniqueType) && return (obj instanceof UniqueType uniqueType) &&
types.isSameType(type, ((UniqueType)obj).type); types.isSameType(type, uniqueType.type);
} }
public String toString() { public String toString() {
@ -5032,8 +5027,8 @@ public class Types {
Attribute.Compound c = sym.attribute(syms.retentionType.tsym); Attribute.Compound c = sym.attribute(syms.retentionType.tsym);
if (c != null) { if (c != null) {
Attribute value = c.member(names.value); Attribute value = c.member(names.value);
if (value != null && value instanceof Attribute.Enum) { if (value != null && value instanceof Attribute.Enum attributeEnum) {
Name levelName = ((Attribute.Enum)value).value.name; Name levelName = attributeEnum.value.name;
if (levelName == names.SOURCE) vis = RetentionPolicy.SOURCE; if (levelName == names.SOURCE) vis = RetentionPolicy.SOURCE;
else if (levelName == names.CLASS) vis = RetentionPolicy.CLASS; else if (levelName == names.CLASS) vis = RetentionPolicy.CLASS;
else if (levelName == names.RUNTIME) vis = RetentionPolicy.RUNTIME; else if (levelName == names.RUNTIME) vis = RetentionPolicy.RUNTIME;

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -404,13 +404,9 @@ public class Annotate {
} }
//where: //where:
private boolean isAttributeTrue(Attribute attr) { private boolean isAttributeTrue(Attribute attr) {
if (attr instanceof Attribute.Constant) { return (attr instanceof Attribute.Constant constant)
Attribute.Constant v = (Attribute.Constant) attr; && constant.type == syms.booleanType
if (v.type == syms.booleanType && ((Integer) v.value) != 0) { && ((Integer) constant.value) != 0;
return true;
}
}
return false;
} }
/** /**
@ -447,7 +443,7 @@ public class Annotate {
{ {
// The attribute might have been entered if it is Target or Repeatable // The attribute might have been entered if it is Target or Repeatable
// Because TreeCopier does not copy type, redo this if type is null // Because TreeCopier does not copy type, redo this if type is null
if (a.attribute == null || a.type == null || !(a.attribute instanceof Attribute.TypeCompound)) { if (a.attribute == null || a.type == null || !(a.attribute instanceof Attribute.TypeCompound typeCompound)) {
// Create a new TypeCompound // Create a new TypeCompound
List<Pair<MethodSymbol,Attribute>> elems = List<Pair<MethodSymbol,Attribute>> elems =
attributeAnnotationValues(a, expectedAnnotationType, env); attributeAnnotationValues(a, expectedAnnotationType, env);
@ -458,7 +454,7 @@ public class Annotate {
return tc; return tc;
} else { } else {
// Use an existing TypeCompound // Use an existing TypeCompound
return (Attribute.TypeCompound)a.attribute; return typeCompound;
} }
} }
@ -911,12 +907,12 @@ public class Annotate {
log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl)); log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl));
return null; return null;
} }
if (!(p.snd instanceof Attribute.Class)) { // check that the value of "value" is an Attribute.Class if (!(p.snd instanceof Attribute.Class attributeClass)) { // check that the value of "value" is an Attribute.Class
log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl)); log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl));
return null; return null;
} }
return ((Attribute.Class)p.snd).getValue(); return attributeClass.getValue();
} }
/* Validate that the suggested targetContainerType Type is a valid /* Validate that the suggested targetContainerType Type is a valid

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -751,12 +751,9 @@ public class ArgumentAttr extends JCTree.Visitor {
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (obj instanceof UniquePos) { return (obj instanceof UniquePos uniquePos)
UniquePos that = (UniquePos)obj; && pos == uniquePos.pos
return pos == that.pos && source == that.source; && source == uniquePos.source;
} else {
return false;
}
} }
@Override @Override

@ -430,8 +430,8 @@ public class Attr extends JCTree.Visitor {
} catch (BreakAttr b) { } catch (BreakAttr b) {
return b.env; return b.env;
} catch (AssertionError ae) { } catch (AssertionError ae) {
if (ae.getCause() instanceof BreakAttr) { if (ae.getCause() instanceof BreakAttr breakAttr) {
return ((BreakAttr)(ae.getCause())).env; return breakAttr.env;
} else { } else {
throw ae; throw ae;
} }

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2020, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -243,8 +243,8 @@ public class AttrRecover {
break; break;
} }
for (Object a : d.getArgs()) { for (Object a : d.getArgs()) {
if (a instanceof JCDiagnostic) { if (a instanceof JCDiagnostic diagnostic) {
diags = diags.prepend((JCDiagnostic) a); diags = diags.prepend(diagnostic);
} }
} }
} }

@ -317,12 +317,12 @@ public class Check {
Type typeTagError(DiagnosticPosition pos, JCDiagnostic required, Object found) { Type typeTagError(DiagnosticPosition pos, JCDiagnostic required, Object found) {
// this error used to be raised by the parser, // this error used to be raised by the parser,
// but has been delayed to this point: // but has been delayed to this point:
if (found instanceof Type && ((Type)found).hasTag(VOID)) { if (found instanceof Type type && type.hasTag(VOID)) {
log.error(pos, Errors.IllegalStartOfType); log.error(pos, Errors.IllegalStartOfType);
return syms.errType; return syms.errType;
} }
log.error(pos, Errors.TypeFoundReq(found, required)); log.error(pos, Errors.TypeFoundReq(found, required));
return types.createErrorType(found instanceof Type ? (Type)found : syms.errType); return types.createErrorType(found instanceof Type type ? type : syms.errType);
} }
/** Report an error that symbol cannot be referenced before super /** Report an error that symbol cannot be referenced before super
@ -1337,8 +1337,7 @@ public class Check {
@Override @Override
public void visitVarDef(JCVariableDecl tree) { public void visitVarDef(JCVariableDecl tree) {
if ((tree.mods.flags & ENUM) != 0) { if ((tree.mods.flags & ENUM) != 0) {
if (tree.init instanceof JCNewClass && if (tree.init instanceof JCNewClass newClass && newClass.def != null) {
((JCNewClass) tree.init).def != null) {
specialized = true; specialized = true;
} }
} }
@ -3168,11 +3167,10 @@ public class Check {
} else { } else {
containerTargets = new HashSet<>(); containerTargets = new HashSet<>();
for (Attribute app : containerTarget.values) { for (Attribute app : containerTarget.values) {
if (!(app instanceof Attribute.Enum)) { if (!(app instanceof Attribute.Enum attributeEnum)) {
continue; // recovery continue; // recovery
} }
Attribute.Enum e = (Attribute.Enum)app; containerTargets.add(attributeEnum.value.name);
containerTargets.add(e.value.name);
} }
} }
@ -3183,11 +3181,10 @@ public class Check {
} else { } else {
containedTargets = new HashSet<>(); containedTargets = new HashSet<>();
for (Attribute app : containedTarget.values) { for (Attribute app : containedTarget.values) {
if (!(app instanceof Attribute.Enum)) { if (!(app instanceof Attribute.Enum attributeEnum)) {
continue; // recovery continue; // recovery
} }
Attribute.Enum e = (Attribute.Enum)app; containedTargets.add(attributeEnum.value.name);
containedTargets.add(e.value.name);
} }
} }
@ -3311,11 +3308,10 @@ public class Check {
targets = new Name[arr.values.length]; targets = new Name[arr.values.length];
for (int i=0; i<arr.values.length; ++i) { for (int i=0; i<arr.values.length; ++i) {
Attribute app = arr.values[i]; Attribute app = arr.values[i];
if (!(app instanceof Attribute.Enum)) { if (!(app instanceof Attribute.Enum attributeEnum)) {
return new Name[0]; return new Name[0];
} }
Attribute.Enum e = (Attribute.Enum) app; targets[i] = attributeEnum.value.name;
targets[i] = e.value.name;
} }
} }
return targets; return targets;
@ -3343,12 +3339,11 @@ public class Check {
targets = new Name[arr.values.length]; targets = new Name[arr.values.length];
for (int i=0; i<arr.values.length; ++i) { for (int i=0; i<arr.values.length; ++i) {
Attribute app = arr.values[i]; Attribute app = arr.values[i];
if (!(app instanceof Attribute.Enum)) { if (!(app instanceof Attribute.Enum attributeEnum)) {
// recovery // recovery
return Optional.empty(); return Optional.empty();
} }
Attribute.Enum e = (Attribute.Enum) app; targets[i] = attributeEnum.value.name;
targets[i] = e.value.name;
} }
} }
for (Name target : targets) { for (Name target : targets) {
@ -3412,8 +3407,7 @@ public class Check {
Attribute.Compound atTarget = s.getAnnotationTypeMetadata().getTarget(); Attribute.Compound atTarget = s.getAnnotationTypeMetadata().getTarget();
if (atTarget == null) return null; // ok, is applicable if (atTarget == null) return null; // ok, is applicable
Attribute atValue = atTarget.member(names.value); Attribute atValue = atTarget.member(names.value);
if (!(atValue instanceof Attribute.Array)) return null; // error recovery return (atValue instanceof Attribute.Array attributeArray) ? attributeArray : null;
return (Attribute.Array) atValue;
} }
public final Name[] dfltTargetMeta; public final Name[] dfltTargetMeta;

@ -749,11 +749,10 @@ public class Flow {
ListBuffer<PendingExit> prevPendingExits = pendingExits; ListBuffer<PendingExit> prevPendingExits = pendingExits;
pendingExits = new ListBuffer<>(); pendingExits = new ListBuffer<>();
for (JCTree resource : tree.resources) { for (JCTree resource : tree.resources) {
if (resource instanceof JCVariableDecl) { if (resource instanceof JCVariableDecl variableDecl) {
JCVariableDecl vdecl = (JCVariableDecl) resource; visitVarDef(variableDecl);
visitVarDef(vdecl); } else if (resource instanceof JCExpression expression) {
} else if (resource instanceof JCExpression) { scan(expression);
scan((JCExpression) resource);
} else { } else {
throw new AssertionError(tree); // parser error throw new AssertionError(tree); // parser error
} }
@ -943,8 +942,7 @@ public class Flow {
for (PendingExit exit = pendingExits.next(); for (PendingExit exit = pendingExits.next();
exit != null; exit != null;
exit = pendingExits.next()) { exit = pendingExits.next()) {
if (exit instanceof ThrownPendingExit) { if (exit instanceof ThrownPendingExit thrownExit) {
ThrownPendingExit thrownExit = (ThrownPendingExit) exit;
if (classDef != null && if (classDef != null &&
classDef.pos == exit.tree.pos) { classDef.pos == exit.tree.pos) {
log.error(exit.tree.pos(), log.error(exit.tree.pos(),
@ -1222,11 +1220,10 @@ public class Flow {
ListBuffer<PendingExit> prevPendingExits = pendingExits; ListBuffer<PendingExit> prevPendingExits = pendingExits;
pendingExits = new ListBuffer<>(); pendingExits = new ListBuffer<>();
for (JCTree resource : tree.resources) { for (JCTree resource : tree.resources) {
if (resource instanceof JCVariableDecl) { if (resource instanceof JCVariableDecl variableDecl) {
JCVariableDecl vdecl = (JCVariableDecl) resource; visitVarDef(variableDecl);
visitVarDef(vdecl); } else if (resource instanceof JCExpression expression) {
} else if (resource instanceof JCExpression) { scan(expression);
scan((JCExpression) resource);
} else { } else {
throw new AssertionError(tree); // parser error throw new AssertionError(tree); // parser error
} }
@ -2432,13 +2429,12 @@ public class Flow {
final Bits initsTry = new Bits(inits); final Bits initsTry = new Bits(inits);
uninitsTry.assign(uninits); uninitsTry.assign(uninits);
for (JCTree resource : tree.resources) { for (JCTree resource : tree.resources) {
if (resource instanceof JCVariableDecl) { if (resource instanceof JCVariableDecl variableDecl) {
JCVariableDecl vdecl = (JCVariableDecl) resource; visitVarDef(variableDecl);
visitVarDef(vdecl); unrefdResources.enter(variableDecl.sym);
unrefdResources.enter(vdecl.sym); resourceVarDecls.append(variableDecl);
resourceVarDecls.append(vdecl); } else if (resource instanceof JCExpression expression) {
} else if (resource instanceof JCExpression) { scanExpr(expression);
scanExpr((JCExpression) resource);
} else { } else {
throw new AssertionError(tree); // parser error throw new AssertionError(tree); // parser error
} }
@ -2495,9 +2491,9 @@ public class Flow {
// versus finally! // versus finally!
while (exits.nonEmpty()) { while (exits.nonEmpty()) {
PendingExit exit = exits.next(); PendingExit exit = exits.next();
if (exit instanceof AssignPendingExit) { if (exit instanceof AssignPendingExit assignPendingExit) {
((AssignPendingExit) exit).exit_inits.orSet(inits); assignPendingExit.exit_inits.orSet(inits);
((AssignPendingExit) exit).exit_uninits.andSet(uninits); assignPendingExit.exit_uninits.andSet(uninits);
} }
pendingExits.append(exit); pendingExits.append(exit);
} }

@ -1202,14 +1202,10 @@ public class Infer {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (!(o instanceof IncorporationBinaryOp)) { return (o instanceof IncorporationBinaryOp incorporationBinaryOp)
return false; && opKind == incorporationBinaryOp.opKind
} else { && types.isSameType(op1, incorporationBinaryOp.op1)
IncorporationBinaryOp that = (IncorporationBinaryOp)o; && types.isSameType(op2, incorporationBinaryOp.op2);
return opKind == that.opKind &&
types.isSameType(op1, that.op1) &&
types.isSameType(op2, that.op2);
}
} }
@Override @Override

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2010, 2020, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2010, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -197,12 +197,9 @@ public class LambdaToMethod extends TreeTranslator {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (!(o instanceof DedupedLambda)) { return (o instanceof DedupedLambda dedupedLambda)
return false; && types.isSameType(symbol.asType(), dedupedLambda.symbol.asType())
} && new TreeDiffer(symbol.params(), dedupedLambda.symbol.params()).scan(tree, dedupedLambda.tree);
DedupedLambda that = (DedupedLambda) o;
return types.isSameType(symbol.asType(), that.symbol.asType())
&& new TreeDiffer(symbol.params(), that.symbol.params()).scan(tree, that.tree);
} }
} }
@ -1558,12 +1555,9 @@ public class LambdaToMethod extends TreeTranslator {
@Override @Override
public void visitVarDef(JCVariableDecl tree) { public void visitVarDef(JCVariableDecl tree) {
TranslationContext<?> context = context(); TranslationContext<?> context = context();
LambdaTranslationContext ltc = (context != null && context instanceof LambdaTranslationContext)? if (context != null && context instanceof LambdaTranslationContext lambdaContext) {
(LambdaTranslationContext)context :
null;
if (ltc != null) {
if (frameStack.head.tree.hasTag(LAMBDA)) { if (frameStack.head.tree.hasTag(LAMBDA)) {
ltc.addSymbol(tree.sym, LOCAL_VAR); lambdaContext.addSymbol(tree.sym, LOCAL_VAR);
} }
// Check for type variables (including as type arguments). // Check for type variables (including as type arguments).
// If they occur within class nested in a lambda, mark for erasure // If they occur within class nested in a lambda, mark for erasure
@ -1767,10 +1761,7 @@ public class LambdaToMethod extends TreeTranslator {
* set of nodes that select `this' (qualified this) * set of nodes that select `this' (qualified this)
*/ */
private boolean lambdaFieldAccessFilter(JCFieldAccess fAccess) { private boolean lambdaFieldAccessFilter(JCFieldAccess fAccess) {
LambdaTranslationContext lambdaContext = return (context instanceof LambdaTranslationContext lambdaContext)
context instanceof LambdaTranslationContext ?
(LambdaTranslationContext) context : null;
return lambdaContext != null
&& !fAccess.sym.isStatic() && !fAccess.sym.isStatic()
&& fAccess.name == names._this && fAccess.name == names._this
&& (fAccess.sym.owner.kind == TYP) && (fAccess.sym.owner.kind == TYP)

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 1999, 2020, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -1603,11 +1603,10 @@ public class Lower extends TreeTranslator {
JCTree resource = resources.head; JCTree resource = resources.head;
JCExpression resourceUse; JCExpression resourceUse;
boolean resourceNonNull; boolean resourceNonNull;
if (resource instanceof JCVariableDecl) { if (resource instanceof JCVariableDecl variableDecl) {
JCVariableDecl var = (JCVariableDecl) resource; resourceUse = make.Ident(variableDecl.sym).setType(resource.type);
resourceUse = make.Ident(var.sym).setType(resource.type); resourceNonNull = variableDecl.init != null && TreeInfo.skipParens(variableDecl.init).hasTag(NEWCLASS);
resourceNonNull = var.init != null && TreeInfo.skipParens(var.init).hasTag(NEWCLASS); stats.add(variableDecl);
stats.add(var);
} else { } else {
Assert.check(resource instanceof JCExpression); Assert.check(resource instanceof JCExpression);
VarSymbol syntheticTwrVar = VarSymbol syntheticTwrVar =

@ -1599,12 +1599,12 @@ public class Resolve {
case ABSENT_MTH: case ABSENT_MTH:
return new InapplicableSymbolError(currentResolutionContext); return new InapplicableSymbolError(currentResolutionContext);
case HIDDEN: case HIDDEN:
if (bestSoFar instanceof AccessError) { if (bestSoFar instanceof AccessError accessError) {
// Add the JCDiagnostic of previous AccessError to the currentResolutionContext // Add the JCDiagnostic of previous AccessError to the currentResolutionContext
// and construct InapplicableSymbolsError. // and construct InapplicableSymbolsError.
// Intentionally fallthrough. // Intentionally fallthrough.
currentResolutionContext.addInapplicableCandidate(((AccessError) bestSoFar).sym, currentResolutionContext.addInapplicableCandidate(accessError.sym,
((AccessError) bestSoFar).getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT, null, null, site, null, argtypes, typeargtypes)); accessError.getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT, null, null, site, null, argtypes, typeargtypes));
} else { } else {
return bestSoFar; return bestSoFar;
} }
@ -1631,11 +1631,11 @@ public class Resolve {
} else if (bestSoFar.kind == WRONG_MTHS) { } else if (bestSoFar.kind == WRONG_MTHS) {
// Add the JCDiagnostic of current AccessError to the currentResolutionContext // Add the JCDiagnostic of current AccessError to the currentResolutionContext
currentResolutionContext.addInapplicableCandidate(sym, curDiagnostic); currentResolutionContext.addInapplicableCandidate(sym, curDiagnostic);
} else if (bestSoFar.kind == HIDDEN && bestSoFar instanceof AccessError) { } else if (bestSoFar.kind == HIDDEN && bestSoFar instanceof AccessError accessError) {
// Add the JCDiagnostics of previous and current AccessError to the currentResolutionContext // Add the JCDiagnostics of previous and current AccessError to the currentResolutionContext
// and construct InapplicableSymbolsError. // and construct InapplicableSymbolsError.
currentResolutionContext.addInapplicableCandidate(((AccessError) bestSoFar).sym, currentResolutionContext.addInapplicableCandidate(accessError.sym,
((AccessError) bestSoFar).getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT, null, null, site, null, argtypes, typeargtypes)); accessError.getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT, null, null, site, null, argtypes, typeargtypes));
currentResolutionContext.addInapplicableCandidate(sym, curDiagnostic); currentResolutionContext.addInapplicableCandidate(sym, curDiagnostic);
bestSoFar = new InapplicableSymbolsError(currentResolutionContext); bestSoFar = new InapplicableSymbolsError(currentResolutionContext);
} }
@ -4841,10 +4841,10 @@ public class Resolve {
} }
BiPredicate<Object, List<Type>> containsPredicate = (o, ts) -> { BiPredicate<Object, List<Type>> containsPredicate = (o, ts) -> {
if (o instanceof Type) { if (o instanceof Type type) {
return ((Type)o).containsAny(ts); return type.containsAny(ts);
} else if (o instanceof JCDiagnostic) { } else if (o instanceof JCDiagnostic diagnostic) {
return containsAny((JCDiagnostic)o, ts); return containsAny(diagnostic, ts);
} else { } else {
return false; return false;
} }

@ -829,7 +829,7 @@ public class ClassReader {
// ignore ConstantValue attribute if type is not primitive or String // ignore ConstantValue attribute if type is not primitive or String
return; return;
} }
if (v instanceof Integer && !var.type.getTag().checkRange((Integer) v)) { if (v instanceof Integer intVal && !var.type.getTag().checkRange(intVal)) {
throw badClassFile("bad.constant.range", v, var, var.type); throw badClassFile("bad.constant.range", v, var, var.type);
} }
var.setData(v); var.setData(v);
@ -1429,9 +1429,8 @@ public class ClassReader {
else if (proxy.type.tsym.flatName() == syms.profileType.tsym.flatName()) { else if (proxy.type.tsym.flatName() == syms.profileType.tsym.flatName()) {
if (profile != Profile.DEFAULT) { if (profile != Profile.DEFAULT) {
for (Pair<Name, Attribute> v : proxy.values) { for (Pair<Name, Attribute> v : proxy.values) {
if (v.fst == names.value && v.snd instanceof Attribute.Constant) { if (v.fst == names.value && v.snd instanceof Attribute.Constant constant) {
Attribute.Constant c = (Attribute.Constant)v.snd; if (constant.type == syms.intType && ((Integer) constant.value) > profile.value) {
if (c.type == syms.intType && ((Integer)c.value) > profile.value) {
sym.flags_field |= NOT_IN_PROFILE; sym.flags_field |= NOT_IN_PROFILE;
} }
} }
@ -1460,9 +1459,8 @@ public class ClassReader {
//where: //where:
private void setFlagIfAttributeTrue(CompoundAnnotationProxy proxy, Symbol sym, Name attribute, long flag) { private void setFlagIfAttributeTrue(CompoundAnnotationProxy proxy, Symbol sym, Name attribute, long flag) {
for (Pair<Name, Attribute> v : proxy.values) { for (Pair<Name, Attribute> v : proxy.values) {
if (v.fst == attribute && v.snd instanceof Attribute.Constant) { if (v.fst == attribute && v.snd instanceof Attribute.Constant constant) {
Attribute.Constant c = (Attribute.Constant)v.snd; if (constant.type == syms.booleanType && ((Integer) constant.value) != 0) {
if (c.type == syms.booleanType && ((Integer)c.value) != 0) {
sym.flags_field |= flag; sym.flags_field |= flag;
} }
} }
@ -2051,12 +2049,12 @@ public class ClassReader {
} }
Type resolvePossibleProxyType(Type t) { Type resolvePossibleProxyType(Type t) {
if (t instanceof ProxyType) { if (t instanceof ProxyType proxyType) {
Assert.check(requestingOwner.owner.kind == MDL); Assert.check(requestingOwner.owner.kind == MDL);
ModuleSymbol prevCurrentModule = currentModule; ModuleSymbol prevCurrentModule = currentModule;
currentModule = (ModuleSymbol) requestingOwner.owner; currentModule = (ModuleSymbol) requestingOwner.owner;
try { try {
return ((ProxyType) t).resolve(); return proxyType.resolve();
} finally { } finally {
currentModule = prevCurrentModule; currentModule = prevCurrentModule;
} }
@ -2125,9 +2123,8 @@ public class ClassReader {
if (attr.type.tsym == syms.deprecatedType.tsym) { if (attr.type.tsym == syms.deprecatedType.tsym) {
sym.flags_field |= (DEPRECATED | DEPRECATED_ANNOTATION); sym.flags_field |= (DEPRECATED | DEPRECATED_ANNOTATION);
Attribute forRemoval = attr.member(names.forRemoval); Attribute forRemoval = attr.member(names.forRemoval);
if (forRemoval instanceof Attribute.Constant) { if (forRemoval instanceof Attribute.Constant constant) {
Attribute.Constant c = (Attribute.Constant) forRemoval; if (constant.type == syms.booleanType && ((Integer) constant.value) != 0) {
if (c.type == syms.booleanType && ((Integer) c.value) != 0) {
sym.flags_field |= DEPRECATED_REMOVAL; sym.flags_field |= DEPRECATED_REMOVAL;
} }
} }
@ -2811,12 +2808,8 @@ public class ClassReader {
public boolean equals(Object other) { public boolean equals(Object other) {
if (this == other) if (this == other)
return true; return true;
return (other instanceof SourceFileObject sourceFileObject)
if (!(other instanceof SourceFileObject)) && name.equals(sourceFileObject.name);
return false;
SourceFileObject o = (SourceFileObject) other;
return name.equals(o.name);
} }
@Override @Override

@ -530,8 +530,8 @@ public class Gen extends JCTree.Visitor {
private void checkStringConstant(DiagnosticPosition pos, Object constValue) { private void checkStringConstant(DiagnosticPosition pos, Object constValue) {
if (nerrs != 0 || // only complain about a long string once if (nerrs != 0 || // only complain about a long string once
constValue == null || constValue == null ||
!(constValue instanceof String) || !(constValue instanceof String str) ||
((String)constValue).length() < PoolWriter.MAX_STRING_LENGTH) str.length() < PoolWriter.MAX_STRING_LENGTH)
return; return;
log.error(pos, Errors.LimitString); log.error(pos, Errors.LimitString);
nerrs++; nerrs++;
@ -824,8 +824,8 @@ public class Gen extends JCTree.Visitor {
@Override @Override
public void visitIdent(JCIdent tree) { public void visitIdent(JCIdent tree) {
if (tree.sym.owner instanceof ClassSymbol) { if (tree.sym.owner instanceof ClassSymbol classSymbol) {
poolWriter.putClass((ClassSymbol)tree.sym.owner); poolWriter.putClass(classSymbol);
} }
} }
@ -888,8 +888,8 @@ public class Gen extends JCTree.Visitor {
public boolean isConstantDynamic(Symbol sym) { public boolean isConstantDynamic(Symbol sym) {
return sym.kind == VAR && return sym.kind == VAR &&
sym instanceof DynamicVarSymbol && sym instanceof DynamicVarSymbol dynamicVarSymbol &&
((DynamicVarSymbol)sym).isDynamic(); dynamicVarSymbol.isDynamic();
} }
/** Derived visitor method: generate code for a list of method arguments. /** Derived visitor method: generate code for a list of method arguments.
@ -1667,9 +1667,8 @@ public class Gen extends JCTree.Visitor {
while(alts != null && alts.head != null) { while(alts != null && alts.head != null) {
JCExpression alt = alts.head; JCExpression alt = alts.head;
if (alt instanceof JCAnnotatedType) { if (alt instanceof JCAnnotatedType annotatedType) {
JCAnnotatedType a = (JCAnnotatedType)alt; res = res.prepend(new Pair<>(annotate.fromAnnotations(annotatedType.annotations), alt));
res = res.prepend(new Pair<>(annotate.fromAnnotations(a.annotations), alt));
} else { } else {
res = res.prepend(new Pair<>(List.nil(), alt)); res = res.prepend(new Pair<>(List.nil(), alt));
} }
@ -2032,13 +2031,13 @@ public class Gen extends JCTree.Visitor {
// int variable we can use an incr instruction instead of // int variable we can use an incr instruction instead of
// proceeding further. // proceeding further.
if ((tree.hasTag(PLUS_ASG) || tree.hasTag(MINUS_ASG)) && if ((tree.hasTag(PLUS_ASG) || tree.hasTag(MINUS_ASG)) &&
l instanceof LocalItem && l instanceof LocalItem localItem &&
tree.lhs.type.getTag().isSubRangeOf(INT) && tree.lhs.type.getTag().isSubRangeOf(INT) &&
tree.rhs.type.getTag().isSubRangeOf(INT) && tree.rhs.type.getTag().isSubRangeOf(INT) &&
tree.rhs.type.constValue() != null) { tree.rhs.type.constValue() != null) {
int ival = ((Number) tree.rhs.type.constValue()).intValue(); int ival = ((Number) tree.rhs.type.constValue()).intValue();
if (tree.hasTag(MINUS_ASG)) ival = -ival; if (tree.hasTag(MINUS_ASG)) ival = -ival;
((LocalItem)l).incr(ival); localItem.incr(ival);
result = l; result = l;
return; return;
} }
@ -2073,9 +2072,9 @@ public class Gen extends JCTree.Visitor {
break; break;
case PREINC: case PREDEC: case PREINC: case PREDEC:
od.duplicate(); od.duplicate();
if (od instanceof LocalItem && if (od instanceof LocalItem localItem &&
(operator.opcode == iadd || operator.opcode == isub)) { (operator.opcode == iadd || operator.opcode == isub)) {
((LocalItem)od).incr(tree.hasTag(PREINC) ? 1 : -1); localItem.incr(tree.hasTag(PREINC) ? 1 : -1);
result = od; result = od;
} else { } else {
od.load(); od.load();
@ -2091,10 +2090,10 @@ public class Gen extends JCTree.Visitor {
break; break;
case POSTINC: case POSTDEC: case POSTINC: case POSTDEC:
od.duplicate(); od.duplicate();
if (od instanceof LocalItem && if (od instanceof LocalItem localItem &&
(operator.opcode == iadd || operator.opcode == isub)) { (operator.opcode == iadd || operator.opcode == isub)) {
Item res = od.load(); Item res = od.load();
((LocalItem)od).incr(tree.hasTag(POSTINC) ? 1 : -1); localItem.incr(tree.hasTag(POSTINC) ? 1 : -1);
result = res; result = res;
} else { } else {
Item res = od.load(); Item res = od.load();
@ -2178,8 +2177,8 @@ public class Gen extends JCTree.Visitor {
MethodType optype = (MethodType)operator.type; MethodType optype = (MethodType)operator.type;
int opcode = operator.opcode; int opcode = operator.opcode;
if (opcode >= if_icmpeq && opcode <= if_icmple && if (opcode >= if_icmpeq && opcode <= if_icmple &&
rhs.type.constValue() instanceof Number && rhs.type.constValue() instanceof Number number &&
((Number) rhs.type.constValue()).intValue() == 0) { number.intValue() == 0) {
opcode = opcode + (ifeq - if_icmpeq); opcode = opcode + (ifeq - if_icmpeq);
} else if (opcode >= if_acmpeq && opcode <= if_acmpne && } else if (opcode >= if_acmpeq && opcode <= if_acmpne &&
TreeInfo.isNull(rhs)) { TreeInfo.isNull(rhs)) {

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2019, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -187,13 +187,9 @@ public interface PoolConstant {
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (obj instanceof BsmKey) { return (obj instanceof BsmKey key)
BsmKey other = (BsmKey)obj; && Objects.equals(bsmKey, key.bsmKey)
return Objects.equals(bsmKey, other.bsmKey) && && Objects.equals(staticArgKeys, key.staticArgKeys);
Objects.equals(staticArgKeys, other.staticArgKeys);
} else {
return false;
}
} }
} }
} }

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2019, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -163,16 +163,16 @@ public class PoolWriter {
* double and String. * double and String.
*/ */
int putConstant(Object o) { int putConstant(Object o) {
if (o instanceof Integer) { if (o instanceof Integer intVal) {
return putConstant(LoadableConstant.Int((int)o)); return putConstant(LoadableConstant.Int(intVal));
} else if (o instanceof Float) { } else if (o instanceof Float floatVal) {
return putConstant(LoadableConstant.Float((float)o)); return putConstant(LoadableConstant.Float(floatVal));
} else if (o instanceof Long) { } else if (o instanceof Long longVal) {
return putConstant(LoadableConstant.Long((long)o)); return putConstant(LoadableConstant.Long(longVal));
} else if (o instanceof Double) { } else if (o instanceof Double doubleVal) {
return putConstant(LoadableConstant.Double((double)o)); return putConstant(LoadableConstant.Double(doubleVal));
} else if (o instanceof String) { } else if (o instanceof String strVal) {
return putConstant(LoadableConstant.String((String)o)); return putConstant(LoadableConstant.String(strVal));
} else { } else {
throw new AssertionError("unexpected constant: " + o); throw new AssertionError("unexpected constant: " + o);
} }

@ -3584,8 +3584,8 @@ public class JavacParser implements Parser {
} }
} }
JCTree def = typeDeclaration(mods, docComment); JCTree def = typeDeclaration(mods, docComment);
if (def instanceof JCExpressionStatement) if (def instanceof JCExpressionStatement statement)
def = ((JCExpressionStatement)def).expr; def = statement.expr;
defs.append(def); defs.append(def);
if (def instanceof JCClassDecl) if (def instanceof JCClassDecl)
checkForImports = false; checkForImports = false;

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -74,12 +74,11 @@ public class ScannerFactory {
} }
public Scanner newScanner(CharSequence input, boolean keepDocComments) { public Scanner newScanner(CharSequence input, boolean keepDocComments) {
if (input instanceof CharBuffer) { if (input instanceof CharBuffer charBuffer) {
CharBuffer buf = (CharBuffer) input;
if (keepDocComments) if (keepDocComments)
return new Scanner(this, new JavadocTokenizer(this, buf)); return new Scanner(this, new JavadocTokenizer(this, charBuffer));
else else
return new Scanner(this, buf); return new Scanner(this, charBuffer);
} else { } else {
char[] array = input.toString().toCharArray(); char[] array = input.toString().toCharArray();
return newScanner(array, array.length, keepDocComments); return newScanner(array, array.length, keepDocComments);

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2005, 2020, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2005, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -542,18 +542,17 @@ public class JavacFiler implements Filer, Closeable {
relativeName.toString(), null); relativeName.toString(), null);
checkFileReopening(fileObject, true); checkFileReopening(fileObject, true);
if (fileObject instanceof JavaFileObject) if (fileObject instanceof JavaFileObject javaFileObject)
return new FilerOutputJavaFileObject(msym, null, (JavaFileObject)fileObject); return new FilerOutputJavaFileObject(msym, null, javaFileObject);
else else
return new FilerOutputFileObject(msym, null, fileObject); return new FilerOutputFileObject(msym, null, fileObject);
} }
private void locationCheck(JavaFileManager.Location location) { private void locationCheck(JavaFileManager.Location location) {
if (location instanceof StandardLocation) { if (location instanceof StandardLocation standardLocation) {
StandardLocation stdLoc = (StandardLocation) location; if (!standardLocation.isOutputLocation())
if (!stdLoc.isOutputLocation())
throw new IllegalArgumentException("Resource creation not supported in location " + throw new IllegalArgumentException("Resource creation not supported in location " +
stdLoc); standardLocation);
} }
} }
@ -889,9 +888,8 @@ public class JavacFiler implements Filer, Closeable {
* subject to annotation processing. * subject to annotation processing.
*/ */
if ((typeName != null)) { if ((typeName != null)) {
if (!(fileObject instanceof JavaFileObject)) if (!(fileObject instanceof JavaFileObject javaFileObject))
throw new AssertionError("JavaFileObject not found for " + fileObject); throw new AssertionError("JavaFileObject not found for " + fileObject);
JavaFileObject javaFileObject = (JavaFileObject)fileObject;
switch(javaFileObject.getKind()) { switch(javaFileObject.getKind()) {
case SOURCE: case SOURCE:
generatedSourceNames.add(typeName); generatedSourceNames.add(typeName);

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2005, 2020, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2005, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -286,8 +286,8 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea
if (options.isSet("accessInternalAPI")) if (options.isSet("accessInternalAPI"))
ModuleHelper.addExports(getClass().getModule(), processorClassLoader.getUnnamedModule()); ModuleHelper.addExports(getClass().getModule(), processorClassLoader.getUnnamedModule());
if (processorClassLoader != null && processorClassLoader instanceof Closeable) { if (processorClassLoader != null && processorClassLoader instanceof Closeable closeable) {
compiler.closeables = compiler.closeables.prepend((Closeable) processorClassLoader); compiler.closeables = compiler.closeables.prepend(closeable);
} }
} }
} catch (SecurityException e) { } catch (SecurityException e) {
@ -376,8 +376,7 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea
* @param e If non-null, pass this exception to Abort * @param e If non-null, pass this exception to Abort
*/ */
private Iterator<Processor> handleServiceLoaderUnavailability(String key, Exception e) { private Iterator<Processor> handleServiceLoaderUnavailability(String key, Exception e) {
if (fileManager instanceof JavacFileManager) { if (fileManager instanceof JavacFileManager standardFileManager) {
StandardJavaFileManager standardFileManager = (JavacFileManager) fileManager;
Iterable<? extends Path> workingPath = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH) Iterable<? extends Path> workingPath = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH)
? standardFileManager.getLocationAsPaths(ANNOTATION_PROCESSOR_PATH) ? standardFileManager.getLocationAsPaths(ANNOTATION_PROCESSOR_PATH)
: standardFileManager.getLocationAsPaths(CLASS_PATH); : standardFileManager.getLocationAsPaths(CLASS_PATH);
@ -880,8 +879,8 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea
*/ */
public void close() { public void close() {
if (processorIterator != null && if (processorIterator != null &&
processorIterator instanceof ServiceIterator) { processorIterator instanceof ServiceIterator serviceIterator) {
((ServiceIterator) processorIterator).close(); serviceIterator.close();
} }
} }
} }