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

View File

@ -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.
*
* 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<>();
if (contained0 != null) {
for (Attribute a : contained0)
if (a instanceof Attribute.Compound)
compounds = compounds.append((Attribute.Compound)a);
if (a instanceof Attribute.Compound attributeCompound)
compounds = compounds.append(attributeCompound);
}
return compounds.toArray(new Attribute.Compound[compounds.size()]);
}

View File

@ -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.
*
* 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)
public <R, P> R accept(AnnotationValueVisitor<R, P> v, P p) {
if (value instanceof String)
return v.visitString((String) value, p);
if (value instanceof String str)
return v.visitString(str, p);
if (value instanceof Integer) {
int i = (Integer) value;
switch (type.getTag()) {
@ -198,12 +198,10 @@ public abstract class Attribute implements AnnotationValue {
if (values.size() == 1) {
Pair<MethodSymbol, Attribute> val = values.get(0);
if (val.fst.getSimpleName().contentEquals("value")
&& val.snd instanceof Array) {
Array arr = (Array) val.snd;
if (arr.values.length != 0
&& arr.values[0] instanceof Attribute.TypeCompound)
return (Attribute.TypeCompound) arr.values[0];
}
&& val.snd instanceof Array arr
&& arr.values.length != 0
&& arr.values[0] instanceof Attribute.TypeCompound compound)
return compound;
}
return null;
}

View File

@ -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.
*
* 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.
boolean useCtProps;
JavaFileManager fm = context.get(JavaFileManager.class);
if (fm instanceof DelegatingJavaFileManager) {
fm = ((DelegatingJavaFileManager) fm).getBaseFileManager();
if (fm instanceof DelegatingJavaFileManager delegatingJavaFileManager) {
fm = delegatingJavaFileManager.getBaseFileManager();
}
if (fm instanceof JavacFileManager) {
JavacFileManager jfm = (JavacFileManager) fm;
useCtProps = jfm.isDefaultBootClassPath() && jfm.isSymbolFileEnabled();
if (fm instanceof JavacFileManager javacFileManager) {
useCtProps = javacFileManager.isDefaultBootClassPath() && javacFileManager.isSymbolFileEnabled();
} else if (fm.getClass().getName().equals("com.sun.tools.sjavac.comp.SmartFileManager")) {
useCtProps = !options.isSet("ignore.symbol.file");
} else {
@ -642,27 +641,26 @@ public class ClassFinder {
if (verbose && verbosePath) {
verbosePath = false; // print once per compile
if (fileManager instanceof StandardJavaFileManager) {
StandardJavaFileManager fm = (StandardJavaFileManager)fileManager;
if (fileManager instanceof StandardJavaFileManager standardJavaFileManager) {
if (haveSourcePath && wantSourceFiles) {
List<Path> path = List.nil();
for (Path sourcePath : fm.getLocationAsPaths(SOURCE_PATH)) {
for (Path sourcePath : standardJavaFileManager.getLocationAsPaths(SOURCE_PATH)) {
path = path.prepend(sourcePath);
}
log.printVerbose("sourcepath", path.reverse().toString());
} else if (wantSourceFiles) {
List<Path> path = List.nil();
for (Path classPath : fm.getLocationAsPaths(CLASS_PATH)) {
for (Path classPath : standardJavaFileManager.getLocationAsPaths(CLASS_PATH)) {
path = path.prepend(classPath);
}
log.printVerbose("sourcepath", path.reverse().toString());
}
if (wantClassFiles) {
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);
}
for (Path classPath : fm.getLocationAsPaths(CLASS_PATH)) {
for (Path classPath : standardJavaFileManager.getLocationAsPaths(CLASS_PATH)) {
path = path.prepend(classPath);
}
log.printVerbose("classpath", path.reverse().toString());

View File

@ -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.
*
* 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?
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ProvidesDirective)) {
return false;
}
ProvidesDirective other = (ProvidesDirective)obj;
return service == other.service && impls.equals(other.impls);
return (obj instanceof ProvidesDirective directive)
&& service == directive.service
&& impls.equals(directive.impls);
}
// TODO: delete?
@ -359,11 +357,8 @@ public abstract class Directive implements ModuleElement.Directive {
// TODO: delete?
@Override
public boolean equals(Object obj) {
if (!(obj instanceof UsesDirective)) {
return false;
}
UsesDirective other = (UsesDirective)obj;
return service == other.service;
return (obj instanceof UsesDirective directive)
&& service == directive.service;
}
// TODO: delete?

View File

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

View File

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

View File

@ -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.
*
* 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()) {
Pair<Symbol.MethodSymbol, Attribute> val = attrCompound.values.get(0);
if (val.fst.getSimpleName().contentEquals("value") &&
val.snd instanceof Attribute.Array) {
Attribute.Array arr = (Attribute.Array) val.snd;
val.snd instanceof Attribute.Array arr) {
if (arr.values.length != 0
&& arr.values[0] instanceof Attribute.Compound
&& arr.values[0].type == compound.type) {

View File

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

View File

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

View File

@ -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.
*
* 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);
if (!(atValue instanceof Attribute.Array)) {
if (!(atValue instanceof Attribute.Array arrayVal)) {
return null;
}
List<Attribute> targets = ((Array)atValue).getValue();
List<Attribute> targets = arrayVal.getValue();
if (targets.stream().anyMatch(a -> !(a instanceof Attribute.Enum))) {
return null;
}

View File

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

View File

@ -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.
*
* This code is free software; you can redistribute it and/or modify it
@ -404,13 +404,9 @@ public class Annotate {
}
//where:
private boolean isAttributeTrue(Attribute attr) {
if (attr instanceof Attribute.Constant) {
Attribute.Constant v = (Attribute.Constant) attr;
if (v.type == syms.booleanType && ((Integer) v.value) != 0) {
return true;
}
}
return false;
return (attr instanceof Attribute.Constant constant)
&& constant.type == syms.booleanType
&& ((Integer) constant.value) != 0;
}
/**
@ -447,7 +443,7 @@ public class Annotate {
{
// The attribute might have been entered if it is Target or Repeatable
// 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
List<Pair<MethodSymbol,Attribute>> elems =
attributeAnnotationValues(a, expectedAnnotationType, env);
@ -458,7 +454,7 @@ public class Annotate {
return tc;
} else {
// Use an existing TypeCompound
return (Attribute.TypeCompound)a.attribute;
return typeCompound;
}
}
@ -911,12 +907,12 @@ public class Annotate {
log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl));
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));
return null;
}
return ((Attribute.Class)p.snd).getValue();
return attributeClass.getValue();
}
/* Validate that the suggested targetContainerType Type is a valid

View File

@ -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.
*
* This code is free software; you can redistribute it and/or modify it
@ -751,12 +751,9 @@ public class ArgumentAttr extends JCTree.Visitor {
@Override
public boolean equals(Object obj) {
if (obj instanceof UniquePos) {
UniquePos that = (UniquePos)obj;
return pos == that.pos && source == that.source;
} else {
return false;
}
return (obj instanceof UniquePos uniquePos)
&& pos == uniquePos.pos
&& source == uniquePos.source;
}
@Override

View File

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

View File

@ -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.
*
* This code is free software; you can redistribute it and/or modify it
@ -243,8 +243,8 @@ public class AttrRecover {
break;
}
for (Object a : d.getArgs()) {
if (a instanceof JCDiagnostic) {
diags = diags.prepend((JCDiagnostic) a);
if (a instanceof JCDiagnostic diagnostic) {
diags = diags.prepend(diagnostic);
}
}
}

View File

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

View File

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

View File

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

View File

@ -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.
*
* This code is free software; you can redistribute it and/or modify it
@ -197,12 +197,9 @@ public class LambdaToMethod extends TreeTranslator {
@Override
public boolean equals(Object o) {
if (!(o instanceof DedupedLambda)) {
return false;
}
DedupedLambda that = (DedupedLambda) o;
return types.isSameType(symbol.asType(), that.symbol.asType())
&& new TreeDiffer(symbol.params(), that.symbol.params()).scan(tree, that.tree);
return (o instanceof DedupedLambda dedupedLambda)
&& types.isSameType(symbol.asType(), dedupedLambda.symbol.asType())
&& new TreeDiffer(symbol.params(), dedupedLambda.symbol.params()).scan(tree, dedupedLambda.tree);
}
}
@ -1558,12 +1555,9 @@ public class LambdaToMethod extends TreeTranslator {
@Override
public void visitVarDef(JCVariableDecl tree) {
TranslationContext<?> context = context();
LambdaTranslationContext ltc = (context != null && context instanceof LambdaTranslationContext)?
(LambdaTranslationContext)context :
null;
if (ltc != null) {
if (context != null && context instanceof LambdaTranslationContext lambdaContext) {
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).
// 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)
*/
private boolean lambdaFieldAccessFilter(JCFieldAccess fAccess) {
LambdaTranslationContext lambdaContext =
context instanceof LambdaTranslationContext ?
(LambdaTranslationContext) context : null;
return lambdaContext != null
return (context instanceof LambdaTranslationContext lambdaContext)
&& !fAccess.sym.isStatic()
&& fAccess.name == names._this
&& (fAccess.sym.owner.kind == TYP)

View File

@ -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.
*
* 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;
JCExpression resourceUse;
boolean resourceNonNull;
if (resource instanceof JCVariableDecl) {
JCVariableDecl var = (JCVariableDecl) resource;
resourceUse = make.Ident(var.sym).setType(resource.type);
resourceNonNull = var.init != null && TreeInfo.skipParens(var.init).hasTag(NEWCLASS);
stats.add(var);
if (resource instanceof JCVariableDecl variableDecl) {
resourceUse = make.Ident(variableDecl.sym).setType(resource.type);
resourceNonNull = variableDecl.init != null && TreeInfo.skipParens(variableDecl.init).hasTag(NEWCLASS);
stats.add(variableDecl);
} else {
Assert.check(resource instanceof JCExpression);
VarSymbol syntheticTwrVar =

View File

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

View File

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

View File

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

View File

@ -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.
*
* This code is free software; you can redistribute it and/or modify it
@ -187,13 +187,9 @@ public interface PoolConstant {
@Override
public boolean equals(Object obj) {
if (obj instanceof BsmKey) {
BsmKey other = (BsmKey)obj;
return Objects.equals(bsmKey, other.bsmKey) &&
Objects.equals(staticArgKeys, other.staticArgKeys);
} else {
return false;
}
return (obj instanceof BsmKey key)
&& Objects.equals(bsmKey, key.bsmKey)
&& Objects.equals(staticArgKeys, key.staticArgKeys);
}
}
}

View File

@ -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.
*
* This code is free software; you can redistribute it and/or modify it
@ -163,16 +163,16 @@ public class PoolWriter {
* double and String.
*/
int putConstant(Object o) {
if (o instanceof Integer) {
return putConstant(LoadableConstant.Int((int)o));
} else if (o instanceof Float) {
return putConstant(LoadableConstant.Float((float)o));
} else if (o instanceof Long) {
return putConstant(LoadableConstant.Long((long)o));
} else if (o instanceof Double) {
return putConstant(LoadableConstant.Double((double)o));
} else if (o instanceof String) {
return putConstant(LoadableConstant.String((String)o));
if (o instanceof Integer intVal) {
return putConstant(LoadableConstant.Int(intVal));
} else if (o instanceof Float floatVal) {
return putConstant(LoadableConstant.Float(floatVal));
} else if (o instanceof Long longVal) {
return putConstant(LoadableConstant.Long(longVal));
} else if (o instanceof Double doubleVal) {
return putConstant(LoadableConstant.Double(doubleVal));
} else if (o instanceof String strVal) {
return putConstant(LoadableConstant.String(strVal));
} else {
throw new AssertionError("unexpected constant: " + o);
}

View File

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

View File

@ -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.
*
* 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) {
if (input instanceof CharBuffer) {
CharBuffer buf = (CharBuffer) input;
if (input instanceof CharBuffer charBuffer) {
if (keepDocComments)
return new Scanner(this, new JavadocTokenizer(this, buf));
return new Scanner(this, new JavadocTokenizer(this, charBuffer));
else
return new Scanner(this, buf);
return new Scanner(this, charBuffer);
} else {
char[] array = input.toString().toCharArray();
return newScanner(array, array.length, keepDocComments);

View File

@ -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.
*
* 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);
checkFileReopening(fileObject, true);
if (fileObject instanceof JavaFileObject)
return new FilerOutputJavaFileObject(msym, null, (JavaFileObject)fileObject);
if (fileObject instanceof JavaFileObject javaFileObject)
return new FilerOutputJavaFileObject(msym, null, javaFileObject);
else
return new FilerOutputFileObject(msym, null, fileObject);
}
private void locationCheck(JavaFileManager.Location location) {
if (location instanceof StandardLocation) {
StandardLocation stdLoc = (StandardLocation) location;
if (!stdLoc.isOutputLocation())
if (location instanceof StandardLocation standardLocation) {
if (!standardLocation.isOutputLocation())
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.
*/
if ((typeName != null)) {
if (!(fileObject instanceof JavaFileObject))
if (!(fileObject instanceof JavaFileObject javaFileObject))
throw new AssertionError("JavaFileObject not found for " + fileObject);
JavaFileObject javaFileObject = (JavaFileObject)fileObject;
switch(javaFileObject.getKind()) {
case SOURCE:
generatedSourceNames.add(typeName);

View File

@ -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.
*
* 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"))
ModuleHelper.addExports(getClass().getModule(), processorClassLoader.getUnnamedModule());
if (processorClassLoader != null && processorClassLoader instanceof Closeable) {
compiler.closeables = compiler.closeables.prepend((Closeable) processorClassLoader);
if (processorClassLoader != null && processorClassLoader instanceof Closeable closeable) {
compiler.closeables = compiler.closeables.prepend(closeable);
}
}
} catch (SecurityException e) {
@ -376,8 +376,7 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea
* @param e If non-null, pass this exception to Abort
*/
private Iterator<Processor> handleServiceLoaderUnavailability(String key, Exception e) {
if (fileManager instanceof JavacFileManager) {
StandardJavaFileManager standardFileManager = (JavacFileManager) fileManager;
if (fileManager instanceof JavacFileManager standardFileManager) {
Iterable<? extends Path> workingPath = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH)
? standardFileManager.getLocationAsPaths(ANNOTATION_PROCESSOR_PATH)
: standardFileManager.getLocationAsPaths(CLASS_PATH);
@ -880,8 +879,8 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea
*/
public void close() {
if (processorIterator != null &&
processorIterator instanceof ServiceIterator) {
((ServiceIterator) processorIterator).close();
processorIterator instanceof ServiceIterator serviceIterator) {
serviceIterator.close();
}
}
}