Skip to content

Commit

Permalink
Use regexp to use JEP394 where IntelliJ inspection fails.
Browse files Browse the repository at this point in the history
PCRE regexp: `(\w+) instanceof ([A-Z]\w+)((\)|;)?.*\n.*)\(\2\) \1`

Replaced with: `$1 instanceof $2 roflmao$3roflmao`

Then processed with a Ruby script to rewrite `roflmao` with the name of the class, lowercasing the first letter.

Then I used the IntelliJ "Remove unnecessary parentheses" inspection.

#jdk21 #jep391

PiperOrigin-RevId: 628255645
Change-Id: I74031b97efa72636fdccb1c2473bc3a5f92ad7e9
  • Loading branch information
michaeledgar authored and Copybara-Service committed Apr 26, 2024
1 parent 49850f8 commit 3beaaaf
Show file tree
Hide file tree
Showing 185 changed files with 675 additions and 679 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,8 @@ private static void appendGlobals(
for (Entry<String, Object> entry : globals.entrySet()) {
String name = entry.getKey();
Object obj = entry.getValue();
if (obj instanceof GuardedValue) {
obj = ((GuardedValue) obj).getObject();
if (obj instanceof GuardedValue guardedValue) {
obj = guardedValue.getObject();
}

Value.Builder value = Value.newBuilder();
Expand Down Expand Up @@ -175,8 +175,8 @@ private static Value.Builder valueFromCallable(StarlarkCallable x) {
}

// annotated Java method?
if (x instanceof BuiltinFunction) {
return valueFromAnnotation(((BuiltinFunction) x).getAnnotation());
if (x instanceof BuiltinFunction builtinFunction) {
return valueFromAnnotation(builtinFunction.getAnnotation());
}

// application-defined callable? Treat as def f(**kwargs).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -230,8 +230,8 @@ private static String reprDefaultValue(Attribute attribute) {
// We cannot print anything useful here other than "optional". Let's assume the doc string for
// the attribute explains the details.
return null;
} else if (value instanceof TriState) {
switch ((TriState) value) {
} else if (value instanceof TriState triState) {
switch (triState) {
case AUTO:
return "-1";
case NO:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -253,8 +253,8 @@ public Collection<String> getClientEnvironmentVariables() {

@Override
public Collection<Artifact> getOutputs() {
return outputs instanceof Artifact
? ImmutableSet.of((Artifact) outputs)
return outputs instanceof Artifact artifact
? ImmutableSet.of(artifact)
: new OutputSet((Artifact[]) outputs);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -534,8 +534,8 @@ public Token getTokenIfNeedToExecute(
action.discoversInputs(),
"Actions that don't know their inputs must discover them: %s",
action);
if (action instanceof ActionCacheAwareAction
&& ((ActionCacheAwareAction) action).storeInputsExecPathsInActionCache()) {
if (action instanceof ActionCacheAwareAction actionCacheAwareAction
&& actionCacheAwareAction.storeInputsExecPathsInActionCache()) {
actionInputs = NestedSetBuilder.wrap(Order.STABLE_ORDER, resolvedCacheArtifacts);
} else {
actionInputs =
Expand Down Expand Up @@ -764,8 +764,8 @@ public void updateActionCache(
}

boolean storeAllInputsInActionCache =
action instanceof ActionCacheAwareAction
&& ((ActionCacheAwareAction) action).storeInputsExecPathsInActionCache();
action instanceof ActionCacheAwareAction actionCacheAwareAction
&& actionCacheAwareAction.storeInputsExecPathsInActionCache();
ImmutableSet<Artifact> excludePathsFromActionCache =
!storeAllInputsInActionCache && action.discoversInputs()
? action.getMandatoryInputs().toSet()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -262,8 +262,8 @@ public BuildEventStreamProtos.BuildEvent asStreamProto(BuildEventContext convert
}
}
try {
if (action instanceof CommandAction) {
actionBuilder.addAllCommandLine(((CommandAction) action).getArguments());
if (action instanceof CommandAction commandAction) {
actionBuilder.addAllCommandLine(commandAction.getArguments());
}
} catch (CommandLineExpansionException e) {
// Command-line not available, so just not report it
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -508,8 +508,8 @@ public void close() throws IOException {
try {
fileOutErr.close();
} finally {
if (actionFileSystem instanceof Closeable) {
((Closeable) actionFileSystem).close();
if (actionFileSystem instanceof Closeable closeable) {
closeable.close();
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,8 +143,8 @@ public static ActionExecutionException fromExecException(

DetailedExitCode code =
DetailedExitCode.of(exception.getFailureDetail(action.describe() + " failed: " + message));
if (exception instanceof LostInputsExecException) {
return ((LostInputsExecException) exception).fromExecException(message, action, code);
if (exception instanceof LostInputsExecException lostInputsExecException) {
return lostInputsExecException.fromExecException(message, action, code);
}

return fromExecException(exception, message, action, code);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,8 +157,8 @@ public static Path toInputPath(ActionInput input, Path execRoot) {
Preconditions.checkNotNull(input, "input");
Preconditions.checkNotNull(execRoot, "execRoot");

return (input instanceof Artifact)
? ((Artifact) input).getPath()
return input instanceof Artifact artifact
? artifact.getPath()
: execRoot.getRelative(input.getExecPath());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -374,8 +374,8 @@ public final ActionLookupKey getArtifactOwner() {
* consistent across calls to {@link #setGeneratingActionKey} and also serialization.
*/
private static Object getOwnerToUseForHashCode(Object owner) {
return owner instanceof ActionLookupData
? ((ActionLookupData) owner).getActionLookupKey()
return owner instanceof ActionLookupData actionLookupData
? actionLookupData.getActionLookupKey()
: owner;
}

Expand Down Expand Up @@ -1408,8 +1408,8 @@ public int hashCode() {

@Override
public boolean equals(Object obj) {
return obj instanceof OwnerlessArtifactWrapper
&& this.artifact.equalsWithoutOwner(((OwnerlessArtifactWrapper) obj).artifact);
return obj instanceof OwnerlessArtifactWrapper ownerlessArtifactWrapper
&& this.artifact.equalsWithoutOwner(ownerlessArtifactWrapper.artifact);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,8 @@ private IdentityResolver(Path execRoot) {

@Override
public Path toPath(ActionInput actionInput) {
if (actionInput instanceof Artifact) {
return ((Artifact) actionInput).getPath();
if (actionInput instanceof Artifact artifact) {
return artifact.getPath();
}
return execRoot.getRelative(actionInput.getExecPath());
}
Expand Down Expand Up @@ -104,8 +104,8 @@ private TransformResolver(Path execRoot) {

@Override
public Path toPath(ActionInput input) {
if (input instanceof Artifact) {
return fileSystem.getPath(((Artifact) input).getPath().asFragment());
if (input instanceof Artifact artifact) {
return fileSystem.getPath(artifact.getPath().asFragment());
}
return execRoot.getRelative(input.getExecPath());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,8 @@ static String expandToCommandLine(Object object) {
// Since StarlarkValue should be moved out of Bazel, this refactoring would be blocked on making
// a BuildStarlarkValue subinterface for Bazel-specific Starlark types. It would then be
// BuildStarlarkValue, rather than StarlarkValue, that extends CommandLineItem.
if (object instanceof CommandLineItem) {
return ((CommandLineItem) object).expandToCommandLine();
if (object instanceof CommandLineItem commandLineItem) {
return commandLineItem.expandToCommandLine();
} else {
return object.toString();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -499,8 +499,8 @@ public ImmutableList<CommandLineAndParamFileInfo> unpack() {
CommandLine commandLine;
ParamFileInfo paramFileInfo = null;

if (obj instanceof CommandLine) {
commandLine = (CommandLine) obj;
if (obj instanceof CommandLine c) {
commandLine = c;
if (i + 1 < commandLines.length && commandLines[i + 1] instanceof ParamFileInfo) {
paramFileInfo = (ParamFileInfo) commandLines[++i];
}
Expand Down Expand Up @@ -530,8 +530,8 @@ public Iterable<String> arguments() throws CommandLineExpansionException, Interr
public Iterable<String> arguments(
@Nullable ArtifactExpander artifactExpander, PathMapper pathMapper)
throws CommandLineExpansionException, InterruptedException {
if (arg instanceof PathStrippable) {
return ImmutableList.of(((PathStrippable) arg).expand(pathMapper::map));
if (arg instanceof PathStrippable pathStrippable) {
return ImmutableList.of(pathStrippable.expand(pathMapper::map));
}
return ImmutableList.of(CommandLineItem.expandToCommandLine(arg));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ public byte[] getDigest() {

@Override
public boolean equals(Object other) {
if (other instanceof ByteStringDigest) {
return bytes.equals(((ByteStringDigest) other).bytes);
if (other instanceof ByteStringDigest byteStringDigest) {
return bytes.equals(byteStringDigest.bytes);
}
return false;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,8 @@ public RuleContext getRuleContext() {
public static BazelRuleAnalysisThreadContext fromOrFail(StarlarkThread thread, String what)
throws EvalException {
BazelStarlarkContext ctx = thread.getThreadLocal(BazelStarlarkContext.class);
if (ctx instanceof BazelRuleAnalysisThreadContext) {
return (BazelRuleAnalysisThreadContext) ctx;
if (ctx instanceof BazelRuleAnalysisThreadContext bazelRuleAnalysisThreadContext) {
return bazelRuleAnalysisThreadContext;
}
throw Starlark.errorf("%s can only be called from a rule or aspect implementation", what);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -775,8 +775,8 @@ private static ImmutableList<Artifact> filterTransitiveExtraActions(
for (Artifact.DerivedArtifact artifact :
provider.getTransitiveExtraActionArtifacts().toList()) {
ActionLookupKey owner = artifact.getArtifactOwner();
if (owner instanceof AspectKey) {
if (aspectClasses.contains(((AspectKey) owner).getAspectClass())) {
if (owner instanceof AspectKey aspectKey) {
if (aspectClasses.contains(aspectKey.getAspectClass())) {
artifacts.add(artifact);
}
}
Expand All @@ -798,8 +798,8 @@ private static void collectTests(
final boolean isExclusive = topLevelOptions.runTestsExclusively();
for (ConfiguredTarget configuredTarget : allTestTargets) {
Target target = labelToTargetMap.get(configuredTarget.getLabel());
if (target instanceof Rule) {
if (isExclusive || TargetUtils.isExclusiveTestRule((Rule) target)) {
if (target instanceof Rule rule) {
if (isExclusive || TargetUtils.isExclusiveTestRule(rule)) {
exclusiveTests.add(configuredTarget);
} else if (TargetUtils.isExclusiveIfLocalTestRule((Rule) target)
&& TargetUtils.isLocalTestRule((Rule) target)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -198,8 +198,8 @@ public ConfiguredAspect build() throws ActionConflictException, InterruptedExcep
// Initialize every StarlarkApiProvider
for (int i = 0; i < providerMap.getProviderCount(); i++) {
Object obj = providerMap.getProviderInstanceAt(i);
if (obj instanceof StarlarkApiProvider) {
((StarlarkApiProvider) obj).init(providerMap);
if (obj instanceof StarlarkApiProvider starlarkApiProvider) {
starlarkApiProvider.init(providerMap);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,12 +112,12 @@ public static DependencyLabels computeDependencyLabels(
addToolchainDeps(toolchainContexts, outgoingLabels);
} else if (target instanceof InputFile || target instanceof EnvironmentGroup) {
addVisibilityDepLabels(target.getVisibilityDependencyLabels(), outgoingLabels);
} else if (target instanceof Rule) {
fromRule = (Rule) target;
} else if (target instanceof Rule rule) {
fromRule = rule;
attributeMap = ConfiguredAttributeMapper.of(fromRule, configConditions, config);
visitRule(node, aspects, attributeMap, toolchainContexts, outgoingLabels);
} else if (target instanceof PackageGroup) {
outgoingLabels.putAll(VISIBILITY_DEPENDENCY, ((PackageGroup) target).getIncludes());
} else if (target instanceof PackageGroup packageGroup) {
outgoingLabels.putAll(VISIBILITY_DEPENDENCY, packageGroup.getIncludes());
} else {
throw new IllegalStateException(target.getLabel().toString());
}
Expand Down Expand Up @@ -372,8 +372,8 @@ private static <T> void resolveAttribute(
Object defaultValue = attribute.getDefaultValue(rule);
attributeValue =
type.cast(
defaultValue instanceof ComputedDefault
? ((ComputedDefault) defaultValue).getDefault(attributeMap)
defaultValue instanceof ComputedDefault computedDefault
? computedDefault.getDefault(attributeMap)
: defaultValue);
}
} else if (attribute.isLateBound()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,10 +99,10 @@ private static NestedSet<PackageGroupContents> getPackageSpecifications(
@Override
public boolean targetInAllowlist(Object target) throws EvalException, LabelSyntaxException {
Label targetLabel;
if (target instanceof String) {
targetLabel = Label.parseCanonical((String) target);
} else if (target instanceof Label) {
targetLabel = (Label) target;
if (target instanceof String string) {
targetLabel = Label.parseCanonical(string);
} else if (target instanceof Label label) {
targetLabel = label;
} else {
throw Starlark.errorf(
"expected string or label for 'target' instead of %s", Starlark.type(target));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1608,10 +1608,10 @@ private void checkAttributesNonEmpty(AttributeMap attributes) {

// TODO(adonovan): define in terms of Starlark.len?
boolean isEmpty = false;
if (attributeValue instanceof List) {
isEmpty = ((List<?>) attributeValue).isEmpty();
} else if (attributeValue instanceof Map) {
isEmpty = ((Map<?, ?>) attributeValue).isEmpty();
if (attributeValue instanceof List<?> list) {
isEmpty = list.isEmpty();
} else if (attributeValue instanceof Map<?, ?> map) {
isEmpty = map.isEmpty();
}
if (isEmpty) {
reporter.attributeError(attr.getName(), "attribute must be non empty");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -379,8 +379,8 @@ private static String expandToCommandLine(Object object, PathMapper pathMapper)
// It'd be nice to build this into ActionInput's CommandLine interface so we don't have
// to explicitly check if an object is a ActionInput. Unfortunately that would require
// a lot more dependencies on the Java library ActionInput is built into.
return pathMapper != null && object instanceof ActionInput
? pathMapper.getMappedExecPathString((ActionInput) object)
return pathMapper != null && object instanceof ActionInput actionInput
? pathMapper.getMappedExecPathString(actionInput)
: CommandLineItem.expandToCommandLine(object);
}

Expand Down Expand Up @@ -1298,11 +1298,11 @@ public ImmutableList<String> arguments(
String previousFlag = null;
for (int i = 0; i < count; ) {
Object arg = arguments.get(i++);
if (arg instanceof TreeFileArtifactArgvFragment) {
arg = substituteTreeFileArtifactArgvFragment((TreeFileArtifactArgvFragment) arg);
if (arg instanceof TreeFileArtifactArgvFragment treeFileArtifactArgvFragment) {
arg = substituteTreeFileArtifactArgvFragment(treeFileArtifactArgvFragment);
}
if (arg instanceof NestedSet) {
evalSimpleVectorArg(((NestedSet<?>) arg).toList(), builder, pathMapper, previousFlag);
if (arg instanceof NestedSet<?> nestedSet) {
evalSimpleVectorArg(nestedSet.toList(), builder, pathMapper, previousFlag);
} else if (arg instanceof Iterable) {
evalSimpleVectorArg((Iterable<?>) arg, builder, pathMapper, previousFlag);
} else if (arg instanceof ArgvFragment) {
Expand All @@ -1312,17 +1312,17 @@ public ImmutableList<String> arguments(
} else {
i = ((ArgvFragment) arg).eval(arguments, i, builder, pathMapper);
}
} else if (arg instanceof ActionInput) {
builder.add(pathMapper.getMappedExecPathString((ActionInput) arg));
} else if (arg instanceof PathFragment) {
builder.add(pathMapper.map((PathFragment) arg).getPathString());
} else if (arg instanceof ActionInput actionInput) {
builder.add(pathMapper.getMappedExecPathString(actionInput));
} else if (arg instanceof PathFragment pathFragment) {
builder.add(pathMapper.map(pathFragment).getPathString());
} else {
builder.add(CommandLineItem.expandToCommandLine(arg));
}
// Track the last scalar string argument (e.g. "--javacopts") so that the PathMapper can
// heuristically map subsequent argument collections that contain paths.
if (arg instanceof String) {
previousFlag = (String) arg;
if (arg instanceof String string) {
previousFlag = string;
} else {
previousFlag = null;
}
Expand All @@ -1337,8 +1337,8 @@ private void evalSimpleVectorArg(
String previousFlag) {
ExceptionlessMapFn<Object> mapFn = pathMapper.getMapFn(previousFlag);
for (Object value : arg) {
if (value instanceof ActionInput) {
builder.add(pathMapper.getMappedExecPathString((ActionInput) value));
if (value instanceof ActionInput actionInput) {
builder.add(pathMapper.getMappedExecPathString(actionInput));
} else {
mapFn.expandToCommandLine(value, builder::add);
}
Expand All @@ -1365,17 +1365,17 @@ public void addToFingerprint(
int count = arguments.size();
for (int i = 0; i < count; ) {
Object arg = arguments.get(i++);
if (arg instanceof TreeFileArtifactArgvFragment) {
arg = substituteTreeFileArtifactArgvFragment((TreeFileArtifactArgvFragment) arg);
if (arg instanceof TreeFileArtifactArgvFragment treeFileArtifactArgvFragment) {
arg = substituteTreeFileArtifactArgvFragment(treeFileArtifactArgvFragment);
}
if (arg instanceof NestedSet) {
actionKeyContext.addNestedSetToFingerprint(fingerprint, (NestedSet<Object>) arg);
} else if (arg instanceof Iterable) {
for (Object value : (Iterable<Object>) arg) {
fingerprint.addString(CommandLineItem.expandToCommandLine(value));
}
} else if (arg instanceof ArgvFragment) {
i = ((ArgvFragment) arg).addToFingerprint(arguments, i, actionKeyContext, fingerprint);
} else if (arg instanceof ArgvFragment argvFragment) {
i = argvFragment.addToFingerprint(arguments, i, actionKeyContext, fingerprint);
} else {
fingerprint.addString(CommandLineItem.expandToCommandLine(arg));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -254,8 +254,8 @@ public final ActionResult execute(ActionExecutionContext actionExecutionContext)
} catch (CommandLineExpansionException e) {
throw createCommandLineException(e);
} catch (ExecException e) {
if (e instanceof SpawnExecException) {
throw ((SpawnExecException) e).toActionExecutionException(this);
if (e instanceof SpawnExecException spawnExecException) {
throw spawnExecException.toActionExecutionException(this);
}
throw ActionExecutionException.fromExecException(e, this);
}
Expand Down

0 comments on commit 3beaaaf

Please sign in to comment.