Skip to content

Commit

Permalink
Update MustBeClosed to handle IO decorators.
Browse files Browse the repository at this point in the history
Tested:
    TAP for global presubmit queue
    []
PiperOrigin-RevId: 673522715
  • Loading branch information
chaoren authored and Error Prone Team committed Oct 5, 2024
1 parent e023166 commit 40e85b6
Show file tree
Hide file tree
Showing 3 changed files with 212 additions and 232 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

package com.google.errorprone.bugpatterns;

import static com.google.errorprone.bugpatterns.CloseableDecoratorTypes.CLOSEABLE_DECORATOR_TYPES;
import static com.google.errorprone.fixes.SuggestedFixes.prettyType;
import static com.google.errorprone.fixes.SuggestedFixes.qualifyType;
import static com.google.errorprone.matchers.Description.NO_MATCH;
Expand Down Expand Up @@ -62,6 +63,7 @@
import com.sun.source.util.TreePath;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.util.Position;
Expand Down Expand Up @@ -299,6 +301,17 @@ && isSameType(type.getReturnType(), streamType, state)) {
}
}
break;
case NEW_CLASS:
NewClassTree newClassTree = (NewClassTree) path.getLeaf();
if (isClosingDecorator(newClassTree, prev.getLeaf(), state)) {
if (HAS_MUST_BE_CLOSED_ANNOTATION.matches(newClassTree, state)) {
// if the decorator is also annotated then it would already be enforced
return Optional.empty();
}
// otherwise, enforce that the decorator must be closed
continue OUTER;
}
break;
case VARIABLE:
Symbol sym = getSymbol(path.getLeaf());
if (sym instanceof VarSymbol) {
Expand Down Expand Up @@ -520,4 +533,29 @@ private static Optional<Change> wrapTryFinallyAroundVariableScope(
.closeBraceAfter(enclosingBlock)
.wrapped();
}

/**
* Returns true if {@code decorator} is the instantiation of an {@link AutoCloseable} decorator
* type that decorates the given {@code resource} and always closes the decorated {@code resource}
* when closed.
*/
private static boolean isClosingDecorator(
NewClassTree decorator, Tree resource, VisitorState state) {
if (decorator.getArguments().isEmpty() || !decorator.getArguments().get(0).equals(resource)) {
// we assume the decorated resource is always the first argument to the decorator constructor
return false;
}
MethodSymbol constructor = getSymbol(decorator);
if (!constructor.getThrownTypes().isEmpty()) {
// resource would not be closed if the decorator constructor throws
return false;
}
Type resourceType = constructor.params().get(0).type;
Type decoratorType = constructor.owner.type;
return CLOSEABLE_DECORATOR_TYPES.keySet().stream()
.filter(key -> isSameType(resourceType, state.getTypeFromString(key), state))
.limit(1)
.flatMap(key -> CLOSEABLE_DECORATOR_TYPES.get(key).stream())
.anyMatch(value -> isSubtype(decoratorType, state.getTypeFromString(value), state));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/*
* Copyright 2024 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.errorprone.bugpatterns;

import com.google.common.collect.ImmutableSetMultimap;
import java.io.FilterInputStream;
import java.io.FilterOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;

/**
* Common {@link AutoCloseable} decorator types that wrap around {@link AutoCloseable} resources,
* which are always closed when the enclosing decorators are closed.
*
* <p>Each value in the map is the common supertype of some {@link AutoCloseable} decorator types,
* with the key being the common {@link AutoCloseable} type that they decorate. The decorated type
* is always assumed to be the first argument to the constructor of the decorator type.
*/
public final class CloseableDecoratorTypes {
public static final ImmutableSetMultimap<String, String> CLOSEABLE_DECORATOR_TYPES =
ImmutableSetMultimap.<String, String>builder()
.putAll(
InputStream.class.getName(),
FilterInputStream.class.getName(), // e.g., BufferedInputStream
InputStreamReader.class.getName())
.putAll(
OutputStream.class.getName(),
FilterOutputStream.class.getName(), // e.g., BufferedOutputStream
OutputStreamWriter.class.getName())
.put(Reader.class.getName(), Reader.class.getName()) // e.g., BufferedReader
.put(Writer.class.getName(), Writer.class.getName()) // e.g., BufferedWriter
.build();

private CloseableDecoratorTypes() {}
}
Loading

0 comments on commit 40e85b6

Please sign in to comment.