diff options
author | 2017-06-30 00:32:04 +0200 | |
---|---|---|
committer | 2017-06-30 13:00:58 +0200 | |
commit | 3d2a68c6da2a50a9e1bcf6615e83a43701cdf95d (patch) | |
tree | 31692a985d316e33733ab6993e529b8a08c206b6 /src/main/java/com/google/devtools/build | |
parent | 2d5eeab381713f99c8c8b7b80f3d447be847b548 (diff) |
Automated conversion to Java 8
With a few manual fixes for readability.
RELNOTES: None.
PiperOrigin-RevId: 160582556
Diffstat (limited to 'src/main/java/com/google/devtools/build')
147 files changed, 1016 insertions, 1983 deletions
diff --git a/src/main/java/com/google/devtools/build/lib/actions/ActionExecutionStatusReporter.java b/src/main/java/com/google/devtools/build/lib/actions/ActionExecutionStatusReporter.java index a15165bd68..fd3dfd58ba 100644 --- a/src/main/java/com/google/devtools/build/lib/actions/ActionExecutionStatusReporter.java +++ b/src/main/java/com/google/devtools/build/lib/actions/ActionExecutionStatusReporter.java @@ -13,6 +13,8 @@ // limitations under the License. package com.google.devtools.build.lib.actions; +import static java.util.Comparator.comparing; + import com.google.common.annotations.VisibleForTesting; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; @@ -137,7 +139,7 @@ public final class ActionExecutionStatusReporter { if (actions.isEmpty()) { return; } - Collections.sort(actions, Pair.<Long, ActionExecutionMetadata>compareByFirst()); + Collections.sort(actions, comparing(arg -> arg.first)); buffer.append("\n " + status + ":"); diff --git a/src/main/java/com/google/devtools/build/lib/actions/ActionInputHelper.java b/src/main/java/com/google/devtools/build/lib/actions/ActionInputHelper.java index c4567d8ce4..1a19d281d3 100644 --- a/src/main/java/com/google/devtools/build/lib/actions/ActionInputHelper.java +++ b/src/main/java/com/google/devtools/build/lib/actions/ActionInputHelper.java @@ -129,19 +129,11 @@ public final class ActionInputHelper { return fromPath(path.getPathString()); } - private static final Function<String, ActionInput> FROM_PATH = - new Function<String, ActionInput>() { - @Override - public ActionInput apply(String path) { - return fromPath(path); - } - }; - /** * Creates a sequence of {@link ActionInput}s from a sequence of string paths. */ public static Collection<ActionInput> fromPaths(Collection<String> paths) { - return Collections2.transform(paths, FROM_PATH); + return Collections2.transform(paths, ActionInputHelper::fromPath); } /** @@ -178,13 +170,8 @@ public final class ActionInputHelper { final Artifact parent, Iterable<? extends PathFragment> parentRelativePaths) { Preconditions.checkState(parent.isTreeArtifact(), "Given parent %s must be a TreeArtifact", parent); - return Iterables.transform(parentRelativePaths, - new Function<PathFragment, TreeFileArtifact>() { - @Override - public TreeFileArtifact apply(PathFragment pathFragment) { - return treeFileArtifact(parent, pathFragment); - } - }); + return Iterables.transform( + parentRelativePaths, pathFragment -> treeFileArtifact(parent, pathFragment)); } /** Returns a Set of TreeFileArtifacts with the given parent and parent-relative paths. */ @@ -224,12 +211,7 @@ public final class ActionInputHelper { /** Formatter for execPath String output. Public because {@link Artifact} uses it directly. */ public static final Function<ActionInput, String> EXEC_PATH_STRING_FORMATTER = - new Function<ActionInput, String>() { - @Override - public String apply(ActionInput input) { - return input.getExecPathString(); - } - }; + ActionInput::getExecPathString; public static Iterable<String> toExecPaths(Iterable<? extends ActionInput> artifacts) { return Iterables.transform(artifacts, EXEC_PATH_STRING_FORMATTER); diff --git a/src/main/java/com/google/devtools/build/lib/actions/ActionLookupValue.java b/src/main/java/com/google/devtools/build/lib/actions/ActionLookupValue.java index 9fdbe1ca8b..6b07feec64 100644 --- a/src/main/java/com/google/devtools/build/lib/actions/ActionLookupValue.java +++ b/src/main/java/com/google/devtools/build/lib/actions/ActionLookupValue.java @@ -14,7 +14,6 @@ package com.google.devtools.build.lib.actions; import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; import com.google.common.base.MoreObjects; import com.google.common.base.MoreObjects.ToStringHelper; import com.google.common.collect.ImmutableList; @@ -157,14 +156,7 @@ public class ActionLookupValue implements SkyValue { public static Map<Artifact, ActionAnalysisMetadata> getMapForConsistencyCheck( Map<Artifact, Integer> generatingActionIndex, final List<? extends ActionAnalysisMetadata> actions) { - return Maps.transformValues( - generatingActionIndex, - new Function<Integer, ActionAnalysisMetadata>() { - @Override - public ActionAnalysisMetadata apply(Integer index) { - return actions.get(index); - } - }); + return Maps.transformValues(generatingActionIndex, actions::get); } /** diff --git a/src/main/java/com/google/devtools/build/lib/actions/Artifact.java b/src/main/java/com/google/devtools/build/lib/actions/Artifact.java index 4a956db6aa..05d66df2d4 100644 --- a/src/main/java/com/google/devtools/build/lib/actions/Artifact.java +++ b/src/main/java/com/google/devtools/build/lib/actions/Artifact.java @@ -14,6 +14,9 @@ package com.google.devtools.build.lib.actions; +import static com.google.common.collect.ImmutableList.toImmutableList; +import static java.util.Comparator.comparing; + import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.base.Functions; @@ -21,7 +24,7 @@ import com.google.common.base.Joiner; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; -import com.google.common.collect.Ordering; +import com.google.common.collect.Streams; import com.google.devtools.build.lib.actions.ActionAnalysisMetadata.MiddlemanType; import com.google.devtools.build.lib.cmdline.Label; import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable; @@ -104,32 +107,23 @@ import javax.annotation.Nullable; public class Artifact implements FileType.HasFilename, ActionInput, SkylarkValue, Comparable<Object> { - /** - * Compares artifact according to their exec paths. Sorts null values first. - */ - public static final Comparator<Artifact> EXEC_PATH_COMPARATOR = new Comparator<Artifact>() { - @Override - public int compare(Artifact a, Artifact b) { - if (a == b) { - return 0; - } else if (a == null) { - return -1; - } else if (b == null) { - return -1; - } else { - return a.execPath.compareTo(b.execPath); - } - } - }; + /** Compares artifact according to their exec paths. Sorts null values first. */ + public static final Comparator<Artifact> EXEC_PATH_COMPARATOR = + (a, b) -> { + if (a == b) { + return 0; + } else if (a == null) { + return -1; + } else if (b == null) { + return -1; + } else { + return a.execPath.compareTo(b.execPath); + } + }; /** Compares artifacts according to their root relative paths. */ public static final Comparator<Artifact> ROOT_RELATIVE_PATH_COMPARATOR = - new Comparator<Artifact>() { - @Override - public int compare(Artifact lhs, Artifact rhs) { - return lhs.getRootRelativePath().compareTo(rhs.getRootRelativePath()); - } - }; + comparing(Artifact::getRootRelativePath); @Override public int compareTo(Object o) { @@ -154,25 +148,8 @@ public class Artifact public static final ImmutableList<Artifact> NO_ARTIFACTS = ImmutableList.of(); - /** - * A Predicate that evaluates to true if the Artifact is not a middleman artifact. - */ - public static final Predicate<Artifact> MIDDLEMAN_FILTER = new Predicate<Artifact>() { - @Override - public boolean apply(Artifact input) { - return !input.isMiddlemanArtifact(); - } - }; - - /** - * A Predicate that evaluates to true if the Artifact <b>is</b> a tree artifact. - */ - public static final Predicate<Artifact> IS_TREE_ARTIFACT = new Predicate<Artifact>() { - @Override - public boolean apply(Artifact input) { - return input.isTreeArtifact(); - } - }; + /** A Predicate that evaluates to true if the Artifact is not a middleman artifact. */ + public static final Predicate<Artifact> MIDDLEMAN_FILTER = input -> !input.isMiddlemanArtifact(); private final int hashCode; private final Path path; @@ -664,35 +641,12 @@ public class Artifact return result; } - //--------------------------------------------------------------------------- + // --------------------------------------------------------------------------- // Static methods to assist in working with Artifacts - /** - * Formatter for execPath PathFragment output. - */ - private static final Function<Artifact, PathFragment> EXEC_PATH_FORMATTER = - new Function<Artifact, PathFragment>() { - @Override - public PathFragment apply(Artifact input) { - return input.getExecPath(); - } - }; - + /** Formatter for execPath PathFragment output. */ public static final Function<Artifact, String> ROOT_RELATIVE_PATH_STRING = - new Function<Artifact, String>() { - @Override - public String apply(Artifact artifact) { - return artifact.getRootRelativePath().getPathString(); - } - }; - - public static final Function<Artifact, String> ABSOLUTE_PATH_STRING = - new Function<Artifact, String>() { - @Override - public String apply(Artifact artifact) { - return artifact.getPath().getPathString(); - } - }; + artifact -> artifact.getRootRelativePath().getPathString(); /** * Converts a collection of artifacts into execution-time path strings, and @@ -724,7 +678,7 @@ public class Artifact public static Iterable<String> toAbsolutePaths(Iterable<Artifact> artifacts) { return Iterables.transform( Iterables.filter(artifacts, MIDDLEMAN_FILTER), - ABSOLUTE_PATH_STRING); + artifact -> artifact.getPath().getPathString()); } /** @@ -734,7 +688,7 @@ public class Artifact public static Iterable<String> toRootRelativePaths(Iterable<Artifact> artifacts) { return Iterables.transform( Iterables.filter(artifacts, MIDDLEMAN_FILTER), - ROOT_RELATIVE_PATH_STRING); + artifact -> artifact.getRootRelativePath().getPathString()); } /** @@ -800,7 +754,7 @@ public class Artifact */ public static void addExpandedExecPaths(Iterable<Artifact> artifacts, Collection<PathFragment> output, ArtifactExpander artifactExpander) { - addExpandedArtifacts(artifacts, output, EXEC_PATH_FORMATTER, artifactExpander); + addExpandedArtifacts(artifacts, output, Artifact::getExecPath, artifactExpander); } /** @@ -906,15 +860,14 @@ public class Artifact * Converts artifacts into their exec paths. Returns an immutable list. */ public static List<PathFragment> asPathFragments(Iterable<? extends Artifact> artifacts) { - return ImmutableList.copyOf(Iterables.transform(artifacts, EXEC_PATH_FORMATTER)); + return Streams.stream(artifacts).map(Artifact::getExecPath).collect(toImmutableList()); } /** * Returns the exec paths of the input artifacts in alphabetical order. */ public static ImmutableList<PathFragment> asSortedPathFragments(Iterable<Artifact> input) { - return Ordering.natural().immutableSortedCopy(Iterables.transform( - input, EXEC_PATH_FORMATTER)); + return Streams.stream(input).map(Artifact::getExecPath).sorted().collect(toImmutableList()); } diff --git a/src/main/java/com/google/devtools/build/lib/actions/ExecutionRequirements.java b/src/main/java/com/google/devtools/build/lib/actions/ExecutionRequirements.java index 74e2eae16a..46ff4b0a82 100644 --- a/src/main/java/com/google/devtools/build/lib/actions/ExecutionRequirements.java +++ b/src/main/java/com/google/devtools/build/lib/actions/ExecutionRequirements.java @@ -116,29 +116,26 @@ public class ExecutionRequirements { ParseableRequirement.create( "cpu:<int>", Pattern.compile("cpu:(.+)"), - new Function<String, String>() { - @Override - public String apply(String s) { - Preconditions.checkNotNull(s); - - int value; - try { - value = Integer.parseInt(s); - } catch (NumberFormatException e) { - return "can't be parsed as an integer"; - } - - // De-and-reserialize & compare to only allow canonical integer formats. - if (!Integer.toString(value).equals(s)) { - return "must be in canonical format (e.g. '4' instead of '+04')"; - } - - if (value < 1) { - return "can't be zero or negative"; - } - - return null; + s -> { + Preconditions.checkNotNull(s); + + int value; + try { + value = Integer.parseInt(s); + } catch (NumberFormatException e) { + return "can't be parsed as an integer"; } + + // De-and-reserialize & compare to only allow canonical integer formats. + if (!Integer.toString(value).equals(s)) { + return "must be in canonical format (e.g. '4' instead of '+04')"; + } + + if (value < 1) { + return "can't be zero or negative"; + } + + return null; }); /** If an action supports running in persistent worker mode. */ diff --git a/src/main/java/com/google/devtools/build/lib/analysis/platform/PlatformProviderUtils.java b/src/main/java/com/google/devtools/build/lib/analysis/platform/PlatformProviderUtils.java index 7a5d06d969..73664f7b04 100644 --- a/src/main/java/com/google/devtools/build/lib/analysis/platform/PlatformProviderUtils.java +++ b/src/main/java/com/google/devtools/build/lib/analysis/platform/PlatformProviderUtils.java @@ -14,7 +14,6 @@ package com.google.devtools.build.lib.analysis.platform; -import com.google.common.base.Function; import com.google.common.collect.Iterables; import com.google.devtools.build.lib.analysis.SkylarkProviderCollection; import com.google.devtools.build.lib.util.Preconditions; @@ -35,14 +34,7 @@ public class PlatformProviderUtils { /** Retrieves and casts {@link PlatformInfo} providers from the given targets. */ public static Iterable<PlatformInfo> platforms( Iterable<? extends SkylarkProviderCollection> targets) { - return Iterables.transform( - targets, - new Function<SkylarkProviderCollection, PlatformInfo>() { - @Override - public PlatformInfo apply(SkylarkProviderCollection target) { - return platform(target); - } - }); + return Iterables.transform(targets, PlatformProviderUtils::platform); } /** Retrieves and casts the {@link ConstraintSettingInfo} provider from the given target. */ @@ -58,14 +50,7 @@ public class PlatformProviderUtils { /** Retrieves and casts {@link ConstraintSettingInfo} providers from the given targets. */ public static Iterable<ConstraintSettingInfo> constraintSettings( Iterable<? extends SkylarkProviderCollection> targets) { - return Iterables.transform( - targets, - new Function<SkylarkProviderCollection, ConstraintSettingInfo>() { - @Override - public ConstraintSettingInfo apply(SkylarkProviderCollection target) { - return constraintSetting(target); - } - }); + return Iterables.transform(targets, PlatformProviderUtils::constraintSetting); } /** Retrieves and casts the {@link ConstraintValueInfo} provider from the given target. */ @@ -81,13 +66,6 @@ public class PlatformProviderUtils { /** Retrieves and casts {@link ConstraintValueInfo} providers from the given targets. */ public static Iterable<ConstraintValueInfo> constraintValues( Iterable<? extends SkylarkProviderCollection> targets) { - return Iterables.transform( - targets, - new Function<SkylarkProviderCollection, ConstraintValueInfo>() { - @Override - public ConstraintValueInfo apply(SkylarkProviderCollection target) { - return constraintValue(target); - } - }); + return Iterables.transform(targets, PlatformProviderUtils::constraintValue); } } diff --git a/src/main/java/com/google/devtools/build/lib/bazel/BazelWorkspaceStatusModule.java b/src/main/java/com/google/devtools/build/lib/bazel/BazelWorkspaceStatusModule.java index 80618a7aba..bb77abc020 100644 --- a/src/main/java/com/google/devtools/build/lib/bazel/BazelWorkspaceStatusModule.java +++ b/src/main/java/com/google/devtools/build/lib/bazel/BazelWorkspaceStatusModule.java @@ -15,13 +15,11 @@ package com.google.devtools.build.lib.bazel; import static com.google.common.base.StandardSystemProperty.USER_NAME; import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.stream.Collectors.joining; -import com.google.common.base.Function; -import com.google.common.base.Joiner; import com.google.common.base.Supplier; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Iterables; import com.google.common.eventbus.Subscribe; import com.google.devtools.build.lib.actions.ActionExecutionContext; import com.google.devtools.build.lib.actions.ActionExecutionException; @@ -59,11 +57,9 @@ import com.google.devtools.common.options.OptionsBase; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Map; -import java.util.Map.Entry; import java.util.Objects; import java.util.TreeMap; import java.util.UUID; -import javax.annotation.Nullable; /** * Provides information about the workspace (e.g. source control context, current machine, current @@ -164,16 +160,10 @@ public class BazelWorkspaceStatusModule extends BlazeModule { private static byte[] printStatusMap(Map<String, String> map) { String s = - Joiner.on("\n") - .join( - Iterables.transform( - map.entrySet(), - new Function<Map.Entry<String, String>, String>() { - @Override - public String apply(@Nullable Entry<String, String> entry) { - return entry.getKey() + " " + entry.getValue(); - } - })); + map.entrySet() + .stream() + .map(entry -> entry.getKey() + " " + entry.getValue()) + .collect(joining("\n")); s += "\n"; return s.getBytes(StandardCharsets.UTF_8); } diff --git a/src/main/java/com/google/devtools/build/lib/bazel/repository/downloader/HttpConnectorMultiplexer.java b/src/main/java/com/google/devtools/build/lib/bazel/repository/downloader/HttpConnectorMultiplexer.java index 374c83e131..48960e1c01 100644 --- a/src/main/java/com/google/devtools/build/lib/bazel/repository/downloader/HttpConnectorMultiplexer.java +++ b/src/main/java/com/google/devtools/build/lib/bazel/repository/downloader/HttpConnectorMultiplexer.java @@ -14,10 +14,10 @@ package com.google.devtools.build.lib.bazel.repository.downloader; -import com.google.common.base.Function; +import static com.google.common.collect.ImmutableSortedSet.toImmutableSortedSet; + import com.google.common.base.Preconditions; import com.google.common.base.Predicates; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Ordering; import com.google.devtools.build.lib.analysis.BlazeVersionInfo; @@ -319,19 +319,11 @@ final class HttpConnectorMultiplexer { } private static String describeErrors(Collection<Throwable> errors) { - return - FluentIterable - .from(errors) - .transform( - new Function<Throwable, String>() { - @Nullable - @Override - public String apply(Throwable workerError) { - return workerError.getMessage(); - } - }) - .filter(Predicates.notNull()) - .toSortedSet(Ordering.natural()) - .toString(); + return errors + .stream() + .map(Throwable::getMessage) + .filter(Predicates.notNull()) + .collect(toImmutableSortedSet(Ordering.natural())) + .toString(); } } diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryRule.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryRule.java index 14ea5a8da9..1c29539bfb 100644 --- a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryRule.java +++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryRule.java @@ -30,7 +30,6 @@ import com.google.devtools.build.lib.packages.RuleClass.Builder.RuleClassType; import com.google.devtools.build.lib.rules.repository.WorkspaceBaseRule; import com.google.devtools.build.lib.rules.repository.WorkspaceConfiguredTargetFactory; import java.util.Map; -import javax.annotation.Nullable; /** * Definition of the {@code android_ndk_repository} rule. @@ -39,20 +38,15 @@ public class AndroidNdkRepositoryRule implements RuleDefinition { public static final String NAME = "android_ndk_repository"; private static final Function<? super Rule, Map<String, Label>> BINDINGS_FUNCTION = - new Function< Rule, Map<String, Label>>() { - @Nullable - @Override - public Map<String, Label> apply(Rule rule) { - - String defaultToolchainName = - AndroidNdkRepositoryFunction.createToolchainName(StlImpls.DEFAULT_STL_NAME); - - return ImmutableMap.of( - "android/crosstool", - Label.parseAbsoluteUnchecked("@" + rule.getName() + "//:" + defaultToolchainName), - "android_ndk_for_testing", - Label.parseAbsoluteUnchecked("@" + rule.getName() + "//:files")); - } + rule -> { + String defaultToolchainName = + AndroidNdkRepositoryFunction.createToolchainName(StlImpls.DEFAULT_STL_NAME); + + return ImmutableMap.of( + "android/crosstool", + Label.parseAbsoluteUnchecked("@" + rule.getName() + "//:" + defaultToolchainName), + "android_ndk_for_testing", + Label.parseAbsoluteUnchecked("@" + rule.getName() + "//:files")); }; @Override diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/AndroidSdkRepositoryFunction.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/AndroidSdkRepositoryFunction.java index 8b3c32b42d..0334c4478f 100644 --- a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/AndroidSdkRepositoryFunction.java +++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/AndroidSdkRepositoryFunction.java @@ -13,16 +13,15 @@ // limitations under the License. package com.google.devtools.build.lib.bazel.rules.android; +import static com.google.common.collect.ImmutableMap.toImmutableMap; + import com.android.repository.Revision; -import com.google.common.base.Function; -import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.collect.Maps.EntryTransformer; +import com.google.common.collect.Streams; import com.google.devtools.build.lib.analysis.BlazeDirectories; import com.google.devtools.build.lib.analysis.RuleDefinition; import com.google.devtools.build.lib.packages.Rule; @@ -51,7 +50,6 @@ import com.google.devtools.build.skyframe.ValueOrException; import java.io.IOException; import java.util.Map; import java.util.Properties; -import javax.annotation.Nullable; /** * Implementation of the {@code android_sdk_repository} rule. @@ -228,22 +226,10 @@ public class AndroidSdkRepositoryFunction extends RepositoryFunction { // All local maven repositories that are shipped in the Android SDK. // TODO(ajmichael): Create SkyKeys so that if the SDK changes, this function will get rerun. Iterable<Path> localMavenRepositories = - Lists.transform( - LOCAL_MAVEN_REPOSITORIES, - new Function<String, Path>() { - @Override - public Path apply(String pathFragment) { - return outputDirectory.getRelative(pathFragment); - } - }); + Lists.transform(LOCAL_MAVEN_REPOSITORIES, outputDirectory::getRelative); try { SdkMavenRepository sdkExtrasRepository = - SdkMavenRepository.create(Iterables.filter(localMavenRepositories, new Predicate<Path>() { - @Override - public boolean apply(@Nullable Path path) { - return path.isDirectory(); - } - })); + SdkMavenRepository.create(Iterables.filter(localMavenRepositories, Path::isDirectory)); sdkExtrasRepository.writeBuildFiles(outputDirectory); buildFile = buildFile.replace( "%exported_files%", sdkExtrasRepository.getExportsFiles(outputDirectory)); @@ -412,29 +398,15 @@ public class AndroidSdkRepositoryFunction extends RepositoryFunction { final Path root, final PathFragment path, DirectoryListingValue directory, Environment env) throws RepositoryFunctionException, InterruptedException { Map<PathFragment, SkyKey> skyKeysForSubdirectoryLookups = - Maps.transformEntries( - Maps.uniqueIndex( - Iterables.filter( - directory.getDirents(), - new Predicate<Dirent>() { - @Override - public boolean apply(Dirent dirent) { - return dirent.getType().equals(Dirent.Type.DIRECTORY); - } - }), - new Function<Dirent, PathFragment>() { - @Override - public PathFragment apply(Dirent input) { - return path.getRelative(input.getName()); - } - }), - new EntryTransformer<PathFragment, Dirent, SkyKey>() { - @Override - public SkyKey transformEntry(PathFragment key, Dirent value) { - return DirectoryListingValue.key( - RootedPath.toRootedPath(root, root.getRelative(key))); - } - }); + Streams.stream(directory.getDirents()) + .filter(dirent -> dirent.getType().equals(Dirent.Type.DIRECTORY)) + .collect( + toImmutableMap( + input -> path.getRelative(input.getName()), + input -> + DirectoryListingValue.key( + RootedPath.toRootedPath( + root, root.getRelative(path).getRelative(input.getName()))))); Map<SkyKey, ValueOrException<InconsistentFilesystemException>> values = env.getValuesOrThrow( diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/AndroidSdkRepositoryRule.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/AndroidSdkRepositoryRule.java index ba0f237085..ae2794941f 100644 --- a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/AndroidSdkRepositoryRule.java +++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/AndroidSdkRepositoryRule.java @@ -29,7 +29,6 @@ import com.google.devtools.build.lib.packages.RuleClass.Builder.RuleClassType; import com.google.devtools.build.lib.rules.repository.WorkspaceBaseRule; import com.google.devtools.build.lib.rules.repository.WorkspaceConfiguredTargetFactory; import java.util.Map; -import javax.annotation.Nullable; /** * Definition of the {@code android_sdk_repository} rule. @@ -38,21 +37,17 @@ public class AndroidSdkRepositoryRule implements RuleDefinition { public static final String NAME = "android_sdk_repository"; private static final Function<? super Rule, Map<String, Label>> BINDINGS_FUNCTION = - new Function<Rule, Map<String, Label>>() { - @Nullable - @Override - public Map<String, Label> apply(Rule rule) { - String prefix = "@" + rule.getName() + "//:"; - ImmutableMap.Builder<String, Label> builder = ImmutableMap.builder(); - builder.put("android/sdk", Label.parseAbsoluteUnchecked(prefix + "sdk")); - builder.put( - "android/dx_jar_import", Label.parseAbsoluteUnchecked(prefix + "dx_jar_import")); - builder.put("android_sdk_for_testing", Label.parseAbsoluteUnchecked(prefix + "files")); - builder.put( - "has_androidsdk", - Label.parseAbsoluteUnchecked("@bazel_tools//tools/android:always_true")); - return builder.build(); - } + rule -> { + String prefix = "@" + rule.getName() + "//:"; + ImmutableMap.Builder<String, Label> builder = ImmutableMap.builder(); + builder.put("android/sdk", Label.parseAbsoluteUnchecked(prefix + "sdk")); + builder.put( + "android/dx_jar_import", Label.parseAbsoluteUnchecked(prefix + "dx_jar_import")); + builder.put("android_sdk_for_testing", Label.parseAbsoluteUnchecked(prefix + "files")); + builder.put( + "has_androidsdk", + Label.parseAbsoluteUnchecked("@bazel_tools//tools/android:always_true")); + return builder.build(); }; @Override diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/SdkMavenRepository.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/SdkMavenRepository.java index 136da18742..1efca1efde 100644 --- a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/SdkMavenRepository.java +++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/SdkMavenRepository.java @@ -14,7 +14,6 @@ package com.google.devtools.build.lib.bazel.rules.android; import com.google.auto.value.AutoValue; -import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; @@ -25,7 +24,6 @@ import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; -import javax.annotation.Nullable; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; @@ -124,12 +122,8 @@ final class SdkMavenRepository { static SdkMavenRepository create(Iterable<Path> mavenRepositories) throws IOException { Collection<Path> pomPaths = new ArrayList<>(); for (Path mavenRepository : mavenRepositories) { - pomPaths.addAll(FileSystemUtils.traverseTree(mavenRepository, new Predicate<Path>() { - @Override - public boolean apply(@Nullable Path path) { - return path.toString().endsWith(".pom"); - } - })); + pomPaths.addAll( + FileSystemUtils.traverseTree(mavenRepository, path -> path.toString().endsWith(".pom"))); } ImmutableSortedSet.Builder<Pom> poms = diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/NdkPaths.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/NdkPaths.java index c59be8216c..45b62deea6 100644 --- a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/NdkPaths.java +++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/NdkPaths.java @@ -14,7 +14,6 @@ package com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools; -import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.devtools.build.lib.rules.cpp.CppConfiguration; @@ -150,18 +149,14 @@ public class NdkPaths { + "/lib/gcc/%targetPlatform%/%gccVersion%/%includeFolderName%"; return Lists.transform( ImmutableList.of("include", "include-fixed"), - new Function<String, String>() { - @Override - public String apply(String includeFolderName) { - return toolchainIncludePathTemplate + includeFolderName -> + toolchainIncludePathTemplate .replace("%repositoryName%", repositoryName) .replace("%toolchainName%", toolchainName) .replace("%hostPlatform%", hostPlatform) .replace("%targetPlatform%", targetPlatform) .replace("%gccVersion%", gccVersion) - .replace("%includeFolderName%", includeFolderName); - } - }); + .replace("%includeFolderName%", includeFolderName)); } public String createBuiltinSysroot(String targetCpu) { diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/java/BazelJavaSemantics.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/java/BazelJavaSemantics.java index 293091f6fa..43307fb12f 100644 --- a/src/main/java/com/google/devtools/build/lib/bazel/rules/java/BazelJavaSemantics.java +++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/java/BazelJavaSemantics.java @@ -16,7 +16,6 @@ package com.google.devtools.build.lib.bazel.rules.java; import static com.google.common.base.Strings.isNullOrEmpty; -import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; @@ -354,15 +353,6 @@ public class BazelJavaSemantics implements JavaSemantics { */ private static class ComputedRelativeClasspathsSubstitution extends ComputedSubstitution { private final JavaCommon javaCommon; - private static final Function<Artifact, String> PATHS_FROM_ARTIFACTS = - new Function<Artifact, String>() { - @Nullable - @Override - public String apply(@Nullable Artifact artifact) { - return artifact == null ? null : artifact.getRunfilesPathString(); - } - }; - public ComputedRelativeClasspathsSubstitution(JavaCommon javaCommon) { super(RELATIVE_CLASSPATHS_PLACEHOLDER); this.javaCommon = javaCommon; @@ -372,7 +362,9 @@ public class BazelJavaSemantics implements JavaSemantics { public String getValue() { // TODO(kush): Get this to work when runfilesEnabled=false, like in windows. Iterable<String> paths = - Iterables.transform(javaCommon.getRuntimeClasspath(), PATHS_FROM_ARTIFACTS); + Iterables.transform( + javaCommon.getRuntimeClasspath(), + artifact -> artifact == null ? null : artifact.getRunfilesPathString()); return Joiner.on(File.pathSeparatorChar).skipNulls().join(paths); } } diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/java/proto/BazelJavaLiteProtoLibraryRule.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/java/proto/BazelJavaLiteProtoLibraryRule.java index 5969c7aa5b..46f5a25859 100644 --- a/src/main/java/com/google/devtools/build/lib/bazel/rules/java/proto/BazelJavaLiteProtoLibraryRule.java +++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/java/proto/BazelJavaLiteProtoLibraryRule.java @@ -36,22 +36,10 @@ import com.google.devtools.build.lib.rules.java.JavaCompilationArgsProvider; import com.google.devtools.build.lib.rules.java.JavaConfiguration; import com.google.devtools.build.lib.rules.java.proto.JavaLiteProtoLibrary; import com.google.devtools.build.lib.rules.proto.ProtoLangToolchainProvider; -import javax.annotation.Nullable; /** Declaration of the {@code java_lite_proto_library} rule. */ public class BazelJavaLiteProtoLibraryRule implements RuleDefinition { - private static final Function<Rule, AspectParameters> ASPECT_PARAMETERS = - new Function<Rule, AspectParameters>() { - @Nullable - @Override - public AspectParameters apply(@Nullable Rule rule) { - return new AspectParameters.Builder() - .addAttribute(INJECTING_RULE_KIND_PARAMETER_KEY, "java_lite_proto_library") - .build(); - } - }; - private final BazelJavaLiteProtoAspect javaProtoAspect; public BazelJavaLiteProtoLibraryRule(BazelJavaLiteProtoAspect javaProtoAspect) { @@ -60,6 +48,12 @@ public class BazelJavaLiteProtoLibraryRule implements RuleDefinition { @Override public RuleClass build(RuleClass.Builder builder, RuleDefinitionEnvironment environment) { + Function<Rule, AspectParameters> aspectParameters = + rule -> + new AspectParameters.Builder() + .addAttribute(INJECTING_RULE_KIND_PARAMETER_KEY, "java_lite_proto_library") + .build(); + return builder .requiresConfigurationFragments(JavaConfiguration.class) /* <!-- #BLAZE_RULE(java_lite_proto_library).ATTRIBUTE(deps) --> @@ -70,7 +64,7 @@ public class BazelJavaLiteProtoLibraryRule implements RuleDefinition { attr("deps", LABEL_LIST) .allowedRuleClasses("proto_library") .allowedFileTypes() - .aspect(javaProtoAspect, ASPECT_PARAMETERS)) + .aspect(javaProtoAspect, aspectParameters)) .add(attr("strict_deps", BOOLEAN).value(true).undocumented("for migration")) .add( attr(PROTO_TOOLCHAIN_ATTR, LABEL) diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/java/proto/BazelJavaProtoLibraryRule.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/java/proto/BazelJavaProtoLibraryRule.java index 8c4ed4b81f..62e70cd2ed 100644 --- a/src/main/java/com/google/devtools/build/lib/bazel/rules/java/proto/BazelJavaProtoLibraryRule.java +++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/java/proto/BazelJavaProtoLibraryRule.java @@ -29,22 +29,10 @@ import com.google.devtools.build.lib.packages.RuleClass; import com.google.devtools.build.lib.rules.java.JavaCompilationArgsProvider; import com.google.devtools.build.lib.rules.java.JavaConfiguration; import com.google.devtools.build.lib.rules.java.proto.JavaProtoLibrary; -import javax.annotation.Nullable; /** Declaration of the {@code java_proto_library} rule. */ public class BazelJavaProtoLibraryRule implements RuleDefinition { - private static final Function<Rule, AspectParameters> ASPECT_PARAMETERS = - new Function<Rule, AspectParameters>() { - @Nullable - @Override - public AspectParameters apply(@Nullable Rule rule) { - return new AspectParameters.Builder() - .addAttribute(INJECTING_RULE_KIND_PARAMETER_KEY, "java_proto_library") - .build(); - } - }; - private final BazelJavaProtoAspect javaProtoAspect; public BazelJavaProtoLibraryRule(BazelJavaProtoAspect javaProtoAspect) { @@ -53,6 +41,12 @@ public class BazelJavaProtoLibraryRule implements RuleDefinition { @Override public RuleClass build(RuleClass.Builder builder, RuleDefinitionEnvironment environment) { + Function<Rule, AspectParameters> aspectParameters = + rule -> + new AspectParameters.Builder() + .addAttribute(INJECTING_RULE_KIND_PARAMETER_KEY, "java_proto_library") + .build(); + return builder .requiresConfigurationFragments(JavaConfiguration.class) /* <!-- #BLAZE_RULE(java_proto_library).ATTRIBUTE(deps) --> @@ -63,7 +57,7 @@ public class BazelJavaProtoLibraryRule implements RuleDefinition { attr("deps", LABEL_LIST) .allowedRuleClasses("proto_library") .allowedFileTypes() - .aspect(javaProtoAspect, ASPECT_PARAMETERS)) + .aspect(javaProtoAspect, aspectParameters)) .add(attr("strict_deps", BOOLEAN).value(true).undocumented("for migration")) .advertiseProvider(JavaCompilationArgsProvider.class) .build(); diff --git a/src/main/java/com/google/devtools/build/lib/buildeventservice/BuildEventServiceTransport.java b/src/main/java/com/google/devtools/build/lib/buildeventservice/BuildEventServiceTransport.java index 467ee8bb0c..0cf67ba959 100644 --- a/src/main/java/com/google/devtools/build/lib/buildeventservice/BuildEventServiceTransport.java +++ b/src/main/java/com/google/devtools/build/lib/buildeventservice/BuildEventServiceTransport.java @@ -176,50 +176,47 @@ public class BuildEventServiceTransport implements BuildEventTransport { shutdownFuture = SettableFuture.create(); uploaderExecutorService.execute( - new Runnable() { - @Override - public void run() { - try { - sendOrderedBuildEvent(besProtoUtil.streamFinished()); - - if (errorsReported) { - // If we encountered errors before and have already reported them, then we should - // not report them a second time. - return; - } - - if (bestEffortUpload) { - // TODO(buchgr): The code structure currently doesn't allow to enforce a timeout for - // best effort upload. - if (!uploadComplete.isDone()) { - report(INFO, "Asynchronous Build Event Protocol upload."); - } else { - Throwable uploadError = fromFuture(uploadComplete); + () -> { + try { + sendOrderedBuildEvent(besProtoUtil.streamFinished()); + + if (errorsReported) { + // If we encountered errors before and have already reported them, then we should + // not report them a second time. + return; + } - if (uploadError != null) { - report(WARNING, UPLOAD_FAILED_MESSAGE, uploadError.getMessage()); - } else { - report(INFO, UPLOAD_SUCCEEDED_MESSAGE); - } - } + if (bestEffortUpload) { + // TODO(buchgr): The code structure currently doesn't allow to enforce a timeout for + // best effort upload. + if (!uploadComplete.isDone()) { + report(INFO, "Asynchronous Build Event Protocol upload."); } else { - report(INFO, "Waiting for Build Event Protocol upload to finish."); - try { - if (Duration.ZERO.equals(uploadTimeout)) { - uploadComplete.get(); - } else { - uploadComplete.get(uploadTimeout.getMillis(), MILLISECONDS); - } + Throwable uploadError = fromFuture(uploadComplete); + + if (uploadError != null) { + report(WARNING, UPLOAD_FAILED_MESSAGE, uploadError.getMessage()); + } else { report(INFO, UPLOAD_SUCCEEDED_MESSAGE); - } catch (Exception e) { - uploadComplete.cancel(true); - reportErrorAndFailBuild(e); } } - } finally { - shutdownFuture.set(null); - uploaderExecutorService.shutdown(); + } else { + report(INFO, "Waiting for Build Event Protocol upload to finish."); + try { + if (Duration.ZERO.equals(uploadTimeout)) { + uploadComplete.get(); + } else { + uploadComplete.get(uploadTimeout.getMillis(), MILLISECONDS); + } + report(INFO, UPLOAD_SUCCEEDED_MESSAGE); + } catch (Exception e) { + uploadComplete.cancel(true); + reportErrorAndFailBuild(e); + } } + } finally { + shutdownFuture.set(null); + uploaderExecutorService.shutdown(); } }); @@ -347,53 +344,43 @@ public class BuildEventServiceTransport implements BuildEventTransport { } private void publishBuildEnqueuedEvent() throws Exception { - retryOnException(new Callable<Void>() { - @Override - public Void call() throws Exception { - publishLifecycleEvent(besProtoUtil.buildEnqueued()); - return null; - } - }); + retryOnException( + () -> { + publishLifecycleEvent(besProtoUtil.buildEnqueued()); + return null; + }); } private void publishInvocationStartedEvent() throws Exception { - retryOnException(new Callable<Void>() { - @Override - public Void call() throws Exception { - publishLifecycleEvent(besProtoUtil.invocationStarted()); - return null; - } - }); + retryOnException( + () -> { + publishLifecycleEvent(besProtoUtil.invocationStarted()); + return null; + }); } private void publishEventStream0() throws Exception { - retryOnException(new Callable<Void>() { - @Override - public Void call() throws Exception { - publishEventStream(); - return null; - } - }); + retryOnException( + () -> { + publishEventStream(); + return null; + }); } private void publishInvocationFinishedEvent(final Result result) throws Exception { - retryOnException(new Callable<Void>() { - @Override - public Void call() throws Exception { - publishLifecycleEvent(besProtoUtil.invocationFinished(result)); - return null; - } - }); + retryOnException( + () -> { + publishLifecycleEvent(besProtoUtil.invocationFinished(result)); + return null; + }); } private void publishBuildFinishedEvent(final Result result) throws Exception { - retryOnException(new Callable<Void>() { - @Override - public Void call() throws Exception { - publishLifecycleEvent(besProtoUtil.buildFinished(result)); - return null; - } - }); + retryOnException( + () -> { + publishLifecycleEvent(besProtoUtil.buildFinished(result)); + return null; + }); } } @@ -452,20 +439,17 @@ public class BuildEventServiceTransport implements BuildEventTransport { private static Function<PublishBuildToolEventStreamResponse, Void> ackCallback( final Deque<OrderedBuildEvent> pendingAck, final BuildEventServiceClient besClient) { - return new Function<PublishBuildToolEventStreamResponse, Void>() { - @Override - public Void apply(PublishBuildToolEventStreamResponse ack) { - long pendingSeq = - pendingAck.isEmpty() ? -1 : pendingAck.peekFirst().getSequenceNumber(); - long ackSeq = ack.getSequenceNumber(); - if (pendingSeq != ackSeq) { - besClient.abortStream(Status.INTERNAL - .augmentDescription(format("Expected ack %s but was %s.", pendingSeq, ackSeq))); - } else { - pendingAck.removeFirst(); - } - return null; + return ack -> { + long pendingSeq = pendingAck.isEmpty() ? -1 : pendingAck.peekFirst().getSequenceNumber(); + long ackSeq = ack.getSequenceNumber(); + if (pendingSeq != ackSeq) { + besClient.abortStream( + Status.INTERNAL.augmentDescription( + format("Expected ack %s but was %s.", pendingSeq, ackSeq))); + } else { + pendingAck.removeFirst(); } + return null; }; } diff --git a/src/main/java/com/google/devtools/build/lib/buildtool/SymlinkForest.java b/src/main/java/com/google/devtools/build/lib/buildtool/SymlinkForest.java index 3f9ac667fc..bcea3d8ae5 100644 --- a/src/main/java/com/google/devtools/build/lib/buildtool/SymlinkForest.java +++ b/src/main/java/com/google/devtools/build/lib/buildtool/SymlinkForest.java @@ -26,7 +26,6 @@ import com.google.devtools.build.lib.util.Preconditions; import com.google.devtools.build.lib.vfs.FileSystemUtils; import com.google.devtools.build.lib.vfs.Path; import com.google.devtools.build.lib.vfs.PathFragment; - import java.io.IOException; import java.util.Map; import java.util.Set; @@ -123,11 +122,7 @@ class SymlinkForest { continue; } PackageIdentifier dir = createInRepo(pkgId, pkgId.getPackageFragment().subFragment(0, i)); - Set<Path> roots = dirRootsMap.get(dir); - if (roots == null) { - roots = Sets.newHashSet(); - dirRootsMap.put(dir, roots); - } + Set<Path> roots = dirRootsMap.computeIfAbsent(dir, k -> Sets.newHashSet()); roots.add(pkgRoot); } } diff --git a/src/main/java/com/google/devtools/build/lib/cmdline/Label.java b/src/main/java/com/google/devtools/build/lib/cmdline/Label.java index 3767ed721b..b689f6daa7 100644 --- a/src/main/java/com/google/devtools/build/lib/cmdline/Label.java +++ b/src/main/java/com/google/devtools/build/lib/cmdline/Label.java @@ -13,7 +13,6 @@ // limitations under the License. package com.google.devtools.build.lib.cmdline; -import com.google.common.base.Function; import com.google.common.collect.ComparisonChain; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Interner; @@ -153,15 +152,6 @@ public final class Label implements Comparable<Label>, Serializable, SkylarkPrin return parseAbsoluteUnchecked(absName, true); } - /** A long way to say '(String) s -> parseAbsoluteUnchecked(s)'. */ - public static final Function<String, Label> PARSE_ABSOLUTE_UNCHECKED = - new Function<String, Label>() { - @Override - public Label apply(@Nullable String s) { - return s == null ? null : parseAbsoluteUnchecked(s); - } - }; - /** * Factory for Labels from separate components. * diff --git a/src/main/java/com/google/devtools/build/lib/collect/CollectionUtils.java b/src/main/java/com/google/devtools/build/lib/collect/CollectionUtils.java index 192a411b26..341e750b87 100644 --- a/src/main/java/com/google/devtools/build/lib/collect/CollectionUtils.java +++ b/src/main/java/com/google/devtools/build/lib/collect/CollectionUtils.java @@ -20,7 +20,6 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.devtools.build.lib.collect.nestedset.NestedSet; import com.google.devtools.build.lib.util.Preconditions; - import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; @@ -82,12 +81,7 @@ public final class CollectionUtils { */ public static <T> Collection<Set<T>> partition(Collection<T> elements, final EquivalenceRelation<T> equivalenceRelation) { - return partition(elements, new Comparator<T>() { - @Override - public int compare(T o1, T o2) { - return equivalenceRelation.compare(o1, o2); - } - }); + return partition(elements, (Comparator<T>) equivalenceRelation::compare); } /** diff --git a/src/main/java/com/google/devtools/build/lib/collect/nestedset/NestedSet.java b/src/main/java/com/google/devtools/build/lib/collect/nestedset/NestedSet.java index ab24d0a155..74e01eeeca 100644 --- a/src/main/java/com/google/devtools/build/lib/collect/nestedset/NestedSet.java +++ b/src/main/java/com/google/devtools/build/lib/collect/nestedset/NestedSet.java @@ -13,11 +13,11 @@ // limitations under the License. package com.google.devtools.build.lib.collect.nestedset; +import static java.util.stream.Collectors.joining; + import com.google.common.base.Function; -import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; import com.google.devtools.build.lib.collect.CompactHashSet; import java.util.AbstractCollection; import java.util.Arrays; @@ -26,6 +26,7 @@ import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.Set; +import java.util.stream.Stream; import javax.annotation.Nullable; /** @@ -245,8 +246,9 @@ public final class NestedSet<E> implements Iterable<E> { // TODO: this leaves LINK_ORDER backwards private static String childrenToString(Object children) { if (children instanceof Object[]) { - return "{" + Joiner.on(", ").join(Iterables.transform( - Arrays.asList((Object[]) children), Stringer.INSTANCE)) + "}"; + return "{" + + Stream.of((Object[]) children).map(Stringer.INSTANCE).collect(joining(", ")) + + "}"; } else { return children.toString(); } diff --git a/src/main/java/com/google/devtools/build/lib/concurrent/AbstractQueueVisitor.java b/src/main/java/com/google/devtools/build/lib/concurrent/AbstractQueueVisitor.java index 7c0809d431..3eeb9377ea 100644 --- a/src/main/java/com/google/devtools/build/lib/concurrent/AbstractQueueVisitor.java +++ b/src/main/java/com/google/devtools/build/lib/concurrent/AbstractQueueVisitor.java @@ -44,19 +44,14 @@ public class AbstractQueueVisitor implements QuiescingExecutor { * ThreadPoolExecutor}. */ public static final Function<ExecutorParams, ThreadPoolExecutor> EXECUTOR_FACTORY = - new Function<ExecutorParams, ThreadPoolExecutor>() { - @Override - public ThreadPoolExecutor apply(ExecutorParams p) { - return new ThreadPoolExecutor( + p -> + new ThreadPoolExecutor( /*corePoolSize=*/ p.getParallelism(), /*maximumPoolSize=*/ p.getParallelism(), p.getKeepAliveTime(), p.getUnits(), p.getWorkQueue(), new ThreadFactoryBuilder().setNameFormat(p.getPoolName() + " %d").build()); - } - }; - /** * The most severe unhandled exception thrown by a worker thread, according to * {@link #errorClassifier}. This exception gets propagated to the calling thread of diff --git a/src/main/java/com/google/devtools/build/lib/concurrent/Sharder.java b/src/main/java/com/google/devtools/build/lib/concurrent/Sharder.java index d43c0ffb57..008b9c78f7 100644 --- a/src/main/java/com/google/devtools/build/lib/concurrent/Sharder.java +++ b/src/main/java/com/google/devtools/build/lib/concurrent/Sharder.java @@ -13,11 +13,9 @@ // limitations under the License. package com.google.devtools.build.lib.concurrent; -import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.devtools.build.lib.util.Preconditions; - import java.util.Collections; import java.util.Iterator; import java.util.List; @@ -61,11 +59,6 @@ public final class Sharder<T> implements Iterable<List<T>> { @Override public Iterator<List<T>> iterator() { - return Iterables.filter(shards, new Predicate<List<T>>() { - @Override - public boolean apply(List<T> list) { - return !list.isEmpty(); - } - }).iterator(); + return Iterables.filter(shards, list -> !list.isEmpty()).iterator(); } } diff --git a/src/main/java/com/google/devtools/build/lib/concurrent/ThrowableRecordingRunnableWrapper.java b/src/main/java/com/google/devtools/build/lib/concurrent/ThrowableRecordingRunnableWrapper.java index 870d92b781..f66e23070f 100644 --- a/src/main/java/com/google/devtools/build/lib/concurrent/ThrowableRecordingRunnableWrapper.java +++ b/src/main/java/com/google/devtools/build/lib/concurrent/ThrowableRecordingRunnableWrapper.java @@ -14,11 +14,9 @@ package com.google.devtools.build.lib.concurrent; import com.google.devtools.build.lib.util.Preconditions; - import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Level; import java.util.logging.Logger; - import javax.annotation.Nullable; /** @@ -43,15 +41,12 @@ public class ThrowableRecordingRunnableWrapper { } public Runnable wrap(final Runnable runnable) { - return new Runnable() { - @Override - public void run() { - try { - runnable.run(); - } catch (Throwable error) { - errorRef.compareAndSet(null, error); - LOG.log(Level.SEVERE, "Error thrown by runnable in " + name, error); - } + return () -> { + try { + runnable.run(); + } catch (Throwable error) { + errorRef.compareAndSet(null, error); + LOG.log(Level.SEVERE, "Error thrown by runnable in " + name, error); } }; } diff --git a/src/main/java/com/google/devtools/build/lib/events/EventCollector.java b/src/main/java/com/google/devtools/build/lib/events/EventCollector.java index 0d309439db..46bf3adf3f 100644 --- a/src/main/java/com/google/devtools/build/lib/events/EventCollector.java +++ b/src/main/java/com/google/devtools/build/lib/events/EventCollector.java @@ -13,10 +13,8 @@ // limitations under the License. package com.google.devtools.build.lib.events; -import com.google.common.base.Predicate; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; - import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; @@ -84,12 +82,7 @@ public final class EventCollector extends AbstractEventHandler implements Iterab * scenario where there may still be concurrent modifications to the collector. */ public Iterable<Event> filtered(final EventKind eventKind) { - return Iterables.filter(collected, new Predicate<Event>() { - @Override - public boolean apply(Event event) { - return event.getKind() == eventKind; - } - }); + return Iterables.filter(collected, event -> event.getKind() == eventKind); } /** diff --git a/src/main/java/com/google/devtools/build/lib/graph/DFS.java b/src/main/java/com/google/devtools/build/lib/graph/DFS.java index 5682baa4d9..9cf947e0dc 100644 --- a/src/main/java/com/google/devtools/build/lib/graph/DFS.java +++ b/src/main/java/com/google/devtools/build/lib/graph/DFS.java @@ -14,8 +14,9 @@ package com.google.devtools.build.lib.graph; -import com.google.common.collect.Ordering; +import static java.util.Comparator.comparing; +import com.google.common.collect.Ordering; import java.util.Collection; import java.util.Collections; import java.util.Comparator; @@ -70,12 +71,7 @@ public class DFS<T> { if (edgeOrder == null) { this.edgeOrder = null; } else { - this.edgeOrder = new Comparator<Node<T>>() { - @Override - public int compare(Node<T> o1, Node<T> o2) { - return edgeOrder.compare(o1.getLabel(), o2.getLabel()); - } - }; + this.edgeOrder = comparing(Node::getLabel, edgeOrder::compare); } } diff --git a/src/main/java/com/google/devtools/build/lib/graph/Digraph.java b/src/main/java/com/google/devtools/build/lib/graph/Digraph.java index c2e7d0d378..b6d913f2b1 100644 --- a/src/main/java/com/google/devtools/build/lib/graph/Digraph.java +++ b/src/main/java/com/google/devtools/build/lib/graph/Digraph.java @@ -14,10 +14,12 @@ package com.google.devtools.build.lib.graph; +import static java.util.Comparator.comparing; +import static java.util.Comparator.comparingLong; + import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import com.google.common.collect.Ordering; - import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -29,7 +31,6 @@ import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Set; - import javax.annotation.Nullable; /** @@ -384,10 +385,7 @@ public final class Digraph<T> implements Cloneable { if (label == null) { throw new NullPointerException(); } - Node<T> n = nodes.get(label); - if (n == null) { - nodes.put(label, n = new Node<T>(label, nextHashCode++)); - } + Node<T> n = nodes.computeIfAbsent(label, k -> new Node<T>(k, nextHashCode++)); return n; } @@ -827,14 +825,10 @@ public final class Digraph<T> implements Cloneable { // number of paths of high-order nodes making the time consumption explode. // For perfect results we should reorder the set each time we add a new edge but this would // be too expensive, so this is a good enough approximation. - final PriorityQueue<Node<T>> reachables = new PriorityQueue<>(toRemove.size(), - new Comparator<Node<T>>() { - @Override - public int compare(Node<T> o1, Node<T> o2) { - return Long.compare((long) o1.numPredecessors() * (long) o1.numSuccessors(), - (long) o2.numPredecessors() * (long) o2.numSuccessors()); - } - }); + final PriorityQueue<Node<T>> reachables = + new PriorityQueue<>( + toRemove.size(), + comparingLong(arg -> (long) arg.numPredecessors() * (long) arg.numSuccessors())); // Construct the reachables queue with the list of successors and predecessors of keep in // toRemove. @@ -1041,12 +1035,7 @@ public final class Digraph<T> implements Cloneable { private static <T> Comparator<Node<T>> makeNodeComparator( final Comparator<? super T> comparator) { - return new Comparator<Node<T>>() { - @Override - public int compare(Node<T> o1, Node<T> o2) { - return comparator.compare(o1.getLabel(), o2.getLabel()); - } - }; + return comparing(Node::getLabel, comparator::compare); } /** diff --git a/src/main/java/com/google/devtools/build/lib/packages/Attribute.java b/src/main/java/com/google/devtools/build/lib/packages/Attribute.java index 0b1b86d867..ed8af8a6e7 100644 --- a/src/main/java/com/google/devtools/build/lib/packages/Attribute.java +++ b/src/main/java/com/google/devtools/build/lib/packages/Attribute.java @@ -974,14 +974,12 @@ public final class Attribute implements Comparable<Attribute> { public Builder<TYPE> legacyMandatoryProviders(String... ids) { return mandatoryProviders( - Iterables.transform(Arrays.asList(ids), - new Function<String, SkylarkProviderIdentifier>() { - @Override - public SkylarkProviderIdentifier apply(String s) { - Preconditions.checkNotNull(s); - return SkylarkProviderIdentifier.forLegacy(s); - } - })); + Iterables.transform( + Arrays.asList(ids), + s -> { + Preconditions.checkNotNull(s); + return SkylarkProviderIdentifier.forLegacy(s); + })); } public Builder<TYPE> mandatoryProviders(Iterable<SkylarkProviderIdentifier> providers) { @@ -1014,14 +1012,7 @@ public final class Attribute implements Comparable<Attribute> { * dependencies through this attribute. */ public Builder<TYPE> aspect(NativeAspectClass aspect) { - Function<Rule, AspectParameters> noParameters = - new Function<Rule, AspectParameters>() { - @Override - public AspectParameters apply(Rule input) { - return AspectParameters.EMPTY; - } - }; - return this.aspect(aspect, noParameters); + return this.aspect(aspect, input -> AspectParameters.EMPTY); } public Builder<TYPE> aspect( diff --git a/src/main/java/com/google/devtools/build/lib/packages/AttributeContainer.java b/src/main/java/com/google/devtools/build/lib/packages/AttributeContainer.java index 80889a9594..8622cda8cb 100644 --- a/src/main/java/com/google/devtools/build/lib/packages/AttributeContainer.java +++ b/src/main/java/com/google/devtools/build/lib/packages/AttributeContainer.java @@ -226,11 +226,7 @@ public class AttributeContainer { setAttributeLocation(index, location); } + // TODO(laurentlb): Delete field and inline it. public static final Function<RuleClass, AttributeContainer> ATTRIBUTE_CONTAINER_FACTORY = - new Function<RuleClass, AttributeContainer>() { - @Override - public AttributeContainer apply(RuleClass ruleClass) { - return new AttributeContainer(ruleClass); - } - }; + AttributeContainer::new; } diff --git a/src/main/java/com/google/devtools/build/lib/packages/BuildType.java b/src/main/java/com/google/devtools/build/lib/packages/BuildType.java index 6a32c68d57..a602515b45 100644 --- a/src/main/java/com/google/devtools/build/lib/packages/BuildType.java +++ b/src/main/java/com/google/devtools/build/lib/packages/BuildType.java @@ -290,9 +290,7 @@ public final class BuildType { Map<Label, List<Object>> convertedFrom = new LinkedHashMap<>(); for (Object original : input.keySet()) { Label label = LABEL.convert(original, what, context); - if (!convertedFrom.containsKey(label)) { - convertedFrom.put(label, new ArrayList<Object>()); - } + convertedFrom.computeIfAbsent(label, k -> new ArrayList<Object>()); convertedFrom.get(label).add(original); } StringBuilder errorMessage = new StringBuilder(); diff --git a/src/main/java/com/google/devtools/build/lib/packages/GlobCache.java b/src/main/java/com/google/devtools/build/lib/packages/GlobCache.java index aecf43f94f..e46bddf0df 100644 --- a/src/main/java/com/google/devtools/build/lib/packages/GlobCache.java +++ b/src/main/java/com/google/devtools/build/lib/packages/GlobCache.java @@ -109,18 +109,19 @@ public class GlobCache { this.maxDirectoriesToEagerlyVisit = maxDirectoriesToEagerlyVisit; Preconditions.checkNotNull(locator); - childDirectoryPredicate = new Predicate<Path>() { - @Override - public boolean apply(Path directory) { - if (directory.equals(packageDirectory)) { - return true; - } - PackageIdentifier subPackageId = PackageIdentifier.create( - packageId.getRepository(), - packageId.getPackageFragment().getRelative(directory.relativeTo(packageDirectory))); - return locator.getBuildFileForPackage(subPackageId) == null; - } - }; + childDirectoryPredicate = + directory -> { + if (directory.equals(packageDirectory)) { + return true; + } + PackageIdentifier subPackageId = + PackageIdentifier.create( + packageId.getRepository(), + packageId + .getPackageFragment() + .getRelative(directory.relativeTo(packageDirectory))); + return locator.getBuildFileForPackage(subPackageId) == null; + }; } /** diff --git a/src/main/java/com/google/devtools/build/lib/packages/ImplicitOutputsFunction.java b/src/main/java/com/google/devtools/build/lib/packages/ImplicitOutputsFunction.java index 9dea0b725a..525055476c 100644 --- a/src/main/java/com/google/devtools/build/lib/packages/ImplicitOutputsFunction.java +++ b/src/main/java/com/google/devtools/build/lib/packages/ImplicitOutputsFunction.java @@ -15,8 +15,8 @@ package com.google.devtools.build.lib.packages; import static com.google.devtools.build.lib.syntax.SkylarkType.castMap; import static java.util.Collections.singleton; +import static java.util.stream.Collectors.toCollection; -import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; @@ -319,26 +319,18 @@ public abstract class ImplicitOutputsFunction { } else if (BuildType.LABEL_LIST == attrType) { // Labels are most often used to change the extension, // e.g. %.foo -> %.java, so we return the basename w/o extension. - return Sets.newLinkedHashSet( - Iterables.transform(rule.get(attrName, BuildType.LABEL_LIST), - new Function<Label, String>() { - @Override - public String apply(Label label) { - return FileSystemUtils.removeExtension(label.getName()); - } - })); + return rule.get(attrName, BuildType.LABEL_LIST) + .stream() + .map(label -> FileSystemUtils.removeExtension(label.getName())) + .collect(toCollection(LinkedHashSet::new)); } else if (BuildType.OUTPUT == attrType) { Label out = rule.get(attrName, BuildType.OUTPUT); return singleton(out.getName()); } else if (BuildType.OUTPUT_LIST == attrType) { - return Sets.newLinkedHashSet( - Iterables.transform(rule.get(attrName, BuildType.OUTPUT_LIST), - new Function<Label, String>() { - @Override - public String apply(Label label) { - return label.getName(); - } - })); + return rule.get(attrName, BuildType.OUTPUT_LIST) + .stream() + .map(Label::getName) + .collect(toCollection(LinkedHashSet::new)); } throw new IllegalArgumentException( "Don't know how to handle " + attrName + " : " + attrType); diff --git a/src/main/java/com/google/devtools/build/lib/packages/MakeEnvironment.java b/src/main/java/com/google/devtools/build/lib/packages/MakeEnvironment.java index becb14c5c9..a208e11b38 100644 --- a/src/main/java/com/google/devtools/build/lib/packages/MakeEnvironment.java +++ b/src/main/java/com/google/devtools/build/lib/packages/MakeEnvironment.java @@ -18,12 +18,10 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable; import com.google.devtools.build.lib.concurrent.ThreadSafety.ThreadSafe; - import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; - import javax.annotation.Nullable; /** @@ -132,11 +130,7 @@ public class MakeEnvironment { if (varname == null || value == null || platformSetRegexp == null) { throw new NullPointerException(); } - LinkedList<Binding> bindings = env.get(varname); - if (bindings == null) { - bindings = new LinkedList<>(); - env.put(varname, bindings); - } + LinkedList<Binding> bindings = env.computeIfAbsent(varname, k -> new LinkedList<>()); // push new bindings onto head of list (=> most recent binding is // definitive): bindings.addFirst(new Binding(value, platformSetRegexp)); diff --git a/src/main/java/com/google/devtools/build/lib/packages/Package.java b/src/main/java/com/google/devtools/build/lib/packages/Package.java index 91cc477c21..e5a5598a38 100644 --- a/src/main/java/com/google/devtools/build/lib/packages/Package.java +++ b/src/main/java/com/google/devtools/build/lib/packages/Package.java @@ -15,7 +15,6 @@ package com.google.devtools.build.lib.packages; import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; @@ -483,14 +482,7 @@ public class Package { /** Returns all rules in the package that match the given rule class. */ public Iterable<Rule> getRulesMatchingRuleClass(final String ruleClass) { Iterable<Rule> targets = getTargets(Rule.class); - return Iterables.filter( - targets, - new Predicate<Rule>() { - @Override - public boolean apply(@Nullable Rule rule) { - return rule.getRuleClass().equals(ruleClass); - } - }); + return Iterables.filter(targets, rule -> rule.getRuleClass().equals(ruleClass)); } /** @@ -1264,9 +1256,7 @@ public class Package { PathFragment outputFileFragment = PathFragment.create(outputFile.getName()); for (int i = 1; i < outputFileFragment.segmentCount(); i++) { String prefix = outputFileFragment.subFragment(0, i).toString(); - if (!outputFilePrefixes.containsKey(prefix)) { - outputFilePrefixes.put(prefix, outputFile); - } + outputFilePrefixes.putIfAbsent(prefix, outputFile); } } targets.put(rule.getName(), rule); @@ -1460,9 +1450,7 @@ public class Package { throw conflictingOutputFile(outputFile, (OutputFile) targets.get(prefix)); } - if (!outputFilePrefixes.containsKey(prefix)) { - outputFilePrefixes.put(prefix, outputFile); - } + outputFilePrefixes.putIfAbsent(prefix, outputFile); } } diff --git a/src/main/java/com/google/devtools/build/lib/packages/RequiredProviders.java b/src/main/java/com/google/devtools/build/lib/packages/RequiredProviders.java index 24719c6bf2..586b105bd9 100644 --- a/src/main/java/com/google/devtools/build/lib/packages/RequiredProviders.java +++ b/src/main/java/com/google/devtools/build/lib/packages/RequiredProviders.java @@ -115,15 +115,9 @@ public final class RequiredProviders { return true; } return satisfies( - new Predicate<Class<?>>() { - @Override - public boolean apply(Class<?> aClass) { - return advertisedProviderSet.getNativeProviders().contains(aClass); - } - }, + aClass -> advertisedProviderSet.getNativeProviders().contains(aClass), Predicates.in(advertisedProviderSet.getSkylarkProviders()), - requiredProviders - ); + requiredProviders); } /** diff --git a/src/main/java/com/google/devtools/build/lib/packages/SkylarkAspect.java b/src/main/java/com/google/devtools/build/lib/packages/SkylarkAspect.java index 895afba506..26fcd30fc5 100644 --- a/src/main/java/com/google/devtools/build/lib/packages/SkylarkAspect.java +++ b/src/main/java/com/google/devtools/build/lib/packages/SkylarkAspect.java @@ -27,7 +27,6 @@ import com.google.devtools.build.lib.syntax.Type; import com.google.devtools.build.lib.util.Preconditions; import java.util.Arrays; import java.util.List; -import javax.annotation.Nullable; /** A Skylark value that is a result of an 'aspect(..)' function call. */ @SkylarkModule( @@ -167,37 +166,33 @@ public class SkylarkAspect implements SkylarkExportable { } public Function<Rule, AspectParameters> getDefaultParametersExtractor() { - return new Function<Rule, AspectParameters>() { - @Nullable - @Override - public AspectParameters apply(Rule rule) { - AttributeMap ruleAttrs = RawAttributeMapper.of(rule); - AspectParameters.Builder builder = new AspectParameters.Builder(); - for (Attribute aspectAttr : attributes) { - if (!Attribute.isImplicit(aspectAttr.getName())) { - String param = aspectAttr.getName(); - Attribute ruleAttr = ruleAttrs.getAttributeDefinition(param); - if (paramAttributes.contains(aspectAttr.getName())) { - // These are preconditions because if they are false, RuleFunction.call() should - // already have generated an error. - Preconditions.checkArgument(ruleAttr != null, - String.format("Cannot apply aspect %s to %s that does not define attribute '%s'.", - getName(), - rule.getTargetKind(), - param)); - Preconditions.checkArgument(ruleAttr.getType() == Type.STRING, - String.format("Cannot apply aspect %s to %s with non-string attribute '%s'.", - getName(), - rule.getTargetKind(), - param)); - } - if (ruleAttr != null && ruleAttr.getType() == aspectAttr.getType()) { - builder.addAttribute(param, (String) ruleAttrs.get(param, ruleAttr.getType())); - } + return rule -> { + AttributeMap ruleAttrs = RawAttributeMapper.of(rule); + AspectParameters.Builder builder = new AspectParameters.Builder(); + for (Attribute aspectAttr : attributes) { + if (!Attribute.isImplicit(aspectAttr.getName())) { + String param = aspectAttr.getName(); + Attribute ruleAttr = ruleAttrs.getAttributeDefinition(param); + if (paramAttributes.contains(aspectAttr.getName())) { + // These are preconditions because if they are false, RuleFunction.call() should + // already have generated an error. + Preconditions.checkArgument( + ruleAttr != null, + String.format( + "Cannot apply aspect %s to %s that does not define attribute '%s'.", + getName(), rule.getTargetKind(), param)); + Preconditions.checkArgument( + ruleAttr.getType() == Type.STRING, + String.format( + "Cannot apply aspect %s to %s with non-string attribute '%s'.", + getName(), rule.getTargetKind(), param)); + } + if (ruleAttr != null && ruleAttr.getType() == aspectAttr.getType()) { + builder.addAttribute(param, (String) ruleAttrs.get(param, ruleAttr.getType())); } } - return builder.build(); } + return builder.build(); }; } diff --git a/src/main/java/com/google/devtools/build/lib/packages/TargetUtils.java b/src/main/java/com/google/devtools/build/lib/packages/TargetUtils.java index 4f3598ea20..a2babbc9ef 100644 --- a/src/main/java/com/google/devtools/build/lib/packages/TargetUtils.java +++ b/src/main/java/com/google/devtools/build/lib/packages/TargetUtils.java @@ -209,22 +209,19 @@ public final class TargetUtils { TestTargetUtils.sortTagsBySense(tagFilterList); final Collection<String> requiredTags = tagLists.first; final Collection<String> excludedTags = tagLists.second; - return new Predicate<Target>() { - @Override - public boolean apply(Target input) { - if (requiredTags.isEmpty() && excludedTags.isEmpty()) { - return true; - } + return input -> { + if (requiredTags.isEmpty() && excludedTags.isEmpty()) { + return true; + } - if (!(input instanceof Rule)) { - return false; - } - // Note that test_tags are those originating from the XX_test rule, - // whereas the requiredTags and excludedTags originate from the command - // line or test_suite rule. - return TestTargetUtils.testMatchesFilters(((Rule) input).getRuleTags(), - requiredTags, excludedTags, false); + if (!(input instanceof Rule)) { + return false; } + // Note that test_tags are those originating from the XX_test rule, + // whereas the requiredTags and excludedTags originate from the command + // line or test_suite rule. + return TestTargetUtils.testMatchesFilters( + ((Rule) input).getRuleTags(), requiredTags, excludedTags, false); }; } diff --git a/src/main/java/com/google/devtools/build/lib/packages/TestTargetUtils.java b/src/main/java/com/google/devtools/build/lib/packages/TestTargetUtils.java index 1ab25112fb..b51285001d 100644 --- a/src/main/java/com/google/devtools/build/lib/packages/TestTargetUtils.java +++ b/src/main/java/com/google/devtools/build/lib/packages/TestTargetUtils.java @@ -43,14 +43,11 @@ public final class TestTargetUtils { * given size. */ public static Predicate<Target> testSizeFilter(final Set<TestSize> allowedSizes) { - return new Predicate<Target>() { - @Override - public boolean apply(Target target) { - if (!(target instanceof Rule)) { - return false; - } - return allowedSizes.contains(TestSize.getTestSize((Rule) target)); + return target -> { + if (!(target instanceof Rule)) { + return false; } + return allowedSizes.contains(TestSize.getTestSize((Rule) target)); }; } @@ -59,14 +56,11 @@ public final class TestTargetUtils { * the given timeout. **/ public static Predicate<Target> testTimeoutFilter(final Set<TestTimeout> allowedTimeouts) { - return new Predicate<Target>() { - @Override - public boolean apply(Target target) { - if (!(target instanceof Rule)) { - return false; - } - return allowedTimeouts.contains(TestTimeout.getTestTimeout((Rule) target)); + return target -> { + if (!(target instanceof Rule)) { + return false; } + return allowedTimeouts.contains(TestTimeout.getTestTimeout((Rule) target)); }; } @@ -93,13 +87,10 @@ public final class TestTargetUtils { } } - return new Predicate<Target>() { - @Override - public boolean apply(Target rule) { - String ruleLang = TargetUtils.getRuleLanguage(rule); - return (requiredLangs.isEmpty() || requiredLangs.contains(ruleLang)) - && !excludedLangs.contains(ruleLang); - } + return rule -> { + String ruleLang = TargetUtils.getRuleLanguage(rule); + return (requiredLangs.isEmpty() || requiredLangs.contains(ruleLang)) + && !excludedLangs.contains(ruleLang); }; } diff --git a/src/main/java/com/google/devtools/build/lib/pkgcache/CompileOneDependencyTransformer.java b/src/main/java/com/google/devtools/build/lib/pkgcache/CompileOneDependencyTransformer.java index b23b62c8e0..47cbaadb62 100644 --- a/src/main/java/com/google/devtools/build/lib/pkgcache/CompileOneDependencyTransformer.java +++ b/src/main/java/com/google/devtools/build/lib/pkgcache/CompileOneDependencyTransformer.java @@ -13,6 +13,8 @@ // limitations under the License. package com.google.devtools.build.lib.pkgcache; +import static java.util.Comparator.comparingInt; + import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.devtools.build.lib.cmdline.Label; @@ -30,7 +32,6 @@ import com.google.devtools.build.lib.packages.RuleClass; import com.google.devtools.build.lib.packages.Target; import java.util.Collection; import java.util.Collections; -import java.util.Comparator; import java.util.List; import java.util.Set; import java.util.TreeSet; @@ -73,14 +74,7 @@ public final class CompileOneDependencyTransformer { orderedList.add(rule); } - Collections.sort(orderedList, new Comparator<Rule>() { - @Override - public int compare(Rule o1, Rule o2) { - return Integer.compare( - o1.getLocation().getStartOffset(), - o2.getLocation().getStartOffset()); - } - }); + Collections.sort(orderedList, comparingInt(arg -> arg.getLocation().getStartOffset())); return orderedList; } diff --git a/src/main/java/com/google/devtools/build/lib/pkgcache/LoadingPhaseCompleteEvent.java b/src/main/java/com/google/devtools/build/lib/pkgcache/LoadingPhaseCompleteEvent.java index 315d2437f5..4cfc4fa473 100644 --- a/src/main/java/com/google/devtools/build/lib/pkgcache/LoadingPhaseCompleteEvent.java +++ b/src/main/java/com/google/devtools/build/lib/pkgcache/LoadingPhaseCompleteEvent.java @@ -13,7 +13,6 @@ // limitations under the License. package com.google.devtools.build.lib.pkgcache; -import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; @@ -65,7 +64,7 @@ public final class LoadingPhaseCompleteEvent implements ExtendedEventHandler.Pos * targets we attempted to load. */ public Iterable<Label> getLabels() { - return Iterables.transform(targets, TO_LABEL); + return Iterables.transform(targets, Target::getLabel); } public long getTimeInMs() { @@ -78,11 +77,4 @@ public final class LoadingPhaseCompleteEvent implements ExtendedEventHandler.Pos public PackageManager.PackageManagerStatistics getPkgManagerStats() { return pkgManagerStats; } - - private static final Function<Target, Label> TO_LABEL = new Function<Target, Label>() { - @Override - public Label apply(Target input) { - return input.getLabel(); - } - }; } diff --git a/src/main/java/com/google/devtools/build/lib/pkgcache/TargetParsingCompleteEvent.java b/src/main/java/com/google/devtools/build/lib/pkgcache/TargetParsingCompleteEvent.java index 704a316358..2a0763b8fc 100644 --- a/src/main/java/com/google/devtools/build/lib/pkgcache/TargetParsingCompleteEvent.java +++ b/src/main/java/com/google/devtools/build/lib/pkgcache/TargetParsingCompleteEvent.java @@ -14,7 +14,6 @@ package com.google.devtools.build.lib.pkgcache; import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; @@ -78,12 +77,7 @@ public class TargetParsingCompleteEvent implements BuildEvent { } public Iterable<Label> getLabels() { - return Iterables.transform(targets, new Function<Target, Label>() { - @Override - public Label apply(Target input) { - return input.getLabel(); - } - }); + return Iterables.transform(targets, Target::getLabel); } /** diff --git a/src/main/java/com/google/devtools/build/lib/profiler/MetricData.java b/src/main/java/com/google/devtools/build/lib/profiler/MetricData.java index db46b0d866..419318c054 100644 --- a/src/main/java/com/google/devtools/build/lib/profiler/MetricData.java +++ b/src/main/java/com/google/devtools/build/lib/profiler/MetricData.java @@ -13,12 +13,10 @@ // limitations under the License. package com.google.devtools.build.lib.profiler; -import com.google.common.base.Joiner; -import com.google.common.base.Predicate; -import com.google.common.collect.Collections2; +import static java.util.stream.Collectors.joining; + import com.google.common.collect.ImmutableList; import com.google.common.collect.Range; - import java.text.DecimalFormat; /** @@ -33,14 +31,6 @@ public final class MetricData { private final double avg; private final double stdDev; private final int max; - private static final Predicate<HistogramElement> NON_EMPTY_HISTOGRAM_ELEMENT = - new Predicate<HistogramElement>() { - @Override - public boolean apply(HistogramElement element) { - return element.count > 0; - } - }; - public MetricData(Object description, ImmutableList<HistogramElement> histogram, int count, double avg, double stdDev, int max) { this.description = description; @@ -81,13 +71,23 @@ public final class MetricData { return "'" + description + "'. Zero data recorded"; } DecimalFormat fmt = new DecimalFormat("0.###"); - return "'" + description + "'. " - + " Count: " + count - + " Avg: " + fmt.format(avg) - + " StdDev: " + fmt.format(stdDev) - + " Max: " + max + return "'" + + description + + "'. " + + " Count: " + + count + + " Avg: " + + fmt.format(avg) + + " StdDev: " + + fmt.format(stdDev) + + " Max: " + + max + " Histogram:\n " - + Joiner.on("\n ").join(Collections2.filter(histogram, NON_EMPTY_HISTOGRAM_ELEMENT)); + + histogram + .stream() + .filter(element -> element.count > 0) + .map(Object::toString) + .collect(joining("\n ")); } /** An histogram element that contains the range that applies to and the number of elements. */ diff --git a/src/main/java/com/google/devtools/build/lib/profiler/ProfileInfo.java b/src/main/java/com/google/devtools/build/lib/profiler/ProfileInfo.java index 4c1309a040..242bdb2c7f 100644 --- a/src/main/java/com/google/devtools/build/lib/profiler/ProfileInfo.java +++ b/src/main/java/com/google/devtools/build/lib/profiler/ProfileInfo.java @@ -13,11 +13,11 @@ // limitations under the License. package com.google.devtools.build.lib.profiler; +import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.devtools.build.lib.profiler.ProfilerTask.CRITICAL_PATH; import static com.google.devtools.build.lib.profiler.ProfilerTask.TASK_COUNT; import com.google.common.base.Joiner; -import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.ListMultimap; @@ -29,7 +29,6 @@ import com.google.common.collect.Sets; import com.google.devtools.build.lib.util.Preconditions; import com.google.devtools.build.lib.util.VarInt; import com.google.devtools.build.lib.vfs.Path; - import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.IOException; @@ -49,6 +48,7 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; +import java.util.stream.Stream; import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; @@ -320,17 +320,10 @@ public class ProfileInfo { out.print(" ["); ImmutableList<Task> sortedSubTasks = - TASK_DURATION_ORDERING - .reverse() - .immutableSortedCopy( - Iterables.filter( - Arrays.asList(subtasks), - new Predicate<Task>() { - @Override - public boolean apply(Task task) { - return task.durationNanos >= durationThresholdNanos; - } - })); + Stream.of(subtasks) + .filter(task -> task.durationNanos >= durationThresholdNanos) + .sorted(TASK_DURATION_ORDERING.reverse()) + .collect(toImmutableList()); String sep = ""; for (Task task : sortedSubTasks) { out.print(sep); @@ -953,13 +946,7 @@ public class ProfileInfo { */ public Iterable<Task> findTasksByDescription(final Pattern description) { return Iterables.filter( - allTasksById, - new Predicate<Task>() { - @Override - public boolean apply(Task task) { - return description.matcher(task.getDescription()).find(); - } - }); + allTasksById, task -> description.matcher(task.getDescription()).find()); } /** diff --git a/src/main/java/com/google/devtools/build/lib/profiler/chart/Chart.java b/src/main/java/com/google/devtools/build/lib/profiler/chart/Chart.java index 79ec2fcba8..9fddfd92c3 100644 --- a/src/main/java/com/google/devtools/build/lib/profiler/chart/Chart.java +++ b/src/main/java/com/google/devtools/build/lib/profiler/chart/Chart.java @@ -143,11 +143,7 @@ public class Chart { * otherwise */ private ChartRow addSlotIfAbsent(long id) { - ChartRow slot = rows.get(id); - if (slot == null) { - slot = new ChartRow(Long.toString(id), rowIndex++); - rows.put(id, slot); - } + ChartRow slot = rows.computeIfAbsent(id, k -> new ChartRow(Long.toString(k), rowIndex++)); return slot; } diff --git a/src/main/java/com/google/devtools/build/lib/profiler/statistics/CriticalPathStatistics.java b/src/main/java/com/google/devtools/build/lib/profiler/statistics/CriticalPathStatistics.java index 8631016543..ec18dc5092 100644 --- a/src/main/java/com/google/devtools/build/lib/profiler/statistics/CriticalPathStatistics.java +++ b/src/main/java/com/google/devtools/build/lib/profiler/statistics/CriticalPathStatistics.java @@ -13,21 +13,18 @@ // limitations under the License. package com.google.devtools.build.lib.profiler.statistics; -import com.google.common.base.Predicate; import com.google.devtools.build.lib.actions.MiddlemanAction; import com.google.devtools.build.lib.profiler.ProfileInfo; import com.google.devtools.build.lib.profiler.ProfileInfo.CriticalPathEntry; import com.google.devtools.build.lib.profiler.ProfileInfo.Task; import com.google.devtools.build.lib.profiler.ProfilerTask; import com.google.devtools.build.lib.util.Pair; - import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.EnumSet; import java.util.Iterator; import java.util.List; - import javax.annotation.Nullable; /** @@ -50,12 +47,7 @@ public final class CriticalPathStatistics implements Iterable<Pair<String, Doubl Pair.of( "the VFS calls", ProfilerTask.allSatisfying( - new Predicate<ProfilerTask>() { - @Override - public boolean apply(ProfilerTask task) { - return DEFAULT_FILTER.contains(task) || task.name().startsWith("VFS_"); - } - })), + task -> DEFAULT_FILTER.contains(task) || task.name().startsWith("VFS_"))), typeFilter("the dependency checking", ProfilerTask.ACTION_CHECK), typeFilter("the execution setup", ProfilerTask.ACTION_EXECUTE), typeFilter("local execution", ProfilerTask.SPAWN, ProfilerTask.LOCAL_EXECUTION), diff --git a/src/main/java/com/google/devtools/build/lib/profiler/statistics/PhaseStatistics.java b/src/main/java/com/google/devtools/build/lib/profiler/statistics/PhaseStatistics.java index b8e303b3f1..290eb72fa0 100644 --- a/src/main/java/com/google/devtools/build/lib/profiler/statistics/PhaseStatistics.java +++ b/src/main/java/com/google/devtools/build/lib/profiler/statistics/PhaseStatistics.java @@ -13,7 +13,6 @@ // limitations under the License. package com.google.devtools.build.lib.profiler.statistics; -import com.google.common.base.Predicate; import com.google.common.collect.Iterators; import com.google.devtools.build.lib.profiler.ProfileInfo; import com.google.devtools.build.lib.profiler.ProfileInfo.AggregateAttr; @@ -21,11 +20,9 @@ import com.google.devtools.build.lib.profiler.ProfileInfo.Task; import com.google.devtools.build.lib.profiler.ProfilePhase; import com.google.devtools.build.lib.profiler.ProfilerTask; import com.google.devtools.build.lib.util.Preconditions; - import java.util.EnumMap; import java.util.Iterator; import java.util.List; - import javax.annotation.Nullable; /** @@ -207,12 +204,7 @@ public final class PhaseStatistics implements Iterable<ProfilerTask> { public Iterator<ProfilerTask> iterator() { return Iterators.filter( taskCounts.keySet().iterator(), - new Predicate<ProfilerTask>() { - @Override - public boolean apply(ProfilerTask taskType) { - return getTotalDurationNanos(taskType) > 0 && wasExecuted(taskType); - } - }); + taskType -> getTotalDurationNanos(taskType) > 0 && wasExecuted(taskType)); } /** diff --git a/src/main/java/com/google/devtools/build/lib/profiler/statistics/PhaseVfsStatistics.java b/src/main/java/com/google/devtools/build/lib/profiler/statistics/PhaseVfsStatistics.java index 58d454f368..cdc794c033 100644 --- a/src/main/java/com/google/devtools/build/lib/profiler/statistics/PhaseVfsStatistics.java +++ b/src/main/java/com/google/devtools/build/lib/profiler/statistics/PhaseVfsStatistics.java @@ -13,7 +13,6 @@ // limitations under the License. package com.google.devtools.build.lib.profiler.statistics; -import com.google.common.base.Supplier; import com.google.common.collect.ComparisonChain; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Table; @@ -23,7 +22,6 @@ import com.google.devtools.build.lib.profiler.ProfileInfo; import com.google.devtools.build.lib.profiler.ProfileInfo.Task; import com.google.devtools.build.lib.profiler.ProfilePhase; import com.google.devtools.build.lib.profiler.ProfilerTask; - import java.util.Arrays; import java.util.EnumMap; import java.util.HashMap; @@ -108,13 +106,7 @@ public final class PhaseVfsStatistics implements Iterable<ProfilerTask> { this.phase = phase; this.statistics = Tables.newCustomTable( - new EnumMap<ProfilerTask, Map<String, Stat>>(ProfilerTask.class), - new Supplier<Map<String, Stat>>() { - @Override - public Map<String, Stat> get() { - return new HashMap<>(); - } - }); + new EnumMap<ProfilerTask, Map<String, Stat>>(ProfilerTask.class), HashMap::new); } public PhaseVfsStatistics(final String workSpaceName, ProfilePhase phase, ProfileInfo info) { diff --git a/src/main/java/com/google/devtools/build/lib/profiler/statistics/SkylarkStatistics.java b/src/main/java/com/google/devtools/build/lib/profiler/statistics/SkylarkStatistics.java index 50a4e32a5b..325446668c 100644 --- a/src/main/java/com/google/devtools/build/lib/profiler/statistics/SkylarkStatistics.java +++ b/src/main/java/com/google/devtools/build/lib/profiler/statistics/SkylarkStatistics.java @@ -14,12 +14,10 @@ package com.google.devtools.build.lib.profiler.statistics; import com.google.common.collect.Maps; -import com.google.common.collect.Maps.EntryTransformer; import com.google.common.collect.Multimap; import com.google.devtools.build.lib.profiler.ProfileInfo; import com.google.devtools.build.lib.profiler.ProfileInfo.Task; import com.google.devtools.build.lib.util.LongArrayList; - import java.util.Collection; import java.util.HashMap; import java.util.Map; @@ -251,13 +249,6 @@ public final class SkylarkStatistics { */ private static Map<String, TasksStatistics> buildTasksStatistics( final Map<String, LongArrayList> durationsMap) { - return Maps.transformEntries( - durationsMap, - new EntryTransformer<String, LongArrayList, TasksStatistics>() { - @Override - public TasksStatistics transformEntry(String function, LongArrayList durations) { - return TasksStatistics.create(function, durations); - } - }); + return Maps.transformEntries(durationsMap, TasksStatistics::create); } } diff --git a/src/main/java/com/google/devtools/build/lib/query2/BlazeQueryEnvironment.java b/src/main/java/com/google/devtools/build/lib/query2/BlazeQueryEnvironment.java index 7fa00512d9..601ae5c0e6 100644 --- a/src/main/java/com/google/devtools/build/lib/query2/BlazeQueryEnvironment.java +++ b/src/main/java/com/google/devtools/build/lib/query2/BlazeQueryEnvironment.java @@ -13,11 +13,10 @@ // limitations under the License. package com.google.devtools.build.lib.query2; -import com.google.common.base.Function; +import static com.google.common.collect.ImmutableSet.toImmutableSet; + import com.google.common.base.Predicate; -import com.google.common.collect.Collections2; import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import com.google.devtools.build.lib.cmdline.Label; import com.google.devtools.build.lib.cmdline.LabelSyntaxException; @@ -68,13 +67,6 @@ import java.util.Set; * The environment of a Blaze query. Not thread-safe. */ public class BlazeQueryEnvironment extends AbstractBlazeQueryEnvironment<Target> { - private static final Function<Target, Label> TO_LABEL = new Function<Target, Label>() { - @Override - public Label apply(Target input) { - return input.getLabel(); - } - }; - private static final int MAX_DEPTH_FULL_SCAN_LIMIT = 20; private final Map<String, Set<Target>> resolvedTargetPatterns = new HashMap<>(); private final TargetPatternEvaluator targetPatternEvaluator; @@ -323,7 +315,7 @@ public class BlazeQueryEnvironment extends AbstractBlazeQueryEnvironment<Target> if (maxDepth >= MAX_DEPTH_FULL_SCAN_LIMIT && transitivePackageLoader != null) { // Only do the full visitation if "maxDepth" is large enough. Otherwise, the benefits of // preloading will be outweighed by the cost of doing more work than necessary. - Set<Label> labels = ImmutableSet.copyOf(Collections2.transform(targets, TO_LABEL)); + Set<Label> labels = targets.stream().map(Target::getLabel).collect(toImmutableSet()); transitivePackageLoader.sync(eventHandler, labels, keepGoing, loadingPhaseThreads); } } @@ -421,15 +413,6 @@ public class BlazeQueryEnvironment extends AbstractBlazeQueryEnvironment<Target> } return dependentFiles; } - - private static final Function<ResolvedTargets<Target>, Set<Target>> RESOLVED_TARGETS_TO_TARGETS = - new Function<ResolvedTargets<Target>, Set<Target>>() { - @Override - public Set<Target> apply(ResolvedTargets<Target> resolvedTargets) { - return resolvedTargets.getTargets(); - } - }; - @Override protected void preloadOrThrow(QueryExpression caller, Collection<String> patterns) throws TargetParsingException, InterruptedException { @@ -439,7 +422,7 @@ public class BlazeQueryEnvironment extends AbstractBlazeQueryEnvironment<Target> resolvedTargetPatterns.putAll( Maps.transformValues( targetPatternEvaluator.preloadTargetPatterns(eventHandler, patterns, keepGoing), - RESOLVED_TARGETS_TO_TARGETS)); + ResolvedTargets::getTargets)); } } diff --git a/src/main/java/com/google/devtools/build/lib/query2/LabelVisitor.java b/src/main/java/com/google/devtools/build/lib/query2/LabelVisitor.java index d3b2c140f4..86bf39f9fa 100644 --- a/src/main/java/com/google/devtools/build/lib/query2/LabelVisitor.java +++ b/src/main/java/com/google/devtools/build/lib/query2/LabelVisitor.java @@ -317,18 +317,15 @@ final class LabelVisitor { private Runnable newVisitRunnable(final Target from, final Attribute attr, final Label label, final int depth, final int count) { - return new Runnable() { - @Override - public void run() { + return () -> { + try { try { - try { - visit(from, attr, targetProvider.getTarget(eventHandler, label), depth + 1, count); - } catch (NoSuchThingException e) { - observeError(from, label, e); - } - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); + visit(from, attr, targetProvider.getTarget(eventHandler, label), depth + 1, count); + } catch (NoSuchThingException e) { + observeError(from, label, e); } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); } }; } diff --git a/src/main/java/com/google/devtools/build/lib/query2/ParallelSkyQueryUtils.java b/src/main/java/com/google/devtools/build/lib/query2/ParallelSkyQueryUtils.java index 28cdede50e..87f8e7de51 100644 --- a/src/main/java/com/google/devtools/build/lib/query2/ParallelSkyQueryUtils.java +++ b/src/main/java/com/google/devtools/build/lib/query2/ParallelSkyQueryUtils.java @@ -13,17 +13,17 @@ // limitations under the License. package com.google.devtools.build.lib.query2; +import static com.google.common.collect.ImmutableSet.toImmutableSet; + import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.Collections2; import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.ListMultimap; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; +import com.google.common.collect.Streams; import com.google.devtools.build.lib.cmdline.Label; import com.google.devtools.build.lib.cmdline.PackageIdentifier; import com.google.devtools.build.lib.collect.CompactHashSet; @@ -134,10 +134,9 @@ class ParallelSkyQueryUtils { Iterable<SkyKey> keysToUseForResult, Callback<Target> callback) throws QueryException, InterruptedException { Set<PackageIdentifier> pkgIdsNeededForResult = - ImmutableSet.copyOf( - Iterables.transform( - keysToUseForResult, - SkyQueryEnvironment.PACKAGE_SKYKEY_TO_PACKAGE_IDENTIFIER)); + Streams.stream(keysToUseForResult) + .map(SkyQueryEnvironment.PACKAGE_SKYKEY_TO_PACKAGE_IDENTIFIER) + .collect(toImmutableSet()); packageSemaphore.acquireAll(pkgIdsNeededForResult); try { callback.process(SkyQueryEnvironment.getBuildFilesForPackageValues( @@ -222,9 +221,7 @@ class ParallelSkyQueryUtils { continue; } - if (!reverseDepsMap.containsKey(reverseDepPair.first)) { - reverseDepsMap.put(reverseDepPair.first, new LinkedList<SkyKey>()); - } + reverseDepsMap.computeIfAbsent(reverseDepPair.first, k -> new LinkedList<SkyKey>()); reverseDepsMap.get(reverseDepPair.first).add(reverseDepPair.second); } @@ -232,10 +229,11 @@ class ParallelSkyQueryUtils { Multimap<SkyKey, SkyKey> packageKeyToTargetKeyMap = env.makePackageKeyToTargetKeyMap(Iterables.concat(reverseDepsMap.values())); Set<PackageIdentifier> pkgIdsNeededForTargetification = - ImmutableSet.copyOf( - Iterables.transform( - packageKeyToTargetKeyMap.keySet(), - SkyQueryEnvironment.PACKAGE_SKYKEY_TO_PACKAGE_IDENTIFIER)); + packageKeyToTargetKeyMap + .keySet() + .stream() + .map(SkyQueryEnvironment.PACKAGE_SKYKEY_TO_PACKAGE_IDENTIFIER) + .collect(toImmutableSet()); packageSemaphore.acquireAll(pkgIdsNeededForTargetification); try { @@ -245,8 +243,10 @@ class ParallelSkyQueryUtils { Collection<Target> filteredTargets = env.filterRawReverseDepsOfTransitiveTraversalKeys( reverseDepsMap, packageKeyToTargetKeyMap); - filteredKeys.addAll( - Collections2.transform(filteredTargets, SkyQueryEnvironment.TARGET_TO_SKY_KEY)); + filteredTargets + .stream() + .map(SkyQueryEnvironment.TARGET_TO_SKY_KEY) + .forEachOrdered(filteredKeys::add); } } finally { packageSemaphore.releaseAll(pkgIdsNeededForTargetification); @@ -276,10 +276,11 @@ class ParallelSkyQueryUtils { Multimap<SkyKey, SkyKey> packageKeyToTargetKeyMap = env.makePackageKeyToTargetKeyMap(keysToUseForResult); Set<PackageIdentifier> pkgIdsNeededForResult = - ImmutableSet.copyOf( - Iterables.transform( - packageKeyToTargetKeyMap.keySet(), - SkyQueryEnvironment.PACKAGE_SKYKEY_TO_PACKAGE_IDENTIFIER)); + packageKeyToTargetKeyMap + .keySet() + .stream() + .map(SkyQueryEnvironment.PACKAGE_SKYKEY_TO_PACKAGE_IDENTIFIER) + .collect(toImmutableSet()); packageSemaphore.acquireAll(pkgIdsNeededForResult); try { callback.process( @@ -291,16 +292,7 @@ class ParallelSkyQueryUtils { @Override protected Iterable<Pair<SkyKey, SkyKey>> preprocessInitialVisit(Iterable<SkyKey> keys) { - return Iterables.transform( - keys, - new Function<SkyKey, Pair<SkyKey, SkyKey>>() { - @Override - public Pair<SkyKey, SkyKey> apply(SkyKey key) { - // Set parent of first-level nodes to null. They are handled specially in - // AllRdepsUnboundedVisitor#getVisitResult and will not be filtered later. - return Pair.of(null, key); - } - }); + return Iterables.transform(keys, key -> Pair.of(null, key)); } @Override diff --git a/src/main/java/com/google/devtools/build/lib/query2/ParallelVisitor.java b/src/main/java/com/google/devtools/build/lib/query2/ParallelVisitor.java index e98a6afb7e..820bdfc6d2 100644 --- a/src/main/java/com/google/devtools/build/lib/query2/ParallelVisitor.java +++ b/src/main/java/com/google/devtools/build/lib/query2/ParallelVisitor.java @@ -15,6 +15,7 @@ package com.google.devtools.build.lib.query2; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; +import com.google.common.collect.Streams; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.google.devtools.build.lib.concurrent.AbstractQueueVisitor; import com.google.devtools.build.lib.concurrent.BlockingStack; @@ -140,7 +141,7 @@ public abstract class ParallelVisitor<T> { void visitAndWaitForCompletion(Iterable<SkyKey> keys) throws QueryException, InterruptedException { - processingQueue.addAll(ImmutableList.copyOf(preprocessInitialVisit(keys))); + Streams.stream(preprocessInitialVisit(keys)).forEachOrdered(processingQueue::add); executor.visitAndWaitForCompletion(); } @@ -205,7 +206,7 @@ public abstract class ParallelVisitor<T> { executor.execute(new GetAndProcessResultsTask(keysToUseForResultBatch)); } - processingQueue.addAll(ImmutableList.copyOf(visit.keysToVisit)); + Streams.stream(visit.keysToVisit).forEachOrdered(processingQueue::add); } } diff --git a/src/main/java/com/google/devtools/build/lib/query2/RBuildFilesFunction.java b/src/main/java/com/google/devtools/build/lib/query2/RBuildFilesFunction.java index 23a9560b15..dc3a338357 100644 --- a/src/main/java/com/google/devtools/build/lib/query2/RBuildFilesFunction.java +++ b/src/main/java/com/google/devtools/build/lib/query2/RBuildFilesFunction.java @@ -13,8 +13,6 @@ // limitations under the License. package com.google.devtools.build.lib.query2; -import com.google.common.base.Function; -import com.google.common.collect.Collections2; import com.google.common.collect.Iterables; import com.google.devtools.build.lib.packages.Target; import com.google.devtools.build.lib.query2.engine.Callback; @@ -28,6 +26,7 @@ import com.google.devtools.build.lib.query2.engine.QueryExpression; import com.google.devtools.build.lib.query2.engine.VariableContext; import com.google.devtools.build.lib.vfs.PathFragment; import java.util.List; +import java.util.stream.Collectors; /** * An "rbuildfiles" query expression, which computes the set of packages (as represented by their @@ -57,14 +56,6 @@ public class RBuildFilesFunction implements QueryFunction { return Iterables.cycle(ArgumentType.WORD); } - private static final Function<Argument, PathFragment> ARGUMENT_TO_PATH_FRAGMENT = - new Function<Argument, PathFragment>() { - @Override - public PathFragment apply(Argument argument) { - return PathFragment.create(argument.getWord()); - } - }; - @Override @SuppressWarnings("unchecked") // Cast from <Target> to <T>. This will only be used with <Target>. public <T> QueryTaskFuture<Void> eval( @@ -79,7 +70,9 @@ public class RBuildFilesFunction implements QueryFunction { } SkyQueryEnvironment skyEnv = ((SkyQueryEnvironment) env); return skyEnv.getRBuildFilesParallel( - Collections2.transform(args, ARGUMENT_TO_PATH_FRAGMENT), + args.stream() + .map(argument -> PathFragment.create(argument.getWord())) + .collect(Collectors.toList()), (Callback<Target>) callback); } } diff --git a/src/main/java/com/google/devtools/build/lib/query2/SkyQueryEnvironment.java b/src/main/java/com/google/devtools/build/lib/query2/SkyQueryEnvironment.java index 6bf3ceab52..db78d71e03 100644 --- a/src/main/java/com/google/devtools/build/lib/query2/SkyQueryEnvironment.java +++ b/src/main/java/com/google/devtools/build/lib/query2/SkyQueryEnvironment.java @@ -126,7 +126,6 @@ import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; -import javax.annotation.Nullable; /** * {@link AbstractBlazeQueryEnvironment} that introspects the Skyframe graph to find forward and @@ -610,12 +609,8 @@ public class SkyQueryEnvironment extends AbstractBlazeQueryEnvironment<Target> final Callback<Target> callback) { // TODO(bazel-team): As in here, use concurrency for the async #eval of other QueryEnvironment // implementations. - Callable<QueryTaskFutureImpl<Void>> task = new Callable<QueryTaskFutureImpl<Void>>() { - @Override - public QueryTaskFutureImpl<Void> call() { - return (QueryTaskFutureImpl<Void>) expr.eval(SkyQueryEnvironment.this, context, callback); - } - }; + Callable<QueryTaskFutureImpl<Void>> task = + () -> (QueryTaskFutureImpl<Void>) expr.eval(SkyQueryEnvironment.this, context, callback); ListenableFuture<QueryTaskFutureImpl<Void>> futureFuture = safeSubmit(task); return QueryTaskFutureImpl.ofDelegate(Futures.dereference(futureFuture)); } @@ -632,12 +627,7 @@ public class SkyQueryEnvironment extends AbstractBlazeQueryEnvironment<Target> return QueryTaskFutureImpl.ofDelegate( Futures.transformAsync( (QueryTaskFutureImpl<T1>) future, - new AsyncFunction<T1, T2>() { - @Override - public ListenableFuture<T2> apply(T1 input) { - return (QueryTaskFutureImpl<T2>) function.apply(input); - } - }, + input -> (QueryTaskFutureImpl<T2>) function.apply(input), executor)); } @@ -721,13 +711,10 @@ public class SkyQueryEnvironment extends AbstractBlazeQueryEnvironment<Target> ImmutableSet<PathFragment> subdirectoriesToExclude = patternToEvalAndSubdirectoriesToExclude.getSecond(); AsyncFunction<TargetParsingException, Void> reportBuildFileErrorAsyncFunction = - new AsyncFunction<TargetParsingException, Void>() { - @Override - public ListenableFuture<Void> apply(TargetParsingException exn) throws QueryException { - reportBuildFileError(owner, exn.getMessage()); - return Futures.immediateFuture(null); - } - }; + exn -> { + reportBuildFileError(owner, exn.getMessage()); + return Futures.immediateFuture(null); + }; ListenableFuture<Void> evalFuture = patternToEval.evalAsync( resolver, subdirectoriesToExclude, @@ -910,26 +897,17 @@ public class SkyQueryEnvironment extends AbstractBlazeQueryEnvironment<Target> } static final Function<SkyKey, Label> SKYKEY_TO_LABEL = - new Function<SkyKey, Label>() { - @Nullable - @Override - public Label apply(SkyKey skyKey) { - SkyFunctionName functionName = skyKey.functionName(); - if (!functionName.equals(Label.TRANSITIVE_TRAVERSAL)) { - // Skip non-targets. - return null; - } - return (Label) skyKey.argument(); + skyKey -> { + SkyFunctionName functionName = skyKey.functionName(); + if (!functionName.equals(Label.TRANSITIVE_TRAVERSAL)) { + // Skip non-targets. + return null; } + return (Label) skyKey.argument(); }; static final Function<SkyKey, PackageIdentifier> PACKAGE_SKYKEY_TO_PACKAGE_IDENTIFIER = - new Function<SkyKey, PackageIdentifier>() { - @Override - public PackageIdentifier apply(SkyKey skyKey) { - return (PackageIdentifier) skyKey.argument(); - } - }; + skyKey -> (PackageIdentifier) skyKey.argument(); @ThreadSafe Multimap<SkyKey, SkyKey> makePackageKeyToTargetKeyMap(Iterable<SkyKey> keys) { @@ -975,12 +953,7 @@ public class SkyQueryEnvironment extends AbstractBlazeQueryEnvironment<Target> } static final Function<Target, SkyKey> TARGET_TO_SKY_KEY = - new Function<Target, SkyKey>() { - @Override - public SkyKey apply(Target target) { - return TransitiveTraversalValue.key(target.getLabel()); - } - }; + target -> TransitiveTraversalValue.key(target.getLabel()); /** A strict (i.e. non-lazy) variant of {@link #makeTransitiveTraversalKeys}. */ public static Iterable<SkyKey> makeTransitiveTraversalKeysStrict(Iterable<Target> targets) { @@ -1080,49 +1053,26 @@ public class SkyQueryEnvironment extends AbstractBlazeQueryEnvironment<Target> } return result; } - - private static final Function<SkyValue, Package> EXTRACT_PACKAGE = - new Function<SkyValue, Package>() { - @Override - public Package apply(SkyValue skyValue) { - return ((PackageValue) skyValue).getPackage(); - } - }; - - private static final Predicate<Package> ERROR_FREE_PACKAGE = - new Predicate<Package>() { - @Override - public boolean apply(Package pkg) { - return !pkg.containsErrors(); - } - }; - - private static final Function<Package, Target> GET_BUILD_FILE = - new Function<Package, Target>() { - @Override - public Target apply(Package pkg) { - return pkg.getBuildFile(); - } - }; - static Iterable<Target> getBuildFilesForPackageValues(Iterable<SkyValue> packageValues) { + // TODO(laurentlb): Use streams? return Iterables.transform( - Iterables.filter(Iterables.transform(packageValues, EXTRACT_PACKAGE), ERROR_FREE_PACKAGE), - GET_BUILD_FILE); + Iterables.filter( + Iterables.transform(packageValues, skyValue -> ((PackageValue) skyValue).getPackage()), + pkg -> !pkg.containsErrors()), + Package::getBuildFile); } @ThreadSafe QueryTaskFuture<Void> getRBuildFilesParallel( final Collection<PathFragment> fileIdentifiers, final Callback<Target> callback) { - return QueryTaskFutureImpl.ofDelegate(safeSubmit(new Callable<Void>() { - @Override - public Void call() throws QueryException, InterruptedException { - ParallelSkyQueryUtils.getRBuildFilesParallel( - SkyQueryEnvironment.this, fileIdentifiers, callback, packageSemaphore); - return null; - } - })); + return QueryTaskFutureImpl.ofDelegate( + safeSubmit( + () -> { + ParallelSkyQueryUtils.getRBuildFilesParallel( + SkyQueryEnvironment.this, fileIdentifiers, callback, packageSemaphore); + return null; + })); } /** diff --git a/src/main/java/com/google/devtools/build/lib/query2/engine/AbstractQueryEnvironment.java b/src/main/java/com/google/devtools/build/lib/query2/engine/AbstractQueryEnvironment.java index c9e9a0ab74..818813c75c 100644 --- a/src/main/java/com/google/devtools/build/lib/query2/engine/AbstractQueryEnvironment.java +++ b/src/main/java/com/google/devtools/build/lib/query2/engine/AbstractQueryEnvironment.java @@ -19,7 +19,6 @@ import com.google.common.base.Function; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; -import com.google.common.util.concurrent.AsyncFunction; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import java.util.concurrent.CancellationException; @@ -186,24 +185,12 @@ public abstract class AbstractQueryEnvironment<T> implements QueryEnvironment<T> return QueryTaskFutureImpl.ofDelegate( Futures.transformAsync( (QueryTaskFutureImpl<T1>) future, - new AsyncFunction<T1, T2>() { - @Override - public ListenableFuture<T2> apply(T1 input) throws Exception { - return (QueryTaskFutureImpl<T2>) function.apply(input); - } - }, + input -> (QueryTaskFutureImpl<T2>) function.apply(input), directExecutor())); } protected static Iterable<QueryTaskFutureImpl<?>> cast( Iterable<? extends QueryTaskFuture<?>> futures) { - return Iterables.transform( - futures, - new Function<QueryTaskFuture<?>, QueryTaskFutureImpl<?>>() { - @Override - public QueryTaskFutureImpl<?> apply(QueryTaskFuture<?> future) { - return (QueryTaskFutureImpl<?>) future; - } - }); + return Iterables.transform(futures, future -> (QueryTaskFutureImpl<?>) future); } } diff --git a/src/main/java/com/google/devtools/build/lib/query2/engine/BinaryOperatorExpression.java b/src/main/java/com/google/devtools/build/lib/query2/engine/BinaryOperatorExpression.java index cd042ea235..31fa78577d 100644 --- a/src/main/java/com/google/devtools/build/lib/query2/engine/BinaryOperatorExpression.java +++ b/src/main/java/com/google/devtools/build/lib/query2/engine/BinaryOperatorExpression.java @@ -103,31 +103,29 @@ public class BinaryOperatorExpression extends QueryExpression { QueryTaskFuture<ThreadSafeMutableSet<T>> lhsValueFuture = QueryUtil.evalAll(env, context, operands.get(0)); Function<ThreadSafeMutableSet<T>, QueryTaskFuture<Void>> subtractAsyncFunction = - new Function<ThreadSafeMutableSet<T>, QueryTaskFuture<Void>>() { - @Override - public QueryTaskFuture<Void> apply(ThreadSafeMutableSet<T> lhsValue) { - final Set<T> threadSafeLhsValue = lhsValue; - Callback<T> subtractionCallback = new Callback<T>() { - @Override - public void process(Iterable<T> partialResult) { - for (T target : partialResult) { - threadSafeLhsValue.remove(target); - } - } + lhsValue -> { + final Set<T> threadSafeLhsValue = lhsValue; + Callback<T> subtractionCallback = + new Callback<T>() { + @Override + public void process(Iterable<T> partialResult) { + for (T target : partialResult) { + threadSafeLhsValue.remove(target); + } + } + }; + QueryTaskFuture<Void> rhsEvaluatedFuture = + evalPlus(operands.subList(1, operands.size()), env, context, subtractionCallback); + return env.whenSucceedsCall( + rhsEvaluatedFuture, + new QueryTaskCallable<Void>() { + @Override + public Void call() throws QueryException, InterruptedException { + callback.process(threadSafeLhsValue); + return null; + } + }); }; - QueryTaskFuture<Void> rhsEvaluatedFuture = evalPlus( - operands.subList(1, operands.size()), env, context, subtractionCallback); - return env.whenSucceedsCall( - rhsEvaluatedFuture, - new QueryTaskCallable<Void>() { - @Override - public Void call() throws QueryException, InterruptedException { - callback.process(threadSafeLhsValue); - return null; - } - }); - } - }; return env.transformAsync(lhsValueFuture, subtractAsyncFunction); } @@ -148,24 +146,20 @@ public class BinaryOperatorExpression extends QueryExpression { final int index = i; Function<ThreadSafeMutableSet<T>, QueryTaskFuture<ThreadSafeMutableSet<T>>> evalOperandAndIntersectAsyncFunction = - new Function<ThreadSafeMutableSet<T>, QueryTaskFuture<ThreadSafeMutableSet<T>>>() { - @Override - public QueryTaskFuture<ThreadSafeMutableSet<T>> apply( - final ThreadSafeMutableSet<T> rollingResult) { - final QueryTaskFuture<ThreadSafeMutableSet<T>> rhsOperandValueFuture = - QueryUtil.evalAll(env, context, operands.get(index)); - return env.whenSucceedsCall( - rhsOperandValueFuture, - new QueryTaskCallable<ThreadSafeMutableSet<T>>() { - @Override - public ThreadSafeMutableSet<T> call() - throws QueryException, InterruptedException { - rollingResult.retainAll(rhsOperandValueFuture.getIfSuccessful()); - return rollingResult; - } - }); - } - }; + rollingResult -> { + final QueryTaskFuture<ThreadSafeMutableSet<T>> rhsOperandValueFuture = + QueryUtil.evalAll(env, context, operands.get(index)); + return env.whenSucceedsCall( + rhsOperandValueFuture, + new QueryTaskCallable<ThreadSafeMutableSet<T>>() { + @Override + public ThreadSafeMutableSet<T> call() + throws QueryException, InterruptedException { + rollingResult.retainAll(rhsOperandValueFuture.getIfSuccessful()); + return rollingResult; + } + }); + }; rollingResultFuture = env.transformAsync(rollingResultFuture, evalOperandAndIntersectAsyncFunction); } diff --git a/src/main/java/com/google/devtools/build/lib/query2/engine/FunctionExpression.java b/src/main/java/com/google/devtools/build/lib/query2/engine/FunctionExpression.java index 85cfe9fddb..a8c21d61c4 100644 --- a/src/main/java/com/google/devtools/build/lib/query2/engine/FunctionExpression.java +++ b/src/main/java/com/google/devtools/build/lib/query2/engine/FunctionExpression.java @@ -13,10 +13,10 @@ // limitations under the License. package com.google.devtools.build.lib.query2.engine; +import static java.util.stream.Collectors.joining; + import com.google.common.base.Functions; -import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; import com.google.devtools.build.lib.query2.engine.QueryEnvironment.Argument; import com.google.devtools.build.lib.query2.engine.QueryEnvironment.ArgumentType; import com.google.devtools.build.lib.query2.engine.QueryEnvironment.QueryFunction; @@ -66,7 +66,9 @@ public class FunctionExpression extends QueryExpression { @Override public String toString() { - return function.getName() + - "(" + Joiner.on(", ").join(Iterables.transform(args, Functions.toStringFunction())) + ")"; + return function.getName() + + "(" + + args.stream().map(Functions.toStringFunction()).collect(joining(", ")) + + ")"; } } diff --git a/src/main/java/com/google/devtools/build/lib/query2/engine/LetExpression.java b/src/main/java/com/google/devtools/build/lib/query2/engine/LetExpression.java index 05021e6f8a..fd10135e57 100644 --- a/src/main/java/com/google/devtools/build/lib/query2/engine/LetExpression.java +++ b/src/main/java/com/google/devtools/build/lib/query2/engine/LetExpression.java @@ -77,13 +77,10 @@ class LetExpression extends QueryExpression { QueryTaskFuture<ThreadSafeMutableSet<T>> varValueFuture = QueryUtil.evalAll(env, context, varExpr); Function<ThreadSafeMutableSet<T>, QueryTaskFuture<Void>> evalBodyAsyncFunction = - new Function<ThreadSafeMutableSet<T>, QueryTaskFuture<Void>>() { - @Override - public QueryTaskFuture<Void> apply(ThreadSafeMutableSet<T> varValue) { - VariableContext<T> bodyContext = VariableContext.with(context, varName, varValue); - return env.eval(bodyExpr, bodyContext, callback); - } - }; + varValue -> { + VariableContext<T> bodyContext = VariableContext.with(context, varName, varValue); + return env.eval(bodyExpr, bodyContext, callback); + }; return env.transformAsync(varValueFuture, evalBodyAsyncFunction); } diff --git a/src/main/java/com/google/devtools/build/lib/query2/engine/RdepsFunction.java b/src/main/java/com/google/devtools/build/lib/query2/engine/RdepsFunction.java index 81c0cfcaf0..ebd4d7d106 100644 --- a/src/main/java/com/google/devtools/build/lib/query2/engine/RdepsFunction.java +++ b/src/main/java/com/google/devtools/build/lib/query2/engine/RdepsFunction.java @@ -65,21 +65,18 @@ public final class RdepsFunction extends AllRdepsFunction { QueryTaskFuture<ThreadSafeMutableSet<T>> universeValueFuture = QueryUtil.evalAll(env, context, args.get(0).getExpression()); Function<ThreadSafeMutableSet<T>, QueryTaskFuture<Void>> evalInUniverseAsyncFunction = - new Function<ThreadSafeMutableSet<T>, QueryTaskFuture<Void>>() { - @Override - public QueryTaskFuture<Void> apply(ThreadSafeMutableSet<T> universeValue) { - Predicate<T> universe; - try { - env.buildTransitiveClosure(expression, universeValue, Integer.MAX_VALUE); - universe = Predicates.in(env.getTransitiveClosure(universeValue)); - } catch (InterruptedException e) { - return env.immediateCancelledFuture(); - } catch (QueryException e) { - return env.immediateFailedFuture(e); - } - return RdepsFunction.this.eval( - env, context, args.subList(1, args.size()), callback, Optional.of(universe)); + universeValue -> { + Predicate<T> universe; + try { + env.buildTransitiveClosure(expression, universeValue, Integer.MAX_VALUE); + universe = Predicates.in(env.getTransitiveClosure(universeValue)); + } catch (InterruptedException e) { + return env.immediateCancelledFuture(); + } catch (QueryException e) { + return env.immediateFailedFuture(e); } + return RdepsFunction.this.eval( + env, context, args.subList(1, args.size()), callback, Optional.of(universe)); }; return env.transformAsync(universeValueFuture, evalInUniverseAsyncFunction); } diff --git a/src/main/java/com/google/devtools/build/lib/query2/engine/RegexFilterExpression.java b/src/main/java/com/google/devtools/build/lib/query2/engine/RegexFilterExpression.java index 6b182ee7b1..136e0a6273 100644 --- a/src/main/java/com/google/devtools/build/lib/query2/engine/RegexFilterExpression.java +++ b/src/main/java/com/google/devtools/build/lib/query2/engine/RegexFilterExpression.java @@ -54,17 +54,15 @@ public abstract class RegexFilterExpression implements QueryFunction { // Note that Patttern#matcher is thread-safe and so this Predicate can safely be used // concurrently. - final Predicate<T> matchFilter = new Predicate<T>() { - @Override - public boolean apply(T target) { - for (String str : getFilterStrings(env, args, target)) { - if ((str != null) && compiledPattern.matcher(str).find()) { - return true; + final Predicate<T> matchFilter = + target -> { + for (String str : getFilterStrings(env, args, target)) { + if ((str != null) && compiledPattern.matcher(str).find()) { + return true; + } } - } - return false; - } - }; + return false; + }; return env.eval( Iterables.getLast(args).getExpression(), diff --git a/src/main/java/com/google/devtools/build/lib/query2/engine/VisibleFunction.java b/src/main/java/com/google/devtools/build/lib/query2/engine/VisibleFunction.java index 7a364b8285..072013371d 100644 --- a/src/main/java/com/google/devtools/build/lib/query2/engine/VisibleFunction.java +++ b/src/main/java/com/google/devtools/build/lib/query2/engine/VisibleFunction.java @@ -63,22 +63,17 @@ public class VisibleFunction implements QueryFunction { final QueryTaskFuture<ThreadSafeMutableSet<T>> toSetFuture = QueryUtil.evalAll(env, context, args.get(0).getExpression()); Function<ThreadSafeMutableSet<T>, QueryTaskFuture<Void>> computeVisibleNodesAsyncFunction = - new Function<ThreadSafeMutableSet<T>, QueryTaskFuture<Void>>() { - @Override - public QueryTaskFuture<Void> apply(final ThreadSafeMutableSet<T> toSet) { - return env.eval(args.get(1).getExpression(), context, new Callback<T>() { - @Override - public void process(Iterable<T> partialResult) - throws QueryException, InterruptedException { - for (T t : partialResult) { - if (visibleToAll(env, toSet, t)) { - callback.process(ImmutableList.of(t)); + toSet -> + env.eval( + args.get(1).getExpression(), + context, + partialResult -> { + for (T t : partialResult) { + if (visibleToAll(env, toSet, t)) { + callback.process(ImmutableList.of(t)); + } } - } - } - }); - } - }; + }); return env.transformAsync(toSetFuture, computeVisibleNodesAsyncFunction); } diff --git a/src/main/java/com/google/devtools/build/lib/query2/output/OutputFormatter.java b/src/main/java/com/google/devtools/build/lib/query2/output/OutputFormatter.java index 4b732e1c15..75f0b807ac 100644 --- a/src/main/java/com/google/devtools/build/lib/query2/output/OutputFormatter.java +++ b/src/main/java/com/google/devtools/build/lib/query2/output/OutputFormatter.java @@ -13,13 +13,16 @@ // limitations under the License. package com.google.devtools.build.lib.query2.output; +import static java.util.Comparator.comparingInt; +import static java.util.stream.Collectors.joining; + import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; -import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Sets; +import com.google.common.collect.Streams; import com.google.devtools.build.lib.cmdline.Label; import com.google.devtools.build.lib.collect.CompactHashSet; import com.google.devtools.build.lib.events.Location; @@ -99,13 +102,7 @@ public abstract class OutputFormatter implements Serializable { DEFAULT // Rule class default } - public static final Function<Node<Target>, Target> EXTRACT_NODE_LABEL = - new Function<Node<Target>, Target>() { - @Override - public Target apply(Node<Target> input) { - return input.getLabel(); - } - }; + public static final Function<Node<Target>, Target> EXTRACT_NODE_LABEL = Node::getLabel; /** * Converter from strings to OutputFormatter.OutputType. @@ -129,13 +126,7 @@ public abstract class OutputFormatter implements Serializable { } public static String formatterNames(Iterable<OutputFormatter> formatters) { - return Joiner.on(", ").join(Iterables.transform(formatters, - new Function<OutputFormatter, String>() { - @Override - public String apply(OutputFormatter input) { - return input.getName(); - } - })); + return Streams.stream(formatters).map(OutputFormatter::getName).collect(joining(", ")); } /** @@ -730,14 +721,7 @@ public abstract class OutputFormatter implements Serializable { // Use the natural order for RankAndLabels, which breaks ties alphabetically. Collections.sort(output); } else { - Collections.sort( - output, - new Comparator<RankAndLabel>() { - @Override - public int compare(RankAndLabel o1, RankAndLabel o2) { - return o1.rank - o2.rank; - } - }); + Collections.sort(output, comparingInt(arg -> arg.rank)); } final String lineTerm = options.getLineTerminator(); PrintStream printStream = new PrintStream(out); diff --git a/src/main/java/com/google/devtools/build/lib/remote/TreeNodeRepository.java b/src/main/java/com/google/devtools/build/lib/remote/TreeNodeRepository.java index dba3a14c12..18d61ed1d7 100644 --- a/src/main/java/com/google/devtools/build/lib/remote/TreeNodeRepository.java +++ b/src/main/java/com/google/devtools/build/lib/remote/TreeNodeRepository.java @@ -14,7 +14,6 @@ package com.google.devtools.build.lib.remote; -import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableCollection; import com.google.common.collect.ImmutableList; @@ -202,14 +201,7 @@ public final class TreeNodeRepository extends TreeTraverser<TreeNodeRepository.T @Override public Iterable<TreeNode> children(TreeNode node) { - return Iterables.transform( - node.getChildEntries(), - new Function<TreeNode.ChildEntry, TreeNode>() { - @Override - public TreeNode apply(TreeNode.ChildEntry entry) { - return entry.getChild(); - } - }); + return Iterables.transform(node.getChildEntries(), TreeNode.ChildEntry::getChild); } /** Traverse the directory structure in order (pre-order tree traversal). */ diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidAaptActionHelper.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidAaptActionHelper.java index e9f149c93e..b94f2de4ba 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidAaptActionHelper.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidAaptActionHelper.java @@ -14,7 +14,6 @@ package com.google.devtools.build.lib.rules.android; import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.devtools.build.lib.actions.Artifact; @@ -66,13 +65,10 @@ public final class AndroidAaptActionHelper { if (inputs.isEmpty()) { inputs.add(AndroidSdkProvider.fromRuleContext(ruleContext).getAndroidJar()); inputs.add(manifest); - Iterables.addAll(inputs, Iterables.concat(Iterables.transform(resourceContainers, - new Function<ResourceContainer, Iterable<Artifact>>() { - @Override - public Iterable<Artifact> apply(ResourceContainer container) { - return container.getArtifacts(); - } - }))); + Iterables.addAll( + inputs, + Iterables.concat( + Iterables.transform(resourceContainers, ResourceContainer::getArtifacts))); } return inputs; } diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidBinary.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidBinary.java index 28d635d4a2..438748c5ec 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidBinary.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidBinary.java @@ -16,7 +16,7 @@ package com.google.devtools.build.lib.rules.android; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Predicates.in; import static com.google.common.base.Predicates.not; -import static com.google.common.collect.Iterables.filter; +import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.devtools.build.lib.analysis.OutputGroupProvider.INTERNAL_SUFFIX; import com.google.common.base.Function; @@ -29,6 +29,7 @@ import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Multimap; import com.google.common.collect.MultimapBuilder; +import com.google.common.collect.Streams; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.actions.FailAction; import com.google.devtools.build.lib.actions.ParameterFile.ParameterFileType; @@ -980,8 +981,10 @@ public abstract class AndroidBinary implements RuleConfiguredTargetFactory { } NestedSet<Artifact> libraryResourceJars = libraryResourceJarsBuilder.build(); - Iterable<Artifact> filteredJars = ImmutableList.copyOf( - filter(jars, not(in(libraryResourceJars.toSet())))); + Iterable<Artifact> filteredJars = + Streams.stream(jars) + .filter(not(in(libraryResourceJars.toSet()))) + .collect(toImmutableList()); AndroidSdkProvider sdk = AndroidSdkProvider.fromRuleContext(ruleContext); diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidCcLinkParamsProvider.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidCcLinkParamsProvider.java index c19034bf36..0e21694bdc 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidCcLinkParamsProvider.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidCcLinkParamsProvider.java @@ -32,13 +32,9 @@ public abstract class AndroidCcLinkParamsProvider implements TransitiveInfoProvi public abstract CcLinkParamsStore getLinkParams(); public static final Function<TransitiveInfoCollection, CcLinkParamsStore> TO_LINK_PARAMS = - new Function<TransitiveInfoCollection, CcLinkParamsStore>() { - @Override - public CcLinkParamsStore apply(TransitiveInfoCollection input) { - AndroidCcLinkParamsProvider provider = input.getProvider( - AndroidCcLinkParamsProvider.class); - return provider == null ? null : provider.getLinkParams(); - } + (TransitiveInfoCollection input) -> { + AndroidCcLinkParamsProvider provider = input.getProvider(AndroidCcLinkParamsProvider.class); + return provider == null ? null : provider.getLinkParams(); }; AndroidCcLinkParamsProvider() {} diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidDevice.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidDevice.java index a126da1267..9858bddd1f 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidDevice.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidDevice.java @@ -13,14 +13,16 @@ // limitations under the License. package com.google.devtools.build.lib.rules.android; -import com.google.common.base.Function; -import com.google.common.base.Joiner; +import static com.google.common.collect.MoreCollectors.onlyElement; +import static java.util.stream.Collectors.joining; + import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; +import com.google.common.collect.Streams; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.actions.ResourceSet; import com.google.devtools.build.lib.analysis.ConfiguredTarget; @@ -70,38 +72,11 @@ public class AndroidDevice implements RuleConfiguredTargetFactory { // this is a much lower pixels-per-inch then even some of the oldest phones. private static final int MIN_LCD_DENSITY = 30; - private static final Predicate<Artifact> SOURCE_ARTIFACT_SELECTOR = new Predicate<Artifact>() { - @Override - public boolean apply(Artifact artifact) { - return artifact.isSourceArtifact(); - } - }; - - private static final Predicate<Artifact> GOOGLETEST_SH_SELECTOR = new Predicate<Artifact>() { - @Override - public boolean apply(Artifact artifact) { - return "googletest.sh".equals(artifact.getPath().getBaseName()); - } - }; - - private static final Predicate<Artifact> SOURCE_PROPERTIES_SELECTOR = new Predicate<Artifact>() { - @Override - public boolean apply(Artifact artifact) { - return "source.properties".equals(artifact.getPath().getBaseName()); - } - }; + private static final Predicate<Artifact> SOURCE_PROPERTIES_SELECTOR = + (Artifact artifact) -> "source.properties".equals(artifact.getPath().getBaseName()); private static final Predicate<Artifact> SOURCE_PROPERTIES_FILTER = Predicates.not( SOURCE_PROPERTIES_SELECTOR); - - private static final Function<Artifact, String> RUNFILES_PATH_STRING = - new Function<Artifact, String>() { - @Override - public String apply(Artifact input) { - return input.getRunfilesPathString(); - } - }; - @Override public ConfiguredTarget create(RuleContext ruleContext) throws InterruptedException, RuleErrorException { @@ -214,10 +189,14 @@ public class AndroidDevice implements RuleConfiguredTargetFactory { androidRuntestDeps = ruleContext.getPrerequisiteArtifacts("$android_runtest", Mode.HOST).list(); androidRuntest = - Iterables.getOnlyElement(Iterables.filter(androidRuntestDeps, SOURCE_ARTIFACT_SELECTOR)); + androidRuntestDeps.stream().filter(Artifact::isSourceArtifact).collect(onlyElement()); testingShbaseDeps = ruleContext.getPrerequisiteArtifacts("$testing_shbase", Mode.HOST).list(); testingShbase = - Iterables.getOnlyElement(Iterables.filter(testingShbaseDeps, GOOGLETEST_SH_SELECTOR)); + testingShbaseDeps + .stream() + .filter( + (Artifact artifact) -> "googletest.sh".equals(artifact.getPath().getBaseName())) + .collect(onlyElement()); // may be empty platformApks = ruleContext.getPrerequisiteArtifacts("platform_apks", Mode.TARGET).list(); @@ -282,10 +261,16 @@ public class AndroidDevice implements RuleConfiguredTargetFactory { arguments.add(Substitution.of("%emulator_arm%", emulatorArm.getRunfilesPathString())); arguments.add(Substitution.of("%mksdcard%", mksdcard.getRunfilesPathString())); arguments.add(Substitution.of("%empty_snapshot_fs%", snapshotFs.getRunfilesPathString())); - arguments.add(Substitution.of("%system_images%", - Joiner.on(" ").join(Iterables.transform(systemImages, RUNFILES_PATH_STRING)))); - arguments.add(Substitution.of("%bios_files%", - Joiner.on(" ").join(Iterables.transform(emulatorX86Bios, RUNFILES_PATH_STRING)))); + arguments.add( + Substitution.of( + "%system_images%", + Streams.stream(systemImages) + .map(Artifact::getRunfilesPathString) + .collect(joining(" ")))); + arguments.add( + Substitution.of( + "%bios_files%", + emulatorX86Bios.stream().map(Artifact::getRunfilesPathString).collect(joining(" ")))); arguments.add(Substitution.of("%source_properties_file%", sourcePropertiesFile.getRunfilesPathString())); arguments.add(Substitution.of("%image_input_file%", images.getRunfilesPathString())); diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidInstrumentationTest.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidInstrumentationTest.java index 0e5c7170a7..20066b36c3 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidInstrumentationTest.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidInstrumentationTest.java @@ -17,6 +17,7 @@ import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; +import com.google.common.collect.Streams; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.analysis.ConfiguredTarget; import com.google.devtools.build.lib.analysis.FilesToRunProvider; @@ -37,7 +38,6 @@ import com.google.devtools.build.lib.rules.test.ExecutionInfoProvider; import com.google.devtools.build.lib.syntax.Type; import com.google.devtools.build.lib.util.ResourceFileLoader; import java.io.IOException; -import java.util.stream.StreamSupport; import javax.annotation.Nullable; /** An implementation of the {@code android_instrumentation} rule. */ @@ -170,7 +170,7 @@ public class AndroidInstrumentationTest implements RuleConfiguredTargetFactory { private static Substitution artifactListSubstitution(String key, Iterable<Artifact> artifacts) { return Substitution.ofSpaceSeparatedList( key, - StreamSupport.stream(artifacts.spliterator(), false) + Streams.stream(artifacts) .map(Artifact::getRunfilesPathString) .collect(ImmutableList.toImmutableList())); } diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidLocalTestBase.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidLocalTestBase.java index 3b58190638..ad05fa7508 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidLocalTestBase.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidLocalTestBase.java @@ -16,12 +16,12 @@ package com.google.devtools.build.lib.rules.android; import static com.google.devtools.build.lib.packages.BuildType.LABEL_LIST; import static com.google.devtools.build.lib.rules.java.DeployArchiveBuilder.Compression.COMPRESSED; import static com.google.devtools.build.lib.vfs.FileSystemUtils.replaceExtension; +import static java.util.stream.Collectors.toCollection; -import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; -import com.google.common.collect.Sets; +import com.google.common.collect.Streams; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.analysis.ConfiguredTarget; import com.google.devtools.build.lib.analysis.FileProvider; @@ -61,7 +61,9 @@ import com.google.devtools.build.lib.rules.java.proto.GeneratedExtensionRegistry import com.google.devtools.build.lib.syntax.Type; import com.google.devtools.build.lib.vfs.PathFragment; import java.util.ArrayList; +import java.util.LinkedHashSet; import java.util.List; +import java.util.stream.Stream; /** * An base implementation for the "android_local_test" rule. @@ -214,12 +216,14 @@ public abstract class AndroidLocalTestBase implements RuleConfiguredTargetFactor NestedSet<Artifact> filesToBuild = filesToBuildBuilder.build(); Iterable<AndroidLibraryAarProvider> androidAarProviders = - Sets.newLinkedHashSet( - Iterables.concat( - ruleContext.getPrerequisites( - "runtime_deps", Mode.TARGET, AndroidLibraryAarProvider.class), - ruleContext.getPrerequisites( - "deps", Mode.TARGET, AndroidLibraryAarProvider.class))); + Stream.concat( + Streams.stream( + ruleContext.getPrerequisites( + "runtime_deps", Mode.TARGET, AndroidLibraryAarProvider.class)), + Streams.stream( + ruleContext.getPrerequisites( + "deps", Mode.TARGET, AndroidLibraryAarProvider.class))) + .collect(toCollection(LinkedHashSet::new)); NestedSetBuilder<Aar> transitiveAarsBuilder = NestedSetBuilder.naiveLinkOrder(); NestedSetBuilder<Aar> strictAarsBuilder = NestedSetBuilder.naiveLinkOrder(); @@ -241,27 +245,11 @@ public abstract class AndroidLocalTestBase implements RuleConfiguredTargetFactor CustomCommandLine.Builder cmdLineArgs = CustomCommandLine.builder(); if (!transitiveAars.isEmpty()) { cmdLineArgs.addJoinValues( - "--android_libraries", - ",", - transitiveAars, - new Function<Aar, String>() { - @Override - public String apply(Aar aar) { - return aarCmdLineArg(aar); - } - }); + "--android_libraries", ",", transitiveAars, AndroidLocalTestBase::aarCmdLineArg); } if (!strictAars.isEmpty()) { cmdLineArgs.addJoinValues( - "--strict_libraries", - ",", - strictAars, - new Function<Aar, String>() { - @Override - public String apply(Aar aar) { - return aarCmdLineArg(aar); - } - }); + "--strict_libraries", ",", strictAars, AndroidLocalTestBase::aarCmdLineArg); } RunfilesSupport runfilesSupport = RunfilesSupport.withExecutable( diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidResourceParsingActionBuilder.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidResourceParsingActionBuilder.java index 8a49985468..3861856655 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidResourceParsingActionBuilder.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidResourceParsingActionBuilder.java @@ -13,13 +13,13 @@ // limitations under the License. package com.google.devtools.build.lib.rules.android; +import static java.util.stream.Collectors.joining; + import com.google.common.base.Function; -import com.google.common.base.Functions; -import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; +import com.google.common.collect.Streams; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.actions.ParameterFile.ParameterFileType; import com.google.devtools.build.lib.analysis.RuleConfiguredTarget.Mode; @@ -122,7 +122,7 @@ public class AndroidResourceParsingActionBuilder { } private static String convertRoots(Iterable<PathFragment> roots) { - return Joiner.on("#").join(Iterables.transform(roots, Functions.toStringFunction())); + return Streams.stream(roots).map(Object::toString).collect(joining("#")); } public ResourceContainer build(ActionConstructionContext context) { diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidResourceValidatorActionBuilder.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidResourceValidatorActionBuilder.java index ee77eaa6df..f8169a1500 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidResourceValidatorActionBuilder.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidResourceValidatorActionBuilder.java @@ -13,7 +13,6 @@ // limitations under the License. package com.google.devtools.build.lib.rules.android; -import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.base.Strings; @@ -28,7 +27,6 @@ import com.google.devtools.build.lib.analysis.actions.CustomCommandLine; import com.google.devtools.build.lib.analysis.actions.SpawnAction; import java.util.ArrayList; import java.util.List; -import javax.annotation.Nullable; /** * Builder for creating $android_resource_validator action. This action validates merged resources @@ -57,13 +55,6 @@ class AndroidResourceValidatorActionBuilder { private ResourceDependencies resourceDeps; private Artifact aapt2SourceJarOut; private Artifact aapt2RTxtOut; - private static final Function<ResourceContainer, Artifact> TO_STATIC_LIBRARY_ARTIFACT = - new Function<ResourceContainer, Artifact>() { - @Override - public Artifact apply(@Nullable ResourceContainer resourceContainer) { - return resourceContainer.getStaticLibrary(); - } - }; private Artifact compiledSymbols; /** @param ruleContext The RuleContext that was used to create the SpawnAction.Builder. */ @@ -161,7 +152,8 @@ class AndroidResourceValidatorActionBuilder { builder.addExecPath("--aapt2", sdk.getAapt2().getExecutable()); FluentIterable<Artifact> libraries = - FluentIterable.from(resourceDeps.getResources()).transform(TO_STATIC_LIBRARY_ARTIFACT); + FluentIterable.from(resourceDeps.getResources()) + .transform(ResourceContainer::getStaticLibrary); builder .add("--libraries") diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidRuntimeJarProvider.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidRuntimeJarProvider.java index 85e5fa97fd..1c949850ca 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidRuntimeJarProvider.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidRuntimeJarProvider.java @@ -24,7 +24,6 @@ import com.google.devtools.build.lib.collect.nestedset.NestedSet; import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder; import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable; import java.util.HashMap; -import javax.annotation.Nullable; /** * Provider of Jar files transitively to be included into the runtime classpath of an Android app. @@ -90,13 +89,9 @@ public class AndroidRuntimeJarProvider implements TransitiveInfoProvider { for (ImmutableMap<Artifact, Artifact> partialMapping : runtimeJars) { collapsed.putAll(partialMapping); } - return new Function<Artifact, Artifact>() { - @Override - @Nullable - public Artifact apply(@Nullable Artifact jar) { - Artifact result = collapsed.get(jar); - return result != null ? result : jar; // return null iff input == null - } + return jar -> { + Artifact result = collapsed.get(jar); + return result != null ? result : jar; // return null iff input == null }; } } diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidSkylarkApiProvider.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidSkylarkApiProvider.java index afad1131cc..edf6f2a08f 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidSkylarkApiProvider.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidSkylarkApiProvider.java @@ -13,7 +13,6 @@ // limitations under the License. package com.google.devtools.build.lib.rules.android; -import com.google.common.base.Function; import com.google.common.collect.ImmutableCollection; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; @@ -187,12 +186,8 @@ public class AndroidSkylarkApiProvider extends SkylarkApiProvider { Iterables.concat( Iterables.transform( provider.getDirectAndroidResources(), - new Function<ResourceContainer, Iterable<Artifact>>() { - @Override - public Iterable<Artifact> apply(ResourceContainer resourceContainer) { - return resourceContainer.getArtifacts(resources); - } - }))); + (ResourceContainer resourceContainer) -> + resourceContainer.getArtifacts(resources)))); } /** Helper class to provide information about IDLs related to this rule. */ diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/DexArchiveAspect.java b/src/main/java/com/google/devtools/build/lib/rules/android/DexArchiveAspect.java index 8f7042ae52..05ed23d909 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/DexArchiveAspect.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/DexArchiveAspect.java @@ -19,6 +19,7 @@ import static com.google.devtools.build.lib.packages.BuildType.LABEL; import static com.google.devtools.build.lib.packages.BuildType.TRISTATE; import static com.google.devtools.build.lib.rules.android.AndroidCommon.getAndroidConfig; import static java.nio.charset.StandardCharsets.ISO_8859_1; +import static java.util.stream.Collectors.toCollection; import com.google.common.base.Function; import com.google.common.base.Functions; @@ -29,6 +30,7 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; +import com.google.common.collect.Streams; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.actions.ExecutionRequirements; import com.google.devtools.build.lib.actions.ParameterFile; @@ -65,6 +67,7 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.TreeSet; /** * Aspect to {@link DexArchiveProvider build .dex Archives} from Jars. @@ -76,15 +79,12 @@ public final class DexArchiveAspect extends NativeAspectClass implements Configu * aspect. Must be provided when attaching this aspect to a target. */ public static final Function<Rule, AspectParameters> PARAM_EXTRACTOR = - new Function<Rule, AspectParameters>() { - @Override - public AspectParameters apply(Rule rule) { - AttributeMap attributes = NonconfigurableAttributeMapper.of(rule); - AspectParameters.Builder result = new AspectParameters.Builder(); - TriState incrementalAttr = attributes.get("incremental_dexing", TRISTATE); - result.addAttribute("incremental_dexing", incrementalAttr.name()); - return result.build(); - } + (Rule rule) -> { + AttributeMap attributes = NonconfigurableAttributeMapper.of(rule); + AspectParameters.Builder result = new AspectParameters.Builder(); + TriState incrementalAttr = attributes.get("incremental_dexing", TRISTATE); + result.addAttribute("incremental_dexing", incrementalAttr.name()); + return result.build(); }; /** * Function that limits this aspect to Java 8 desugaring (disabling incremental dexing) when @@ -92,15 +92,10 @@ public final class DexArchiveAspect extends NativeAspectClass implements Configu * for {@code blaze mobile-install}. */ static final Function<Rule, AspectParameters> ONLY_DESUGAR_JAVA8 = - new Function<Rule, AspectParameters>() { - @Override - public AspectParameters apply(Rule rule) { - return new AspectParameters.Builder() + (Rule rule) -> + new AspectParameters.Builder() .addAttribute("incremental_dexing", TriState.NO.name()) .build(); - } - }; - /** Aspect-only label for dexbuidler executable, to avoid name clashes with labels on rules. */ private static final String ASPECT_DEXBUILDER_PREREQ = "$dex_archive_dexbuilder"; /** Aspect-only label for desugaring executable, to avoid name clashes with labels on rules. */ @@ -513,7 +508,10 @@ public final class DexArchiveAspect extends NativeAspectClass implements Configu // we generate one dex archive per set of flag in create() method, regardless of how those flags // are listed in all the top-level targets being built. return ImmutableSet.copyOf( - Sets.newTreeSet(Iterables.transform(tokenizedDexopts, FlagConverter.DX_TO_DEXBUILDER))); + Streams.stream(tokenizedDexopts) + .map(FlagConverter.DX_TO_DEXBUILDER) + .collect(toCollection(TreeSet::new)) + .iterator()); } private static class FlagMatcher implements Predicate<String> { diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/LibraryRGeneratorActionBuilder.java b/src/main/java/com/google/devtools/build/lib/rules/android/LibraryRGeneratorActionBuilder.java index 361a70a803..e4baef192a 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/LibraryRGeneratorActionBuilder.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/LibraryRGeneratorActionBuilder.java @@ -30,19 +30,9 @@ import com.google.devtools.build.lib.collect.nestedset.Order; /** Builder for the action that generates the R class for libraries. */ public class LibraryRGeneratorActionBuilder { static final Function<ResourceContainer, Artifact> TO_SYMBOL_ARTIFACT = - new Function<ResourceContainer, Artifact>() { - @Override - public Artifact apply(ResourceContainer input) { - return input.getSymbols(); - } - }; + ResourceContainer::getSymbols; static final Function<ResourceContainer, String> TO_SYMBOL_PATH = - new Function<ResourceContainer, String>() { - @Override - public String apply(ResourceContainer container) { - return container.getSymbols().getExecPathString(); - } - }; + (ResourceContainer container) -> container.getSymbols().getExecPathString(); private String javaPackage; private Iterable<ResourceContainer> deps = ImmutableList.<ResourceContainer>of(); diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/ManifestMergerActionBuilder.java b/src/main/java/com/google/devtools/build/lib/rules/android/ManifestMergerActionBuilder.java index c84e3fd1a3..00c1a866e3 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/ManifestMergerActionBuilder.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/ManifestMergerActionBuilder.java @@ -102,14 +102,11 @@ public class ManifestMergerActionBuilder { inputs.add(manifest); if (mergeeManifests != null && !mergeeManifests.isEmpty()) { - builder.add("--mergeeManifests") - .add(mapToDictionaryString(mergeeManifests, - new Function<Artifact, String>() { - @Override public String apply(Artifact input) { - return input.getExecPathString(); - } - }, - null /* valueConverter */)); + builder + .add("--mergeeManifests") + .add( + mapToDictionaryString( + mergeeManifests, Artifact::getExecPathString, null /* valueConverter */)); inputs.addAll(mergeeManifests.keySet()); } @@ -145,11 +142,8 @@ public class ManifestMergerActionBuilder { .build(context)); } - private static final Function<String, String> ESCAPER = new Function<String, String>() { - @Override public String apply(String value) { - return value.replace(":", "\\:").replace(",", "\\,"); - } - }; + private static final Function<String, String> ESCAPER = + (String value) -> value.replace(":", "\\:").replace(",", "\\,"); private <K, V> String mapToDictionaryString(Map<K, V> map) { return mapToDictionaryString(map, Functions.toStringFunction(), Functions.toStringFunction()); diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/ResourceContainerConverter.java b/src/main/java/com/google/devtools/build/lib/rules/android/ResourceContainerConverter.java index a78344077a..edca5d9e3b 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/ResourceContainerConverter.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/ResourceContainerConverter.java @@ -107,12 +107,7 @@ public class ResourceContainerConverter { // arguments in a list of arguments. Those characters require escaping if used in a label // (part of the set of allowed characters in a label). if (includeLabel) { - escaper = new Function<String, String>() { - @Override - public String apply(String input) { - return input.replace(":", "\\:").replace(",", "\\,"); - } - }; + escaper = (String input) -> input.replace(":", "\\:").replace(",", "\\,"); } break; case SEMICOLON_AMPERSAND: diff --git a/src/main/java/com/google/devtools/build/lib/rules/config/ConfigRuleClasses.java b/src/main/java/com/google/devtools/build/lib/rules/config/ConfigRuleClasses.java index 0b816c1a0e..a454719044 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/config/ConfigRuleClasses.java +++ b/src/main/java/com/google/devtools/build/lib/rules/config/ConfigRuleClasses.java @@ -20,17 +20,14 @@ import static com.google.devtools.build.lib.syntax.Type.STRING; import static com.google.devtools.build.lib.syntax.Type.STRING_DICT; import static com.google.devtools.build.lib.syntax.Type.STRING_LIST; -import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.google.devtools.build.lib.analysis.BaseRuleClasses; import com.google.devtools.build.lib.analysis.RuleContext; import com.google.devtools.build.lib.analysis.RuleDefinition; import com.google.devtools.build.lib.analysis.RuleDefinitionEnvironment; import com.google.devtools.build.lib.packages.NonconfigurableAttributeMapper; -import com.google.devtools.build.lib.packages.Rule; import com.google.devtools.build.lib.packages.RuleClass; import com.google.devtools.build.lib.syntax.Type; -import java.util.Set; /** * Definitions for rule classes that specify or manipulate configuration settings. @@ -111,16 +108,6 @@ public class ConfigRuleClasses { /** The name of the attribute that declares user-defined flag bindings. */ public static final String FLAG_SETTINGS_ATTRIBUTE = "flag_values"; - private static final Function<Rule, Set<String>> CONFIG_SETTING_OPTION_REFERENCE = - new Function<Rule, Set<String>>() { - @Override - public Set<String> apply(Rule rule) { - return NonconfigurableAttributeMapper.of(rule) - .get(SETTINGS_ATTRIBUTE, Type.STRING_DICT) - .keySet(); - } - }; - @Override public RuleClass build(RuleClass.Builder builder, RuleDefinitionEnvironment env) { return builder @@ -169,7 +156,11 @@ public class ConfigRuleClasses { ImmutableList.of(ConfigFeatureFlagProvider.SKYLARK_IDENTIFIER)) .nonconfigurable(NONCONFIGURABLE_ATTRIBUTE_REASON)) .setIsConfigMatcherForConfigSettingOnly() - .setOptionReferenceFunctionForConfigSettingOnly(CONFIG_SETTING_OPTION_REFERENCE) + .setOptionReferenceFunctionForConfigSettingOnly( + rule -> + NonconfigurableAttributeMapper.of(rule) + .get(SETTINGS_ATTRIBUTE, Type.STRING_DICT) + .keySet()) .build(); } diff --git a/src/main/java/com/google/devtools/build/lib/rules/config/ConfigSetting.java b/src/main/java/com/google/devtools/build/lib/rules/config/ConfigSetting.java index ae98678b71..82bc85c750 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/config/ConfigSetting.java +++ b/src/main/java/com/google/devtools/build/lib/rules/config/ConfigSetting.java @@ -142,11 +142,8 @@ public class ConfigSetting implements RuleConfiguredTargetFactory { continue; } - OptionsParser parser = parserCache.get(optionClass); - if (parser == null) { - parser = OptionsParser.newOptionsParser(optionClass); - parserCache.put(optionClass, parser); - } + OptionsParser parser = + parserCache.computeIfAbsent(optionClass, OptionsParser::newOptionsParser); try { parser.parse("--" + optionName + "=" + expectedRawValue); diff --git a/src/main/java/com/google/devtools/build/lib/rules/cpp/CcLibrary.java b/src/main/java/com/google/devtools/build/lib/rules/cpp/CcLibrary.java index 86f3184349..7b7906a529 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/cpp/CcLibrary.java +++ b/src/main/java/com/google/devtools/build/lib/rules/cpp/CcLibrary.java @@ -14,7 +14,6 @@ package com.google.devtools.build.lib.rules.cpp; -import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.devtools.build.lib.actions.Artifact; @@ -236,15 +235,14 @@ public abstract class CcLibrary implements RuleConfiguredTargetFactory { helper.addStaticLibraries(alwayslinkLibrariesFromSrcs); helper.addPicStaticLibraries(picStaticLibrariesFromSrcs); helper.addPicStaticLibraries(picAlwayslinkLibrariesFromSrcs); - helper.addDynamicLibraries(Iterables.transform(precompiledFiles.getSharedLibraries(), - new Function<Artifact, LibraryToLink>() { - @Override - public LibraryToLink apply(Artifact library) { - return LinkerInputs.solibLibraryToLink( - common.getDynamicLibrarySymlink(library, true), library, - CcLinkingOutputs.libraryIdentifierOf(library)); - } - })); + helper.addDynamicLibraries( + Iterables.transform( + precompiledFiles.getSharedLibraries(), + library -> + LinkerInputs.solibLibraryToLink( + common.getDynamicLibrarySymlink(library, true), + library, + CcLinkingOutputs.libraryIdentifierOf(library)))); CcLibraryHelper.Info info = helper.build(); /* diff --git a/src/main/java/com/google/devtools/build/lib/rules/cpp/CcLibraryHelper.java b/src/main/java/com/google/devtools/build/lib/rules/cpp/CcLibraryHelper.java index ffdacd353d..3c7aa425c2 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/cpp/CcLibraryHelper.java +++ b/src/main/java/com/google/devtools/build/lib/rules/cpp/CcLibraryHelper.java @@ -14,8 +14,10 @@ package com.google.devtools.build.lib.rules.cpp; +import static java.util.stream.Collectors.joining; +import static java.util.stream.Collectors.toCollection; + import com.google.common.base.Function; -import com.google.common.base.Joiner; import com.google.common.base.Optional; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableList; @@ -24,6 +26,7 @@ import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSetMultimap; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; +import com.google.common.collect.Streams; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.analysis.AnalysisUtils; import com.google.devtools.build.lib.analysis.FileProvider; @@ -52,7 +55,6 @@ import com.google.devtools.build.lib.rules.cpp.Link.LinkTargetType; import com.google.devtools.build.lib.rules.cpp.Link.Staticness; import com.google.devtools.build.lib.rules.cpp.LinkerInputs.LibraryToLink; import com.google.devtools.build.lib.syntax.Type; -import com.google.devtools.build.lib.util.FileType; import com.google.devtools.build.lib.util.FileTypeSet; import com.google.devtools.build.lib.util.Pair; import com.google.devtools.build.lib.util.Preconditions; @@ -171,14 +173,10 @@ public final class CcLibraryHelper { /** Function for extracting module maps from CppCompilationDependencies. */ public static final Function<TransitiveInfoCollection, CppModuleMap> CPP_DEPS_TO_MODULES = - new Function<TransitiveInfoCollection, CppModuleMap>() { - @Override - @Nullable - public CppModuleMap apply(TransitiveInfoCollection dep) { + dep -> { CppCompilationContext context = dep.getProvider(CppCompilationContext.class); return context == null ? null : context.getCppModuleMap(); - } - }; + }; /** * Contains the providers as well as the compilation and linking outputs, and the compilation @@ -1004,15 +1002,17 @@ public final class CcLibraryHelper { LinkerInputs.toNonSolibArtifacts(linkedLibraryMap.get(matchingIdentifier)); ruleContext.ruleError( "Can't put " - + Joiner.on(", ") - .join(Iterables.transform(matchingInputLibs, FileType.TO_FILENAME)) + + Streams.stream(matchingInputLibs) + .map(Artifact::getFilename) + .collect(joining(", ")) + " into the srcs of a " + ruleContext.getRuleClassNameForLogging() + " with the same name (" + ruleContext.getRule().getName() + ") which also contains other code or objects to link; it shares a name with " - + Joiner.on(", ") - .join(Iterables.transform(matchingOutputLibs, FileType.TO_FILENAME)) + + Streams.stream(matchingOutputLibs) + .map(Artifact::getFilename) + .collect(joining(", ")) + " (output compiled and linked from the non-library sources of this rule), " + "which could cause confusion"); } @@ -1463,8 +1463,8 @@ public final class CcLibraryHelper { private Iterable<CppModuleMap> collectModuleMaps() { // Cpp module maps may be null for some rules. We filter the nulls out at the end. - List<CppModuleMap> result = new ArrayList<>(); - Iterables.addAll(result, Iterables.transform(deps, CPP_DEPS_TO_MODULES)); + List<CppModuleMap> result = + deps.stream().map(CPP_DEPS_TO_MODULES).collect(toCollection(ArrayList::new)); if (ruleContext.getRule().getAttributeDefinition(":stl") != null) { CppCompilationContext stl = ruleContext.getPrerequisite(":stl", Mode.TARGET, CppCompilationContext.class); diff --git a/src/main/java/com/google/devtools/build/lib/rules/cpp/CcLinkParams.java b/src/main/java/com/google/devtools/build/lib/rules/cpp/CcLinkParams.java index 9469a30bfe..4b9fcd7e8e 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/cpp/CcLinkParams.java +++ b/src/main/java/com/google/devtools/build/lib/rules/cpp/CcLinkParams.java @@ -27,7 +27,6 @@ import com.google.devtools.build.lib.collect.nestedset.Order; import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable; import com.google.devtools.build.lib.rules.cpp.LinkerInputs.LibraryToLink; import com.google.devtools.build.lib.util.Preconditions; - import java.util.Collection; import java.util.List; import java.util.Objects; @@ -90,13 +89,7 @@ public final class CcLinkParams { } public ImmutableList<String> flattenedLinkopts() { - return ImmutableList.copyOf(Iterables.concat(Iterables.transform(linkOpts, - new Function<LinkOptions, ImmutableList<String>>() { - @Override - public ImmutableList<String> apply(LinkOptions linkOptions) { - return linkOptions.get(); - } - }))); + return ImmutableList.copyOf(Iterables.concat(Iterables.transform(linkOpts, LinkOptions::get))); } /** diff --git a/src/main/java/com/google/devtools/build/lib/rules/cpp/CcLinkParamsProvider.java b/src/main/java/com/google/devtools/build/lib/rules/cpp/CcLinkParamsProvider.java index 0f103b7eb6..76a6c768f3 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/cpp/CcLinkParamsProvider.java +++ b/src/main/java/com/google/devtools/build/lib/rules/cpp/CcLinkParamsProvider.java @@ -31,23 +31,20 @@ public final class CcLinkParamsProvider extends SkylarkClassObject public static final ClassObjectConstructor CC_LINK_PARAMS = new NativeClassObjectConstructor("link_params") { }; public static final Function<TransitiveInfoCollection, CcLinkParamsStore> TO_LINK_PARAMS = - new Function<TransitiveInfoCollection, CcLinkParamsStore>() { - @Override - public CcLinkParamsStore apply(TransitiveInfoCollection input) { + input -> { - // Try native first... - CcLinkParamsProvider provider = input.getProvider(CcLinkParamsProvider.class); - if (provider != null) { - return provider.getCcLinkParamsStore(); - } + // Try native first... + CcLinkParamsProvider provider = input.getProvider(CcLinkParamsProvider.class); + if (provider != null) { + return provider.getCcLinkParamsStore(); + } - // ... then try Skylark. - provider = (CcLinkParamsProvider) input.get(CC_LINK_PARAMS.getKey()); - if (provider != null) { - return provider.getCcLinkParamsStore(); - } - return null; + // ... then try Skylark. + provider = (CcLinkParamsProvider) input.get(CC_LINK_PARAMS.getKey()); + if (provider != null) { + return provider.getCcLinkParamsStore(); } + return null; }; private final CcLinkParamsStoreImpl store; diff --git a/src/main/java/com/google/devtools/build/lib/rules/cpp/CcSpecificLinkParamsProvider.java b/src/main/java/com/google/devtools/build/lib/rules/cpp/CcSpecificLinkParamsProvider.java index e43154fb91..6afb548bb0 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/cpp/CcSpecificLinkParamsProvider.java +++ b/src/main/java/com/google/devtools/build/lib/rules/cpp/CcSpecificLinkParamsProvider.java @@ -37,12 +37,9 @@ public final class CcSpecificLinkParamsProvider implements TransitiveInfoProvide } public static final Function<TransitiveInfoCollection, CcLinkParamsStore> TO_LINK_PARAMS = - new Function<TransitiveInfoCollection, CcLinkParamsStore>() { - @Override - public CcLinkParamsStore apply(TransitiveInfoCollection input) { - CcSpecificLinkParamsProvider provider = input.getProvider( - CcSpecificLinkParamsProvider.class); - return provider == null ? null : provider.getLinkParams(); - } + input -> { + CcSpecificLinkParamsProvider provider = + input.getProvider(CcSpecificLinkParamsProvider.class); + return provider == null ? null : provider.getLinkParams(); }; } diff --git a/src/main/java/com/google/devtools/build/lib/rules/cpp/CcToolchainFeatures.java b/src/main/java/com/google/devtools/build/lib/rules/cpp/CcToolchainFeatures.java index 67226586a6..1eee0802c4 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/cpp/CcToolchainFeatures.java +++ b/src/main/java/com/google/devtools/build/lib/rules/cpp/CcToolchainFeatures.java @@ -18,7 +18,6 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Joiner; import com.google.common.base.Optional; import com.google.common.base.Preconditions; -import com.google.common.base.Predicate; import com.google.common.base.Strings; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; @@ -762,14 +761,9 @@ public class CcToolchainFeatures implements Serializable { Optional<CToolchain.Tool> tool = Iterables.tryFind( tools, - new Predicate<CToolchain.Tool>() { - // We select the first listed tool for which all specified features are activated - // in this configuration - @Override - public boolean apply(CToolchain.Tool input) { - Collection<String> featureNamesForTool = input.getWithFeature().getFeatureList(); - return enabledFeatureNames.containsAll(featureNamesForTool); - } + input -> { + Collection<String> featureNamesForTool = input.getWithFeature().getFeatureList(); + return enabledFeatureNames.containsAll(featureNamesForTool); }); if (tool.isPresent()) { return new Tool(tool.get()); diff --git a/src/main/java/com/google/devtools/build/lib/rules/cpp/CompileCommandLine.java b/src/main/java/com/google/devtools/build/lib/rules/cpp/CompileCommandLine.java index f8c39402eb..2df5412218 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/cpp/CompileCommandLine.java +++ b/src/main/java/com/google/devtools/build/lib/rules/cpp/CompileCommandLine.java @@ -15,7 +15,6 @@ package com.google.devtools.build.lib.rules.cpp; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.analysis.config.PerLabelOptions; import com.google.devtools.build.lib.cmdline.Label; @@ -197,7 +196,7 @@ public final class CompileCommandLine { // For each option in 'in', add it to 'out' unless it is matched by the 'coptsFilter' regexp. private void addFilteredOptions(List<String> out, List<String> in) { - Iterables.addAll(out, Iterables.filter(in, coptsFilter)); + in.stream().filter(coptsFilter).forEachOrdered(out::add); } public Artifact getSourceFile() { diff --git a/src/main/java/com/google/devtools/build/lib/rules/cpp/CppCompileActionBuilder.java b/src/main/java/com/google/devtools/build/lib/rules/cpp/CppCompileActionBuilder.java index c86348a100..f5d21f486d 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/cpp/CppCompileActionBuilder.java +++ b/src/main/java/com/google/devtools/build/lib/rules/cpp/CppCompileActionBuilder.java @@ -222,17 +222,14 @@ public class CppCompileActionBuilder { if (finalPatterns.isEmpty()) { return Predicates.alwaysTrue(); } else { - return new Predicate<String>() { - @Override - public boolean apply(String option) { - for (Pattern pattern : finalPatterns) { - if (pattern.matcher(option).matches()) { - return false; - } + return option -> { + for (Pattern pattern : finalPatterns) { + if (pattern.matcher(option).matches()) { + return false; } - - return true; } + + return true; }; } } diff --git a/src/main/java/com/google/devtools/build/lib/rules/cpp/CppConfiguration.java b/src/main/java/com/google/devtools/build/lib/rules/cpp/CppConfiguration.java index b66c6904e4..5468a1607e 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/cpp/CppConfiguration.java +++ b/src/main/java/com/google/devtools/build/lib/rules/cpp/CppConfiguration.java @@ -15,7 +15,6 @@ package com.google.devtools.build.lib.rules.cpp; import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Predicate; import com.google.common.base.Verify; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ImmutableList; @@ -52,7 +51,6 @@ import com.google.devtools.build.lib.vfs.Path; import com.google.devtools.build.lib.vfs.PathFragment; import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig; import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CToolchain; -import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CToolchain.ActionConfig; import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CToolchain.ArtifactNamePattern; import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.LinkingModeFlags; import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.LipoMode; @@ -405,22 +403,19 @@ public class CppConfiguration extends BuildConfiguration.Fragment { Iterable<Tool> neededTools = Iterables.filter( EnumSet.allOf(Tool.class), - new Predicate<Tool>() { - @Override - public boolean apply(Tool tool) { - if (tool == Tool.DWP) { - // When fission is unsupported, don't check for the dwp tool. - return supportsFission(); - } else if (tool == Tool.LLVM_PROFDATA) { - // TODO(tmsriram): Fix this to check if this is a llvm crosstool - // and return true. This needs changes to crosstool_config.proto. - return false; - } else if (tool == Tool.GCOVTOOL || tool == Tool.OBJCOPY) { - // gcov-tool and objcopy are optional, don't check whether they're present - return false; - } else { - return true; - } + tool -> { + if (tool == Tool.DWP) { + // When fission is unsupported, don't check for the dwp tool. + return supportsFission(); + } else if (tool == Tool.LLVM_PROFDATA) { + // TODO(tmsriram): Fix this to check if this is a llvm crosstool + // and return true. This needs changes to crosstool_config.proto. + return false; + } else if (tool == Tool.GCOVTOOL || tool == Tool.OBJCOPY) { + // gcov-tool and objcopy are optional, don't check whether they're present + return false; + } else { + return true; } }); for (Tool tool : neededTools) { @@ -600,17 +595,10 @@ public class CppConfiguration extends BuildConfiguration.Fragment { } private static boolean actionsAreConfigured(CToolchain toolchain) { - return Iterables.any( - toolchain.getActionConfigList(), - new Predicate<ActionConfig>() { - @Override - public boolean apply(@Nullable ActionConfig actionConfig) { - // We cannot assume actions are configured just by presence of any action_config. Some - // crosstools specify unrelated action_configs (e.g. clif_match), but C/C++ part is - // in fact not configured. - return actionConfig.getActionName().contains("c++"); - } - }); + return toolchain + .getActionConfigList() + .stream() + .anyMatch(actionConfig -> actionConfig.getActionName().contains("c++")); } // TODO(bazel-team): Remove this once bazel supports all crosstool flags through diff --git a/src/main/java/com/google/devtools/build/lib/rules/cpp/CppFileTypes.java b/src/main/java/com/google/devtools/build/lib/rules/cpp/CppFileTypes.java index cdda812667..3c7f07f6df 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/cpp/CppFileTypes.java +++ b/src/main/java/com/google/devtools/build/lib/rules/cpp/CppFileTypes.java @@ -169,20 +169,17 @@ public final class CppFileTypes { /** Predicate that matches all artifacts that can be used in an objc Clang module map. */ public static final Predicate<Artifact> MODULE_MAP_HEADER = - new Predicate<Artifact>() { - @Override - public boolean apply(Artifact artifact) { - if (artifact.isTreeArtifact()) { - // Tree artifact is basically a directory, which does not have any information about - // the contained files and their extensions. Here we assume the passed in tree artifact - // contains proper header files with .h extension. - return true; - } else { - // The current clang (clang-600.0.57) on Darwin doesn't support 'textual', so we can't - // have '.inc' files in the module map (since they're implictly textual). - // TODO(bazel-team): Use HEADERS file type once clang-700 is the base clang we support. - return artifact.getFilename().endsWith(".h"); - } + artifact -> { + if (artifact.isTreeArtifact()) { + // Tree artifact is basically a directory, which does not have any information about + // the contained files and their extensions. Here we assume the passed in tree artifact + // contains proper header files with .h extension. + return true; + } else { + // The current clang (clang-600.0.57) on Darwin doesn't support 'textual', so we can't + // have '.inc' files in the module map (since they're implictly textual). + // TODO(bazel-team): Use HEADERS file type once clang-700 is the base clang we support. + return artifact.getFilename().endsWith(".h"); } }; diff --git a/src/main/java/com/google/devtools/build/lib/rules/cpp/CppModuleMapAction.java b/src/main/java/com/google/devtools/build/lib/rules/cpp/CppModuleMapAction.java index 137e22c871..8df91f4995 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/cpp/CppModuleMapAction.java +++ b/src/main/java/com/google/devtools/build/lib/rules/cpp/CppModuleMapAction.java @@ -77,11 +77,11 @@ public final class CppModuleMapAction extends AbstractFileWriteAction { super( owner, ImmutableList.<Artifact>builder() - .addAll(Iterables.filter(privateHeaders, Artifact.IS_TREE_ARTIFACT)) - .addAll(Iterables.filter(publicHeaders, Artifact.IS_TREE_ARTIFACT)) + .addAll(Iterables.filter(privateHeaders, Artifact::isTreeArtifact)) + .addAll(Iterables.filter(publicHeaders, Artifact::isTreeArtifact)) .build(), cppModuleMap.getArtifact(), - /*makeExecutable=*/false); + /*makeExecutable=*/ false); this.cppModuleMap = cppModuleMap; this.moduleMapHomeIsCwd = moduleMapHomeIsCwd; this.privateHeaders = ImmutableList.copyOf(privateHeaders); diff --git a/src/main/java/com/google/devtools/build/lib/rules/cpp/CppRunfilesProvider.java b/src/main/java/com/google/devtools/build/lib/rules/cpp/CppRunfilesProvider.java index 43c13ac5f5..30f7bc9e11 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/cpp/CppRunfilesProvider.java +++ b/src/main/java/com/google/devtools/build/lib/rules/cpp/CppRunfilesProvider.java @@ -45,33 +45,23 @@ public final class CppRunfilesProvider implements TransitiveInfoProvider { } /** - * Returns a function that gets the static C++ runfiles from a {@link TransitiveInfoCollection} - * or the empty runfiles instance if it does not contain that provider. + * Returns a function that gets the static C++ runfiles from a {@link TransitiveInfoCollection} or + * the empty runfiles instance if it does not contain that provider. */ public static final Function<TransitiveInfoCollection, Runfiles> STATIC_RUNFILES = - new Function<TransitiveInfoCollection, Runfiles>() { - @Override - public Runfiles apply(TransitiveInfoCollection input) { - CppRunfilesProvider provider = input.getProvider(CppRunfilesProvider.class); - return provider == null - ? Runfiles.EMPTY - : provider.getStaticRunfiles(); - } + input -> { + CppRunfilesProvider provider = input.getProvider(CppRunfilesProvider.class); + return provider == null ? Runfiles.EMPTY : provider.getStaticRunfiles(); }; /** - * Returns a function that gets the shared C++ runfiles from a {@link TransitiveInfoCollection} - * or the empty runfiles instance if it does not contain that provider. + * Returns a function that gets the shared C++ runfiles from a {@link TransitiveInfoCollection} or + * the empty runfiles instance if it does not contain that provider. */ public static final Function<TransitiveInfoCollection, Runfiles> SHARED_RUNFILES = - new Function<TransitiveInfoCollection, Runfiles>() { - @Override - public Runfiles apply(TransitiveInfoCollection input) { - CppRunfilesProvider provider = input.getProvider(CppRunfilesProvider.class); - return provider == null - ? Runfiles.EMPTY - : provider.getSharedRunfiles(); - } + input -> { + CppRunfilesProvider provider = input.getProvider(CppRunfilesProvider.class); + return provider == null ? Runfiles.EMPTY : provider.getSharedRunfiles(); }; /** diff --git a/src/main/java/com/google/devtools/build/lib/rules/cpp/CrosstoolConfigurationLoader.java b/src/main/java/com/google/devtools/build/lib/rules/cpp/CrosstoolConfigurationLoader.java index 29ace2f135..460dca7136 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/cpp/CrosstoolConfigurationLoader.java +++ b/src/main/java/com/google/devtools/build/lib/rules/cpp/CrosstoolConfigurationLoader.java @@ -45,7 +45,6 @@ import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; -import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import javax.annotation.Nullable; @@ -251,12 +250,9 @@ public class CrosstoolConfigurationLoader { String md5 = BaseEncoding.base16().lowerCase().encode(finalProto.getMd5()); CrosstoolConfig.CrosstoolRelease release; try { - release = crosstoolReleaseCache.get(md5, new Callable<CrosstoolRelease>() { - @Override - public CrosstoolRelease call() throws Exception { - return toReleaseConfiguration(finalProto.getName(), finalProto.getContents()); - } - }); + release = + crosstoolReleaseCache.get( + md5, () -> toReleaseConfiguration(finalProto.getName(), finalProto.getContents())); } catch (ExecutionException e) { throw new InvalidConfigurationException(e); } diff --git a/src/main/java/com/google/devtools/build/lib/rules/cpp/ExtraLinkTimeLibraries.java b/src/main/java/com/google/devtools/build/lib/rules/cpp/ExtraLinkTimeLibraries.java index d596ce0156..4a5c725fa5 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/cpp/ExtraLinkTimeLibraries.java +++ b/src/main/java/com/google/devtools/build/lib/rules/cpp/ExtraLinkTimeLibraries.java @@ -15,7 +15,6 @@ package com.google.devtools.build.lib.rules.cpp; import com.google.common.collect.Lists; - import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; @@ -79,9 +78,7 @@ public final class ExtraLinkTimeLibraries { public final Builder addTransitive(ExtraLinkTimeLibraries dep) { for (ExtraLinkTimeLibrary depLibrary : dep.getExtraLibraries()) { Class<? extends ExtraLinkTimeLibrary> c = depLibrary.getClass(); - if (!libraries.containsKey(c)) { - libraries.put(c, depLibrary.getBuilder()); - } + libraries.computeIfAbsent(c, k -> depLibrary.getBuilder()); libraries.get(c).addTransitive(depLibrary); } return this; @@ -92,9 +89,7 @@ public final class ExtraLinkTimeLibraries { */ public final Builder add(ExtraLinkTimeLibrary b) { Class<? extends ExtraLinkTimeLibrary> c = b.getClass(); - if (!libraries.containsKey(c)) { - libraries.put(c, b.getBuilder()); - } + libraries.computeIfAbsent(c, k -> b.getBuilder()); libraries.get(c).addTransitive(b); return this; } diff --git a/src/main/java/com/google/devtools/build/lib/rules/cpp/FakeCppCompileAction.java b/src/main/java/com/google/devtools/build/lib/rules/cpp/FakeCppCompileAction.java index 70a9dd184d..a8c0160791 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/cpp/FakeCppCompileAction.java +++ b/src/main/java/com/google/devtools/build/lib/rules/cpp/FakeCppCompileAction.java @@ -15,13 +15,11 @@ package com.google.devtools.build.lib.rules.cpp; import static java.nio.charset.StandardCharsets.ISO_8859_1; +import static java.util.stream.Collectors.joining; -import com.google.common.base.Function; -import com.google.common.base.Joiner; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Iterables; import com.google.devtools.build.lib.actions.ActionExecutionContext; import com.google.devtools.build.lib.actions.ActionExecutionException; import com.google.devtools.build.lib.actions.ActionOwner; @@ -207,24 +205,26 @@ public class FakeCppCompileAction extends CppCompileAction { // runfiles directory (where writing is forbidden), we patch the command // line to write to $TEST_TMPDIR instead. final String outputPrefix = "$TEST_TMPDIR/"; - String argv = Joiner.on(' ').join( - Iterables.transform(getArgv(outputFile.getExecPath()), new Function<String, String>() { - @Override - public String apply(String input) { - String result = ShellEscaper.escapeString(input); - // Once -c and -o options are added into action_config, the argument of - // getArgv(outputFile.getExecPath()) won't be used anymore. There will always be - // -c <tempOutputFile>, but here it has to be outputFile, so we replace it. - if (input.equals(tempOutputFile.getPathString())) { - result = outputPrefix + ShellEscaper.escapeString(outputFile.getExecPathString()); - } - if (input.equals(outputFile.getExecPathString()) - || input.equals(getDotdFile().getSafeExecPath().getPathString())) { - result = outputPrefix + ShellEscaper.escapeString(input); - } - return result; - } - })); + String argv = + getArgv(outputFile.getExecPath()) + .stream() + .map( + input -> { + String result = ShellEscaper.escapeString(input); + // Once -c and -o options are added into action_config, the argument of + // getArgv(outputFile.getExecPath()) won't be used anymore. There will always be + // -c <tempOutputFile>, but here it has to be outputFile, so we replace it. + if (input.equals(tempOutputFile.getPathString())) { + result = + outputPrefix + ShellEscaper.escapeString(outputFile.getExecPathString()); + } + if (input.equals(outputFile.getExecPathString()) + || input.equals(getDotdFile().getSafeExecPath().getPathString())) { + result = outputPrefix + ShellEscaper.escapeString(input); + } + return result; + }) + .collect(joining(" ")); // Write the command needed to build the real .o file to the fake .o file. // Generate a command to ensure that the output directory exists; otherwise diff --git a/src/main/java/com/google/devtools/build/lib/rules/cpp/LinkCommandLine.java b/src/main/java/com/google/devtools/build/lib/rules/cpp/LinkCommandLine.java index b279440b7f..a904db923b 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/cpp/LinkCommandLine.java +++ b/src/main/java/com/google/devtools/build/lib/rules/cpp/LinkCommandLine.java @@ -657,8 +657,9 @@ public final class LinkCommandLine extends CommandLine { if (linkstampCompileOptions.isEmpty()) { actualLinkstampCompileOptions = DEFAULT_LINKSTAMP_OPTIONS; } else { - actualLinkstampCompileOptions = ImmutableList.copyOf( - Iterables.concat(DEFAULT_LINKSTAMP_OPTIONS, linkstampCompileOptions)); + actualLinkstampCompileOptions = + ImmutableList.copyOf( + Iterables.concat(DEFAULT_LINKSTAMP_OPTIONS, linkstampCompileOptions)); } if (toolchain == null) { diff --git a/src/main/java/com/google/devtools/build/lib/rules/cpp/LinkerInputs.java b/src/main/java/com/google/devtools/build/lib/rules/cpp/LinkerInputs.java index fd3dce6dee..bee6f9266c 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/cpp/LinkerInputs.java +++ b/src/main/java/com/google/devtools/build/lib/rules/cpp/LinkerInputs.java @@ -14,7 +14,6 @@ package com.google.devtools.build.lib.rules.cpp; -import com.google.common.base.Function; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import com.google.devtools.build.lib.actions.Artifact; @@ -352,12 +351,7 @@ public abstract class LinkerInputs { */ public static Iterable<LinkerInput> simpleLinkerInputs(Iterable<Artifact> input, final ArtifactCategory category) { - return Iterables.transform(input, new Function<Artifact, LinkerInput>() { - @Override - public LinkerInput apply(Artifact artifact) { - return simpleLinkerInput(artifact, category); - } - }); + return Iterables.transform(input, artifact -> simpleLinkerInput(artifact, category)); } /** @@ -382,12 +376,7 @@ public abstract class LinkerInputs { */ public static Iterable<LibraryToLink> opaqueLibrariesToLink( final ArtifactCategory category, Iterable<Artifact> input) { - return Iterables.transform(input, new Function<Artifact, LibraryToLink>() { - @Override - public LibraryToLink apply(Artifact artifact) { - return precompiledLibraryToLink(artifact, category); - } - }); + return Iterables.transform(input, artifact -> precompiledLibraryToLink(artifact, category)); } /** @@ -429,27 +418,14 @@ public abstract class LinkerInputs { library, category, libraryIdentifier, objectFiles, ltoBitcodeFiles); } - private static final Function<LibraryToLink, Artifact> LIBRARY_TO_NON_SOLIB = - new Function<LibraryToLink, Artifact>() { - @Override - public Artifact apply(LibraryToLink input) { - return input.getOriginalLibraryArtifact(); - } - }; - public static Iterable<Artifact> toNonSolibArtifacts(Iterable<LibraryToLink> libraries) { - return Iterables.transform(libraries, LIBRARY_TO_NON_SOLIB); + return Iterables.transform(libraries, LibraryToLink::getOriginalLibraryArtifact); } /** * Returns the linker input artifacts from a collection of {@link LinkerInput} objects. */ public static Iterable<Artifact> toLibraryArtifacts(Iterable<? extends LinkerInput> artifacts) { - return Iterables.transform(artifacts, new Function<LinkerInput, Artifact>() { - @Override - public Artifact apply(LinkerInput input) { - return input.getArtifact(); - } - }); + return Iterables.transform(artifacts, LinkerInput::getArtifact); } } diff --git a/src/main/java/com/google/devtools/build/lib/rules/cpp/PrecompiledFiles.java b/src/main/java/com/google/devtools/build/lib/rules/cpp/PrecompiledFiles.java index 6f9e6f0c94..8dbedeae85 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/cpp/PrecompiledFiles.java +++ b/src/main/java/com/google/devtools/build/lib/rules/cpp/PrecompiledFiles.java @@ -13,7 +13,6 @@ // limitations under the License. package com.google.devtools.build.lib.rules.cpp; -import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.devtools.build.lib.actions.Artifact; @@ -76,21 +75,20 @@ public final class PrecompiledFiles { public Iterable<Artifact> getObjectFiles(final boolean usePic) { if (usePic) { - return Iterables.filter(files, new Predicate<Artifact>() { - @Override - public boolean apply(Artifact artifact) { - String filename = artifact.getExecPathString(); + return Iterables.filter( + files, + artifact -> { + String filename = artifact.getExecPathString(); - // For compatibility with existing BUILD files, any ".o" files listed - // in srcs are assumed to be position-independent code, or - // at least suitable for inclusion in shared libraries, unless they - // end with ".nopic.o". (The ".nopic.o" extension is an undocumented - // feature to give users at least some control over this.) Note that - // some target platforms do not require shared library code to be PIC. - return CppFileTypes.PIC_OBJECT_FILE.matches(filename) - || (CppFileTypes.OBJECT_FILE.matches(filename) && !filename.endsWith(".nopic.o")); - } - }); + // For compatibility with existing BUILD files, any ".o" files listed + // in srcs are assumed to be position-independent code, or + // at least suitable for inclusion in shared libraries, unless they + // end with ".nopic.o". (The ".nopic.o" extension is an undocumented + // feature to give users at least some control over this.) Note that + // some target platforms do not require shared library code to be PIC. + return CppFileTypes.PIC_OBJECT_FILE.matches(filename) + || (CppFileTypes.OBJECT_FILE.matches(filename) && !filename.endsWith(".nopic.o")); + }); } else { return FileType.filter(files, CppFileTypes.OBJECT_FILE); } diff --git a/src/main/java/com/google/devtools/build/lib/rules/cpp/UmbrellaHeaderAction.java b/src/main/java/com/google/devtools/build/lib/rules/cpp/UmbrellaHeaderAction.java index 14c3a0cfaa..eada861fc1 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/cpp/UmbrellaHeaderAction.java +++ b/src/main/java/com/google/devtools/build/lib/rules/cpp/UmbrellaHeaderAction.java @@ -13,8 +13,10 @@ // limitations under the License. package com.google.devtools.build.lib.rules.cpp; +import static com.google.common.collect.ImmutableList.toImmutableList; + import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; +import com.google.common.collect.Streams; import com.google.devtools.build.lib.actions.ActionExecutionContext; import com.google.devtools.build.lib.actions.ActionOwner; import com.google.devtools.build.lib.actions.Artifact; @@ -50,9 +52,9 @@ public final class UmbrellaHeaderAction extends AbstractFileWriteAction { Iterable<PathFragment> additionalExportedHeaders) { super( owner, - ImmutableList.copyOf(Iterables.filter(publicHeaders, Artifact.IS_TREE_ARTIFACT)), + Streams.stream(publicHeaders).filter(Artifact::isTreeArtifact).collect(toImmutableList()), umbrellaHeader, - /*makeExecutable=*/false); + /*makeExecutable=*/ false); this.umbrellaHeader = umbrellaHeader; this.publicHeaders = ImmutableList.copyOf(publicHeaders); this.additionalExportedHeaders = ImmutableList.copyOf(additionalExportedHeaders); diff --git a/src/main/java/com/google/devtools/build/lib/rules/cpp/proto/CcProtoLibraryRule.java b/src/main/java/com/google/devtools/build/lib/rules/cpp/proto/CcProtoLibraryRule.java index 065f722565..dd02eaaadf 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/cpp/proto/CcProtoLibraryRule.java +++ b/src/main/java/com/google/devtools/build/lib/rules/cpp/proto/CcProtoLibraryRule.java @@ -25,22 +25,10 @@ import com.google.devtools.build.lib.analysis.RuleDefinitionEnvironment; import com.google.devtools.build.lib.packages.AspectParameters; import com.google.devtools.build.lib.packages.Rule; import com.google.devtools.build.lib.packages.RuleClass; -import javax.annotation.Nullable; /** Declaration part of cc_proto_library. */ public class CcProtoLibraryRule implements RuleDefinition { - private static final Function<Rule, AspectParameters> ASPECT_PARAMETERS = - new Function<Rule, AspectParameters>() { - @Nullable - @Override - public AspectParameters apply(@Nullable Rule rule) { - return new AspectParameters.Builder() - .addAttribute(INJECTING_RULE_KIND_PARAMETER_KEY, "cc_proto_library") - .build(); - } - }; - private final CcProtoAspect ccProtoAspect; public CcProtoLibraryRule(CcProtoAspect ccProtoAspect) { @@ -49,6 +37,12 @@ public class CcProtoLibraryRule implements RuleDefinition { @Override public RuleClass build(RuleClass.Builder builder, RuleDefinitionEnvironment environment) { + Function<Rule, AspectParameters> aspectParameters = + rule -> + new AspectParameters.Builder() + .addAttribute(INJECTING_RULE_KIND_PARAMETER_KEY, "cc_proto_library") + .build(); + return builder /* <!-- #BLAZE_RULE(cc_proto_library).ATTRIBUTE(deps) --> The list of <a href="protocol-buffer.html#proto_library"><code>proto_library</code></a> @@ -58,7 +52,7 @@ public class CcProtoLibraryRule implements RuleDefinition { attr("deps", LABEL_LIST) .allowedRuleClasses("proto_library") .allowedFileTypes() - .aspect(ccProtoAspect, ASPECT_PARAMETERS)) + .aspect(ccProtoAspect, aspectParameters)) .build(); } diff --git a/src/main/java/com/google/devtools/build/lib/rules/java/DeployArchiveBuilder.java b/src/main/java/com/google/devtools/build/lib/rules/java/DeployArchiveBuilder.java index 29379dcbf0..e110a34174 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/java/DeployArchiveBuilder.java +++ b/src/main/java/com/google/devtools/build/lib/rules/java/DeployArchiveBuilder.java @@ -13,10 +13,13 @@ // limitations under the License. package com.google.devtools.build.lib.rules.java; +import static com.google.common.collect.ImmutableList.toImmutableList; + import com.google.common.base.Function; import com.google.common.base.Functions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; +import com.google.common.collect.Streams; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.actions.ExecutionRequirements; import com.google.devtools.build.lib.actions.ParameterFile.ParameterFileType; @@ -209,8 +212,9 @@ public class DeployArchiveBuilder { Function<Artifact, Artifact> derivedJarFunction) { IterablesChain.Builder<Artifact> inputs = IterablesChain.builder(); inputs.add( - ImmutableList.copyOf( - Iterables.transform(attributes.getRuntimeClassPathForArchive(), derivedJarFunction))); + Streams.stream(attributes.getRuntimeClassPathForArchive()) + .map(derivedJarFunction) + .collect(toImmutableList())); // TODO(bazel-team): Remove? Resources not used as input to singlejar action inputs.add(ImmutableList.copyOf(attributes.getResources().values())); inputs.add(attributes.getClassPathResources()); @@ -237,7 +241,7 @@ public class DeployArchiveBuilder { IterablesChain.Builder<Artifact> inputs = IterablesChain.builder(); inputs.add(getArchiveInputs(attributes, derivedJars)); - inputs.add(ImmutableList.copyOf(Iterables.transform(runtimeJars, derivedJars))); + inputs.add(Streams.stream(runtimeJars).map(derivedJars).collect(toImmutableList())); if (runfilesMiddleman != null) { inputs.addElement(runfilesMiddleman); } diff --git a/src/main/java/com/google/devtools/build/lib/rules/java/JavaCcLinkParamsProvider.java b/src/main/java/com/google/devtools/build/lib/rules/java/JavaCcLinkParamsProvider.java index 7108e3444e..1c096be9ea 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/java/JavaCcLinkParamsProvider.java +++ b/src/main/java/com/google/devtools/build/lib/rules/java/JavaCcLinkParamsProvider.java @@ -37,12 +37,8 @@ public final class JavaCcLinkParamsProvider implements TransitiveInfoProvider { } public static final Function<TransitiveInfoCollection, CcLinkParamsStore> TO_LINK_PARAMS = - new Function<TransitiveInfoCollection, CcLinkParamsStore>() { - @Override - public CcLinkParamsStore apply(TransitiveInfoCollection input) { - JavaCcLinkParamsProvider provider = input.getProvider( - JavaCcLinkParamsProvider.class); - return provider == null ? null : provider.getLinkParams(); - } + input -> { + JavaCcLinkParamsProvider provider = input.getProvider(JavaCcLinkParamsProvider.class); + return provider == null ? null : provider.getLinkParams(); }; } diff --git a/src/main/java/com/google/devtools/build/lib/rules/java/JavaCommon.java b/src/main/java/com/google/devtools/build/lib/rules/java/JavaCommon.java index 082552b9d4..293208c69c 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/java/JavaCommon.java +++ b/src/main/java/com/google/devtools/build/lib/rules/java/JavaCommon.java @@ -13,11 +13,13 @@ // limitations under the License. package com.google.devtools.build.lib.rules.java; -import com.google.common.base.Function; +import static com.google.common.collect.ImmutableList.toImmutableList; + import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList.Builder; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; +import com.google.common.collect.Streams; import com.google.devtools.build.lib.actions.ActionAnalysisMetadata; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.analysis.AnalysisEnvironment; @@ -66,14 +68,6 @@ import javax.annotation.Nullable; * A helper class to create configured targets for Java rules. */ public class JavaCommon { - private static final Function<TransitiveInfoCollection, Label> GET_COLLECTION_LABEL = - new Function<TransitiveInfoCollection, Label>() { - @Override - public Label apply(TransitiveInfoCollection collection) { - return collection.getLabel(); - } - }; - public static final InstrumentationSpec JAVA_COLLECTION_SPEC = new InstrumentationSpec( FileTypeSet.of(JavaSemantics.JAVA_SOURCE)) .withSourceAttributes("srcs") @@ -436,7 +430,7 @@ public class JavaCommon { NestedSetBuilder<Label> builder = NestedSetBuilder.stableOrder(); List<TransitiveInfoCollection> currentRuleExports = getExports(ruleContext); - builder.addAll(Iterables.transform(currentRuleExports, GET_COLLECTION_LABEL)); + builder.addAll(Iterables.transform(currentRuleExports, TransitiveInfoCollection::getLabel)); for (TransitiveInfoCollection dep : currentRuleExports) { JavaExportsProvider exportsProvider = dep.getProvider(JavaExportsProvider.class); @@ -464,10 +458,11 @@ public class JavaCommon { } private ImmutableList<String> computeJavacOpts(Iterable<String> extraJavacOpts) { - return ImmutableList.copyOf(Iterables.concat( - JavaToolchainProvider.fromRuleContext(ruleContext).getJavacOptions(), - extraJavacOpts, - ruleContext.getTokenizedStringListAttr("javacopts"))); + return Streams.concat( + JavaToolchainProvider.fromRuleContext(ruleContext).getJavacOptions().stream(), + Streams.stream(extraJavacOpts), + ruleContext.getTokenizedStringListAttr("javacopts").stream()) + .collect(toImmutableList()); } /** diff --git a/src/main/java/com/google/devtools/build/lib/rules/java/JavaRunfilesProvider.java b/src/main/java/com/google/devtools/build/lib/rules/java/JavaRunfilesProvider.java index 6b064d1aa3..67291a5283 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/java/JavaRunfilesProvider.java +++ b/src/main/java/com/google/devtools/build/lib/rules/java/JavaRunfilesProvider.java @@ -36,18 +36,12 @@ public final class JavaRunfilesProvider implements TransitiveInfoProvider { } /** - * Returns a function that gets the Java runfiles from a {@link TransitiveInfoCollection} or - * the empty runfiles instance if it does not contain that provider. + * Returns a function that gets the Java runfiles from a {@link TransitiveInfoCollection} or the + * empty runfiles instance if it does not contain that provider. */ public static final Function<TransitiveInfoCollection, Runfiles> TO_RUNFILES = - new Function<TransitiveInfoCollection, Runfiles>() { - @Override - public Runfiles apply(TransitiveInfoCollection input) { - JavaRunfilesProvider provider = - JavaProvider.getProvider(JavaRunfilesProvider.class, input); - return provider == null - ? Runfiles.EMPTY - : provider.getRunfiles(); - } + (TransitiveInfoCollection input) -> { + JavaRunfilesProvider provider = JavaProvider.getProvider(JavaRunfilesProvider.class, input); + return provider == null ? Runfiles.EMPTY : provider.getRunfiles(); }; } diff --git a/src/main/java/com/google/devtools/build/lib/rules/java/ResourceJarActionBuilder.java b/src/main/java/com/google/devtools/build/lib/rules/java/ResourceJarActionBuilder.java index a4e707e067..28c0709cfc 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/java/ResourceJarActionBuilder.java +++ b/src/main/java/com/google/devtools/build/lib/rules/java/ResourceJarActionBuilder.java @@ -19,6 +19,7 @@ import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; +import com.google.common.collect.Streams; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.actions.ParameterFile.ParameterFileType; import com.google.devtools.build.lib.analysis.RuleConfiguredTarget.Mode; @@ -145,7 +146,7 @@ public class ResourceJarActionBuilder { } boolean sizeGreaterThanOrEqual(Iterable<?> elements, int size) { - return Iterables.size(Iterables.limit(elements, size)) == size; + return Streams.stream(elements).limit(size).count() == size; } private static void addAsResourcePrefixedExecPath( diff --git a/src/main/java/com/google/devtools/build/lib/rules/objc/AppleDebugOutputsProvider.java b/src/main/java/com/google/devtools/build/lib/rules/objc/AppleDebugOutputsProvider.java index b2cc573f2e..eadabb9c57 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/objc/AppleDebugOutputsProvider.java +++ b/src/main/java/com/google/devtools/build/lib/rules/objc/AppleDebugOutputsProvider.java @@ -105,9 +105,7 @@ public final class AppleDebugOutputsProvider extends SkylarkClassObject * @return this builder. */ public Builder addOutput(String arch, OutputType outputType, Artifact artifact) { - if (!outputsByArch.containsKey(arch)) { - outputsByArch.put(arch, new HashMap<String, Artifact>()); - } + outputsByArch.computeIfAbsent(arch, k -> new HashMap<String, Artifact>()); outputsByArch.get(arch).put(outputType.toString(), artifact); return this; diff --git a/src/main/java/com/google/devtools/build/lib/rules/objc/BundleSupport.java b/src/main/java/com/google/devtools/build/lib/rules/objc/BundleSupport.java index 1c7220b672..8311dc77f6 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/objc/BundleSupport.java +++ b/src/main/java/com/google/devtools/build/lib/rules/objc/BundleSupport.java @@ -20,7 +20,6 @@ import static com.google.devtools.build.lib.rules.objc.ObjcProvider.STRINGS; import static com.google.devtools.build.lib.rules.objc.ObjcProvider.XCASSETS_DIR; import com.google.common.base.Optional; -import com.google.common.base.Predicate; import com.google.common.base.Verify; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; @@ -39,7 +38,6 @@ import com.google.devtools.build.lib.rules.apple.Platform; import com.google.devtools.build.lib.rules.apple.Platform.PlatformType; import com.google.devtools.build.lib.vfs.FileSystemUtils; import com.google.devtools.build.lib.vfs.PathFragment; - import java.util.HashMap; import java.util.Locale; import java.util.Map; @@ -205,13 +203,13 @@ final class BundleSupport { * Returns true if this bundle is targeted to {@link TargetDeviceFamily#WATCH}, false otherwise. */ boolean isBuildingForWatch() { - return Iterables.any(targetDeviceFamilies(), - new Predicate<TargetDeviceFamily>() { - @Override - public boolean apply(TargetDeviceFamily targetDeviceFamily) { - return targetDeviceFamily.name().equalsIgnoreCase(TargetDeviceFamily.WATCH.getNameInRule()); - } - }); + return targetDeviceFamilies() + .stream() + .anyMatch( + targetDeviceFamily -> + targetDeviceFamily + .name() + .equalsIgnoreCase(TargetDeviceFamily.WATCH.getNameInRule())); } /** diff --git a/src/main/java/com/google/devtools/build/lib/rules/objc/CompilationAttributes.java b/src/main/java/com/google/devtools/build/lib/rules/objc/CompilationAttributes.java index 6862165bb1..b44ac67e09 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/objc/CompilationAttributes.java +++ b/src/main/java/com/google/devtools/build/lib/rules/objc/CompilationAttributes.java @@ -400,7 +400,7 @@ final class CompilationAttributes { packageFragment.get(), genfilesFragment.getRelative(packageFragment.get())); Iterable<PathFragment> relativeIncludes = - Iterables.filter(includes(), Predicates.not(PathFragment.IS_ABSOLUTE)); + Iterables.filter(includes(), Predicates.not(PathFragment::isAbsolute)); for (PathFragment include : relativeIncludes) { for (PathFragment rootFragment : rootFragments) { paths.add(rootFragment.getRelative(include).normalize()); diff --git a/src/main/java/com/google/devtools/build/lib/rules/objc/CompilationSupport.java b/src/main/java/com/google/devtools/build/lib/rules/objc/CompilationSupport.java index 5018e98b34..1fd9ee4d8a 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/objc/CompilationSupport.java +++ b/src/main/java/com/google/devtools/build/lib/rules/objc/CompilationSupport.java @@ -31,6 +31,7 @@ import static com.google.devtools.build.lib.rules.objc.ObjcRuleClasses.PRECOMPIL import static com.google.devtools.build.lib.rules.objc.ObjcRuleClasses.SRCS_TYPE; import static com.google.devtools.build.lib.rules.objc.ObjcRuleClasses.STRIP; import static java.nio.charset.StandardCharsets.ISO_8859_1; +import static java.util.stream.Collectors.toCollection; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Joiner; @@ -85,11 +86,13 @@ import com.google.devtools.build.lib.util.FileTypeSet; import com.google.devtools.build.lib.util.Pair; import com.google.devtools.build.lib.vfs.FileSystemUtils; import com.google.devtools.build.lib.vfs.PathFragment; +import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; +import java.util.stream.Stream; import javax.annotation.Nullable; /** @@ -142,16 +145,11 @@ public abstract class CompilationSupport { "-fexceptions", "-fasm-blocks", "-fobjc-abi-version=2", "-fobjc-legacy-dispatch"); private static final String FRAMEWORK_SUFFIX = ".framework"; - + /** Selects cc libraries that have alwayslink=1. */ protected static final Predicate<Artifact> ALWAYS_LINKED_CC_LIBRARY = - new Predicate<Artifact>() { - @Override - public boolean apply(Artifact input) { - return LINK_LIBRARY_FILETYPES.matches(input.getFilename()); - } - }; - + input -> LINK_LIBRARY_FILETYPES.matches(input.getFilename()); + /** * Returns the location of the xcrunwrapper tool. */ @@ -678,7 +676,7 @@ public abstract class CompilationSupport { */ CompilationSupport validateAttributes() throws RuleErrorException { for (PathFragment absoluteInclude : - Iterables.filter(attributes.includes(), PathFragment.IS_ABSOLUTE)) { + Iterables.filter(attributes.includes(), PathFragment::isAbsolute)) { ruleContext.attributeError( "includes", String.format(ABSOLUTE_INCLUDES_PATH_FORMAT, absoluteInclude)); } @@ -825,7 +823,8 @@ public abstract class CompilationSupport { */ protected Iterable<String> getCompileRuleCopts() { List<String> copts = - Lists.newArrayList(Iterables.concat(objcConfiguration.getCopts(), attributes.copts())); + Stream.concat(objcConfiguration.getCopts().stream(), attributes.copts().stream()) + .collect(toCollection(ArrayList::new)); for (String copt : copts) { if (copt.contains("-fmodules-cache-path")) { diff --git a/src/main/java/com/google/devtools/build/lib/rules/objc/CrosstoolCompilationSupport.java b/src/main/java/com/google/devtools/build/lib/rules/objc/CrosstoolCompilationSupport.java index 915d40d76a..aca7f7a4a1 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/objc/CrosstoolCompilationSupport.java +++ b/src/main/java/com/google/devtools/build/lib/rules/objc/CrosstoolCompilationSupport.java @@ -14,6 +14,7 @@ package com.google.devtools.build.lib.rules.objc; +import static com.google.common.collect.ImmutableSortedSet.toImmutableSortedSet; import static com.google.devtools.build.lib.rules.objc.ObjcProvider.DEFINE; import static com.google.devtools.build.lib.rules.objc.ObjcProvider.DYNAMIC_FRAMEWORK_FILE; import static com.google.devtools.build.lib.rules.objc.ObjcProvider.HEADER; @@ -21,6 +22,7 @@ import static com.google.devtools.build.lib.rules.objc.ObjcProvider.IMPORTED_LIB import static com.google.devtools.build.lib.rules.objc.ObjcProvider.INCLUDE; import static com.google.devtools.build.lib.rules.objc.ObjcProvider.INCLUDE_SYSTEM; import static com.google.devtools.build.lib.rules.objc.ObjcProvider.STATIC_FRAMEWORK_FILE; +import static java.util.Comparator.naturalOrder; import com.google.common.base.Preconditions; import com.google.common.base.Predicates; @@ -29,6 +31,7 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Iterables; +import com.google.common.collect.Streams; import com.google.devtools.build.lib.actions.ActionAnalysisMetadata; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.analysis.AnalysisEnvironment; @@ -63,6 +66,7 @@ import com.google.devtools.build.lib.rules.objc.ObjcVariablesExtension.VariableC import com.google.devtools.build.lib.vfs.PathFragment; import java.util.Collection; import java.util.Map; +import java.util.stream.Stream; import javax.annotation.Nullable; /** @@ -387,8 +391,11 @@ public class CrosstoolCompilationSupport extends CompilationSupport { ImmutableSortedSet.copyOf(compilationArtifacts.getNonArcSrcs()); Collection<Artifact> privateHdrs = ImmutableSortedSet.copyOf(compilationArtifacts.getPrivateHdrs()); - Collection<Artifact> publicHdrs = ImmutableSortedSet.copyOf( - Iterables.concat(attributes.hdrs(), compilationArtifacts.getAdditionalHdrs())); + Collection<Artifact> publicHdrs = + Stream.concat( + Streams.stream(attributes.hdrs()), + Streams.stream(compilationArtifacts.getAdditionalHdrs())) + .collect(toImmutableSortedSet(naturalOrder())); Artifact pchHdr = null; if (ruleContext.attributes().has("pch", BuildType.LABEL)) { pchHdr = ruleContext.getPrerequisiteArtifact("pch", Mode.TARGET); diff --git a/src/main/java/com/google/devtools/build/lib/rules/objc/Interspersing.java b/src/main/java/com/google/devtools/build/lib/rules/objc/Interspersing.java index 38f1bca540..4cdc08dbff 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/objc/Interspersing.java +++ b/src/main/java/com/google/devtools/build/lib/rules/objc/Interspersing.java @@ -32,15 +32,7 @@ public class Interspersing { public static <E> Iterable<E> beforeEach(final E what, Iterable<E> sequence) { Preconditions.checkNotNull(what); return Iterables.concat( - Iterables.transform( - sequence, - new Function<E, Iterable<E>>() { - @Override - public Iterable<E> apply(E element) { - return ImmutableList.of(what, element); - } - } - )); + Iterables.transform(sequence, element -> ImmutableList.of(what, element))); } /** @@ -50,14 +42,7 @@ public class Interspersing { public static Iterable<String> prependEach(final String what, Iterable<String> sequence) { Preconditions.checkNotNull(what); - return Iterables.transform( - sequence, - new Function<String, String>() { - @Override - public String apply(String input) { - return what + input; - } - }); + return Iterables.transform(sequence, input -> what + input); } /** diff --git a/src/main/java/com/google/devtools/build/lib/rules/objc/IosApplication.java b/src/main/java/com/google/devtools/build/lib/rules/objc/IosApplication.java index 2d66821c95..f46aee827e 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/objc/IosApplication.java +++ b/src/main/java/com/google/devtools/build/lib/rules/objc/IosApplication.java @@ -14,10 +14,8 @@ package com.google.devtools.build.lib.rules.objc; -import com.google.common.base.Predicate; import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; +import com.google.common.collect.Streams; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.analysis.RuleConfiguredTarget.Mode; import com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder; @@ -69,15 +67,13 @@ public class IosApplication extends ReleaseBundlingTargetFactory { + "watch extension for each watch OS version"); } } - - private boolean hasMoreThanOneWatchExtension(Iterable<ObjcProvider> objcProviders, - final Flag watchExtensionVersionFlag) { - return Lists.newArrayList(Iterables.filter(objcProviders, new Predicate<ObjcProvider>() { - @Override - public boolean apply(ObjcProvider objcProvider) { - return objcProvider.is(watchExtensionVersionFlag); - } - })).size() > 1; + + private boolean hasMoreThanOneWatchExtension( + Iterable<ObjcProvider> objcProviders, final Flag watchExtensionVersionFlag) { + return Streams.stream(objcProviders) + .filter(objcProvider -> objcProvider.is(watchExtensionVersionFlag)) + .count() + > 1; } @Override diff --git a/src/main/java/com/google/devtools/build/lib/rules/objc/ObjcProvider.java b/src/main/java/com/google/devtools/build/lib/rules/objc/ObjcProvider.java index ba2ef87372..3590f5c10e 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/objc/ObjcProvider.java +++ b/src/main/java/com/google/devtools/build/lib/rules/objc/ObjcProvider.java @@ -666,13 +666,7 @@ public final class ObjcProvider extends SkylarkClassObject implements Transitive */ private static Predicate<Artifact> notContainedIn( final HashSet<Artifact> linkedLibraryArtifacts) { - return new Predicate<Artifact>() { - - @Override - public boolean apply(Artifact libraryToLink) { - return !linkedLibraryArtifacts.contains(libraryToLink); - } - }; + return libraryToLink -> !linkedLibraryArtifacts.contains(libraryToLink); } /** @@ -684,13 +678,7 @@ public final class ObjcProvider extends SkylarkClassObject implements Transitive */ private static Predicate<LibraryToLink> ccLibraryNotYetLinked( final HashSet<Artifact> linkedLibraryArtifacts) { - return new Predicate<LibraryToLink>() { - - @Override - public boolean apply(LibraryToLink libraryToLink) { - return !linkedLibraryArtifacts.contains(libraryToLink.getArtifact()); - } - }; + return libraryToLink -> !linkedLibraryArtifacts.contains(libraryToLink.getArtifact()); } @SuppressWarnings("unchecked") @@ -734,9 +722,7 @@ public final class ObjcProvider extends SkylarkClassObject implements Transitive private final Map<Key<?>, NestedSetBuilder<?>> strictDependencyItems = new HashMap<>(); private static void maybeAddEmptyBuilder(Map<Key<?>, NestedSetBuilder<?>> set, Key<?> key) { - if (!set.containsKey(key)) { - set.put(key, new NestedSetBuilder<>(key.order)); - } + set.computeIfAbsent(key, k -> new NestedSetBuilder<>(k.order)); } @SuppressWarnings({"rawtypes", "unchecked"}) diff --git a/src/main/java/com/google/devtools/build/lib/rules/objc/ProtobufSupport.java b/src/main/java/com/google/devtools/build/lib/rules/objc/ProtobufSupport.java index 080716af52..35ba9f9c70 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/objc/ProtobufSupport.java +++ b/src/main/java/com/google/devtools/build/lib/rules/objc/ProtobufSupport.java @@ -14,7 +14,6 @@ package com.google.devtools.build.lib.rules.objc; -import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Optional; import com.google.common.base.Predicates; @@ -567,13 +566,7 @@ final class ProtobufSupport { Iterable<String> filterLines = Iterables.transform( - protoFilePaths, - new Function<String, String>() { - @Override - public String apply(String protoFilePath) { - return String.format("allowed_file: \"%s\"", protoFilePath); - } - }); + protoFilePaths, protoFilePath -> String.format("allowed_file: \"%s\"", protoFilePath)); return String.format( "# Generated portable filter for %s\n\n", ruleContext.getLabel().getCanonicalForm()) diff --git a/src/main/java/com/google/devtools/build/lib/rules/objc/ProtocolBuffers2Support.java b/src/main/java/com/google/devtools/build/lib/rules/objc/ProtocolBuffers2Support.java index 610f27776a..d3f8bbf085 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/objc/ProtocolBuffers2Support.java +++ b/src/main/java/com/google/devtools/build/lib/rules/objc/ProtocolBuffers2Support.java @@ -14,7 +14,6 @@ package com.google.devtools.build.lib.rules.objc; -import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; @@ -40,14 +39,6 @@ final class ProtocolBuffers2Support { private static final String UNIQUE_DIRECTORY_NAME = "_generated_protos"; - private static final Function<Artifact, PathFragment> PARENT_PATHFRAGMENT = - new Function<Artifact, PathFragment>() { - @Override - public PathFragment apply(Artifact input) { - return input.getExecPath().getParentDirectory(); - } - }; - private final RuleContext ruleContext; private final ProtoAttributes attributes; @@ -195,7 +186,8 @@ final class ProtocolBuffers2Support { .add(generatedProtoDir) .addAll( Iterables.transform( - getGeneratedProtoOutputs(getHeaderExtension()), PARENT_PATHFRAGMENT)); + getGeneratedProtoOutputs(getHeaderExtension()), + input -> input.getExecPath().getParentDirectory())); } return searchPathEntriesBuilder.build(); diff --git a/src/main/java/com/google/devtools/build/lib/rules/objc/Xcdatamodel.java b/src/main/java/com/google/devtools/build/lib/rules/objc/Xcdatamodel.java index 274bcb2b9a..e4b13c7409 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/objc/Xcdatamodel.java +++ b/src/main/java/com/google/devtools/build/lib/rules/objc/Xcdatamodel.java @@ -14,7 +14,6 @@ package com.google.devtools.build.lib.rules.objc; -import com.google.common.base.Function; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; @@ -96,11 +95,6 @@ class Xcdatamodel extends Value<Xcdatamodel> { } public static Iterable<Artifact> outputZips(Iterable<Xcdatamodel> models) { - return Iterables.transform(models, new Function<Xcdatamodel, Artifact>() { - @Override - public Artifact apply(Xcdatamodel model) { - return model.getOutputZip(); - } - }); + return Iterables.transform(models, Xcdatamodel::getOutputZip); } } diff --git a/src/main/java/com/google/devtools/build/lib/rules/proto/ProtoSourceFileBlacklist.java b/src/main/java/com/google/devtools/build/lib/rules/proto/ProtoSourceFileBlacklist.java index 7f38142785..70f785c3d2 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/proto/ProtoSourceFileBlacklist.java +++ b/src/main/java/com/google/devtools/build/lib/rules/proto/ProtoSourceFileBlacklist.java @@ -14,6 +14,7 @@ package com.google.devtools.build.lib.rules.proto; +import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.devtools.build.lib.packages.Attribute.ConfigurationTransition.HOST; import static com.google.devtools.build.lib.packages.Attribute.attr; import static com.google.devtools.build.lib.packages.BuildType.LABEL_LIST; @@ -23,7 +24,7 @@ import com.google.common.base.Joiner; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; +import com.google.common.collect.Streams; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.analysis.RuleContext; import com.google.devtools.build.lib.cmdline.Label; @@ -46,13 +47,7 @@ public class ProtoSourceFileBlacklist { private final RuleContext ruleContext; private final ImmutableSet<PathFragment> blacklistProtoFilePaths; - private final Predicate<Artifact> isBlacklistProto = - new Predicate<Artifact>() { - @Override - public boolean apply(Artifact protoFile) { - return isBlacklisted(protoFile); - } - }; + private final Predicate<Artifact> isBlacklistProto = this::isBlacklisted; /** * Creates a proto source file blacklist. @@ -83,7 +78,9 @@ public class ProtoSourceFileBlacklist { * Filters the blacklisted protos from the given protos. */ public Iterable<Artifact> filter(Iterable<Artifact> protoFiles) { - return ImmutableSet.copyOf(Iterables.filter(protoFiles, Predicates.not(isBlacklistProto))); + return Streams.stream(protoFiles) + .filter(Predicates.not(isBlacklistProto)) + .collect(toImmutableSet()); } /** diff --git a/src/main/java/com/google/devtools/build/lib/rules/python/PyCcLinkParamsProvider.java b/src/main/java/com/google/devtools/build/lib/rules/python/PyCcLinkParamsProvider.java index 3234520c63..123444c6e5 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/python/PyCcLinkParamsProvider.java +++ b/src/main/java/com/google/devtools/build/lib/rules/python/PyCcLinkParamsProvider.java @@ -36,12 +36,8 @@ public final class PyCcLinkParamsProvider implements TransitiveInfoProvider { } public static final Function<TransitiveInfoCollection, CcLinkParamsStore> TO_LINK_PARAMS = - new Function<TransitiveInfoCollection, CcLinkParamsStore>() { - @Override - public CcLinkParamsStore apply(TransitiveInfoCollection input) { - PyCcLinkParamsProvider provider = input.getProvider( - PyCcLinkParamsProvider.class); - return provider == null ? null : provider.getLinkParams(); - } + input -> { + PyCcLinkParamsProvider provider = input.getProvider(PyCcLinkParamsProvider.class); + return provider == null ? null : provider.getLinkParams(); }; } diff --git a/src/main/java/com/google/devtools/build/lib/rules/python/PythonRunfilesProvider.java b/src/main/java/com/google/devtools/build/lib/rules/python/PythonRunfilesProvider.java index 76d55573cf..8c6f110d83 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/python/PythonRunfilesProvider.java +++ b/src/main/java/com/google/devtools/build/lib/rules/python/PythonRunfilesProvider.java @@ -37,17 +37,12 @@ public final class PythonRunfilesProvider implements TransitiveInfoProvider { } /** - * Returns a function that gets the Python runfiles from a {@link TransitiveInfoCollection} or - * the empty runfiles instance if it does not contain that provider. + * Returns a function that gets the Python runfiles from a {@link TransitiveInfoCollection} or the + * empty runfiles instance if it does not contain that provider. */ public static final Function<TransitiveInfoCollection, Runfiles> TO_RUNFILES = - new Function<TransitiveInfoCollection, Runfiles>() { - @Override - public Runfiles apply(TransitiveInfoCollection input) { - PythonRunfilesProvider provider = input.getProvider(PythonRunfilesProvider.class); - return provider == null - ? Runfiles.EMPTY - : provider.getPythonRunfiles(); - } + input -> { + PythonRunfilesProvider provider = input.getProvider(PythonRunfilesProvider.class); + return provider == null ? Runfiles.EMPTY : provider.getPythonRunfiles(); }; } diff --git a/src/main/java/com/google/devtools/build/lib/runtime/BlazeCommandDispatcher.java b/src/main/java/com/google/devtools/build/lib/runtime/BlazeCommandDispatcher.java index 3182376bf6..5895916b5d 100644 --- a/src/main/java/com/google/devtools/build/lib/runtime/BlazeCommandDispatcher.java +++ b/src/main/java/com/google/devtools/build/lib/runtime/BlazeCommandDispatcher.java @@ -25,7 +25,6 @@ import com.google.common.cache.LoadingCache; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; import com.google.common.collect.ListMultimap; import com.google.common.io.Flushables; import com.google.common.util.concurrent.UncheckedExecutionException; @@ -205,14 +204,11 @@ public class BlazeCommandDispatcher { List<String> rcfileNotes, ExtendedEventHandler eventHandler) throws OptionsParsingException { Function<String, String> commandOptionSourceFunction = - new Function<String, String>() { - @Override - public String apply(String input) { - if (INTERNAL_COMMAND_OPTIONS.contains(input)) { - return "options generated by " + runtime.getProductName() + " launcher"; - } else { - return "command line options"; - } + input -> { + if (INTERNAL_COMMAND_OPTIONS.contains(input)) { + return "options generated by " + runtime.getProductName() + " launcher"; + } else { + return "command line options"; } }; @@ -649,9 +645,10 @@ public class BlazeCommandDispatcher { } } if (unknownConfigs != null && configs != null && configs.size() > knownConfigs.size()) { - Iterables.addAll( - unknownConfigs, - Iterables.filter(configs, Predicates.not(Predicates.in(knownConfigs)))); + configs + .stream() + .filter(Predicates.not(Predicates.in(knownConfigs))) + .forEachOrdered(unknownConfigs::add); } } diff --git a/src/main/java/com/google/devtools/build/lib/runtime/BlazeRuntime.java b/src/main/java/com/google/devtools/build/lib/runtime/BlazeRuntime.java index d66a4323d8..ee5478679f 100644 --- a/src/main/java/com/google/devtools/build/lib/runtime/BlazeRuntime.java +++ b/src/main/java/com/google/devtools/build/lib/runtime/BlazeRuntime.java @@ -681,19 +681,17 @@ public final class BlazeRuntime { final Thread mainThread = Thread.currentThread(); final AtomicInteger numInterrupts = new AtomicInteger(); - final Runnable interruptWatcher = new Runnable() { - @Override - public void run() { - int count = 0; - // Not an actual infinite loop because it's run in a daemon thread. - while (true) { - count++; - Uninterruptibles.sleepUninterruptibly(10, TimeUnit.SECONDS); - LOG.warning("Slow interrupt number " + count + " in batch mode"); - ThreadUtils.warnAboutSlowInterrupt(); - } - } - }; + final Runnable interruptWatcher = + () -> { + int count = 0; + // Not an actual infinite loop because it's run in a daemon thread. + while (true) { + count++; + Uninterruptibles.sleepUninterruptibly(10, TimeUnit.SECONDS); + LOG.warning("Slow interrupt number " + count + " in batch mode"); + ThreadUtils.warnAboutSlowInterrupt(); + } + }; new InterruptSignalHandler() { @Override @@ -821,12 +819,7 @@ public final class BlazeRuntime { Iterable<BlazeModule> modules, List<String> args) throws IOException, OptionsParsingException, AbruptExitException { final RPCServer[] rpcServer = new RPCServer[1]; - Runnable prepareForAbruptShutdown = new Runnable() { - @Override - public void run() { - rpcServer[0].prepareForAbruptShutdown(); - } - }; + Runnable prepareForAbruptShutdown = () -> rpcServer[0].prepareForAbruptShutdown(); BlazeRuntime runtime = newRuntime(modules, args, prepareForAbruptShutdown); BlazeCommandDispatcher dispatcher = new BlazeCommandDispatcher(runtime); @@ -870,17 +863,18 @@ public final class BlazeRuntime { parser.parse(OptionPriority.COMMAND_LINE, null, args); Map<String, String> optionSources = parser.getOptions(BlazeServerStartupOptions.class).optionSources; - Function<String, String> sourceFunction = option -> { - if (!optionSources.containsKey(option)) { - return "default"; - } + Function<String, String> sourceFunction = + option -> { + if (!optionSources.containsKey(option)) { + return "default"; + } - if (optionSources.get(option).isEmpty()) { - return "command line"; - } + if (optionSources.get(option).isEmpty()) { + return "command line"; + } - return optionSources.get(option); - }; + return optionSources.get(option); + }; // Then parse the command line again, this time with the correct option sources parser = OptionsParser.newOptionsParser(optionClasses); @@ -1082,12 +1076,7 @@ public final class BlazeRuntime { */ private static void setupUncaughtHandler(final String[] args) { Thread.setDefaultUncaughtExceptionHandler( - new Thread.UncaughtExceptionHandler() { - @Override - public void uncaughtException(Thread thread, Throwable throwable) { - BugReport.handleCrash(throwable, args); - } - }); + (thread, throwable) -> BugReport.handleCrash(throwable, args)); } public String getProductName() { diff --git a/src/main/java/com/google/devtools/build/lib/runtime/BuildEventStreamer.java b/src/main/java/com/google/devtools/build/lib/runtime/BuildEventStreamer.java index dc14a2b09e..f32518a99d 100644 --- a/src/main/java/com/google/devtools/build/lib/runtime/BuildEventStreamer.java +++ b/src/main/java/com/google/devtools/build/lib/runtime/BuildEventStreamer.java @@ -265,18 +265,19 @@ public class BuildEventStreamer implements EventHandler { private ScheduledFuture<?> bepUploadWaitEvent(ScheduledExecutorService executor) { final long startNanos = System.nanoTime(); - return executor.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - long deltaNanos = System.nanoTime() - startNanos; - long deltaSeconds = TimeUnit.NANOSECONDS.toSeconds(deltaNanos); - Event waitEvt = - of(PROGRESS, null, "Waiting for build event protocol upload: " + deltaSeconds + "s"); - if (reporter != null) { - reporter.handle(waitEvt); - } - } - }, 0, 1, TimeUnit.SECONDS); + return executor.scheduleAtFixedRate( + () -> { + long deltaNanos = System.nanoTime() - startNanos; + long deltaSeconds = TimeUnit.NANOSECONDS.toSeconds(deltaNanos); + Event waitEvt = + of(PROGRESS, null, "Waiting for build event protocol upload: " + deltaSeconds + "s"); + if (reporter != null) { + reporter.handle(waitEvt); + } + }, + 0, + 1, + TimeUnit.SECONDS); } private void close() { @@ -286,14 +287,13 @@ public class BuildEventStreamer implements EventHandler { List<ListenableFuture<Void>> closeFutures = new ArrayList<>(transports.size()); for (final BuildEventTransport transport : transports) { ListenableFuture<Void> closeFuture = transport.close(); - closeFuture.addListener(new Runnable() { - @Override - public void run() { - if (reporter != null) { - reporter.post(new BuildEventTransportClosedEvent(transport)); - } - } - }, executor); + closeFuture.addListener( + () -> { + if (reporter != null) { + reporter.post(new BuildEventTransportClosedEvent(transport)); + } + }, + executor); closeFutures.add(closeFuture); } diff --git a/src/main/java/com/google/devtools/build/lib/runtime/CommandNameCacheImpl.java b/src/main/java/com/google/devtools/build/lib/runtime/CommandNameCacheImpl.java index 2ebb359141..a0a4b8dea8 100644 --- a/src/main/java/com/google/devtools/build/lib/runtime/CommandNameCacheImpl.java +++ b/src/main/java/com/google/devtools/build/lib/runtime/CommandNameCacheImpl.java @@ -13,7 +13,6 @@ // limitations under the License. package com.google.devtools.build.lib.runtime; -import com.google.common.base.Function; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import com.google.devtools.build.lib.util.Preconditions; @@ -34,13 +33,7 @@ class CommandNameCacheImpl implements CommandNameCache { // post-creation. this.commandMap = Maps.transformValues( - commandMap, - new Function<BlazeCommand, Command>() { - @Override - public Command apply(BlazeCommand blazeCommand) { - return blazeCommand.getClass().getAnnotation(Command.class); - } - }); + commandMap, blazeCommand -> blazeCommand.getClass().getAnnotation(Command.class)); } @Override diff --git a/src/main/java/com/google/devtools/build/lib/runtime/CriticalPathComputer.java b/src/main/java/com/google/devtools/build/lib/runtime/CriticalPathComputer.java index 0702fd198f..52e25d1a7d 100644 --- a/src/main/java/com/google/devtools/build/lib/runtime/CriticalPathComputer.java +++ b/src/main/java/com/google/devtools/build/lib/runtime/CriticalPathComputer.java @@ -14,6 +14,8 @@ package com.google.devtools.build.lib.runtime; +import static java.util.Comparator.comparingLong; + import com.google.common.collect.ImmutableList; import com.google.common.collect.Maps; import com.google.common.eventbus.Subscribe; @@ -28,7 +30,6 @@ import com.google.devtools.build.lib.util.Clock; import com.google.devtools.build.lib.util.Preconditions; import java.util.ArrayList; import java.util.Collections; -import java.util.Comparator; import java.util.Objects; import java.util.PriorityQueue; import java.util.concurrent.ConcurrentMap; @@ -59,14 +60,8 @@ public abstract class CriticalPathComputer<C extends AbstractCriticalPathCompone * <p>This data is a useful metric when running non highly incremental builds, where multiple * tasks could run un parallel and critical path would only record the longest path. */ - private final PriorityQueue<C> slowestComponents = new PriorityQueue<>(SLOWEST_COMPONENTS_SIZE, - new Comparator<C>() { - @Override - public int compare(C o1, C o2) { - return Long.compare(o1.getElapsedTimeNanos(), o2.getElapsedTimeNanos()); - } - } - ); + private final PriorityQueue<C> slowestComponents = + new PriorityQueue<>(SLOWEST_COMPONENTS_SIZE, comparingLong(C::getElapsedTimeNanos)); private final Object lock = new Object(); diff --git a/src/main/java/com/google/devtools/build/lib/runtime/ExperimentalEventHandler.java b/src/main/java/com/google/devtools/build/lib/runtime/ExperimentalEventHandler.java index 4c3ac451c3..391a6c1dff 100644 --- a/src/main/java/com/google/devtools/build/lib/runtime/ExperimentalEventHandler.java +++ b/src/main/java/com/google/devtools/build/lib/runtime/ExperimentalEventHandler.java @@ -705,21 +705,18 @@ public class ExperimentalEventHandler implements EventHandler { final ExperimentalEventHandler eventHandler = this; updateThread = new Thread( - new Runnable() { - @Override - public void run() { - try { - while (true) { - Thread.sleep(minimalUpdateInterval); - if (lastRefreshMillis < mustRefreshAfterMillis - && mustRefreshAfterMillis < clock.currentTimeMillis()) { - progressBarNeedsRefresh = true; - } - eventHandler.doRefresh(/* fromUpdateThread= */ true); + () -> { + try { + while (true) { + Thread.sleep(minimalUpdateInterval); + if (lastRefreshMillis < mustRefreshAfterMillis + && mustRefreshAfterMillis < clock.currentTimeMillis()) { + progressBarNeedsRefresh = true; } - } catch (InterruptedException e) { - // Ignore + eventHandler.doRefresh(/* fromUpdateThread= */ true); } + } catch (InterruptedException e) { + // Ignore } }); threadToStart = updateThread; diff --git a/src/main/java/com/google/devtools/build/lib/runtime/GotOptionsEvent.java b/src/main/java/com/google/devtools/build/lib/runtime/GotOptionsEvent.java index 2097884cff..6d23b67237 100644 --- a/src/main/java/com/google/devtools/build/lib/runtime/GotOptionsEvent.java +++ b/src/main/java/com/google/devtools/build/lib/runtime/GotOptionsEvent.java @@ -13,7 +13,6 @@ // limitations under the License. package com.google.devtools.build.lib.runtime; -import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.devtools.build.lib.buildeventstream.BuildEventConverters; @@ -23,7 +22,6 @@ import com.google.devtools.build.lib.buildeventstream.BuildEventWithOrderConstra import com.google.devtools.build.lib.buildeventstream.GenericBuildEvent; import com.google.devtools.build.lib.runtime.proto.InvocationPolicyOuterClass.InvocationPolicy; import com.google.devtools.build.lib.util.OptionsUtils; -import com.google.devtools.common.options.OptionsParser.UnparsedOptionValueDescription; import com.google.devtools.common.options.OptionsProvider; import java.util.Collection; import java.util.Objects; @@ -88,25 +86,14 @@ public class GotOptionsEvent implements BuildEventWithOrderConstraint { OptionsUtils.asArgumentList( Iterables.filter( options.asListOfExplicitOptions(), - new Predicate<UnparsedOptionValueDescription>() { - @Override - public boolean apply(UnparsedOptionValueDescription input) { - return !Objects.equals(input.getSource(), "default"); - } - }))); + input -> !Objects.equals(input.getSource(), "default")))); options = getOptions(); optionsBuilder.addAllCmdLine(OptionsUtils.asArgumentList(options)); optionsBuilder.addAllExplicitCmdLine( OptionsUtils.asArgumentList( Iterables.filter( options.asListOfExplicitOptions(), - new Predicate<UnparsedOptionValueDescription>() { - @Override - public boolean apply(UnparsedOptionValueDescription input) { - // Source can be null coming from the OptionParser. - return Objects.equals(input.getSource(), "command line options"); - } - }))); + input -> Objects.equals(input.getSource(), "command line options")))); optionsBuilder.setInvocationPolicy(getInvocationPolicy()); diff --git a/src/main/java/com/google/devtools/build/lib/server/GrpcServerImpl.java b/src/main/java/com/google/devtools/build/lib/server/GrpcServerImpl.java index 260273c4fc..032da198d3 100644 --- a/src/main/java/com/google/devtools/build/lib/server/GrpcServerImpl.java +++ b/src/main/java/com/google/devtools/build/lib/server/GrpcServerImpl.java @@ -887,19 +887,12 @@ public class GrpcServerImpl implements RPCServer { new CommandServerGrpc.CommandServerImplBase() { @Override public void run(final RunRequest request, final StreamObserver<RunResponse> observer) { - final GrpcSink sink = new GrpcSink( - "Run", - (ServerCallStreamObserver<RunResponse>) observer, - streamExecutorPool); + final GrpcSink sink = + new GrpcSink( + "Run", (ServerCallStreamObserver<RunResponse>) observer, streamExecutorPool); // Switch to our own threads so that onReadyStateHandler can be called (see class-level // comment) - commandExecutorPool.execute( - new Runnable() { - @Override - public void run() { - executeCommand(request, observer, sink); - } - }); + commandExecutorPool.execute(() -> executeCommand(request, observer, sink)); } @Override @@ -928,12 +921,7 @@ public class GrpcServerImpl implements RPCServer { // Actually performing the cancellation can result in some blocking which we don't want // to do on the dispatcher thread, instead offload to command pool. - commandExecutorPool.execute(new Runnable() { - @Override - public void run() { - doCancel(request, streamObserver); - } - }); + commandExecutorPool.execute(() -> doCancel(request, streamObserver)); } private void doCancel( @@ -958,8 +946,8 @@ public class GrpcServerImpl implements RPCServer { streamObserver.onCompleted(); } catch (StatusRuntimeException e) { // There is no one to report the failure to - log.info("Client cancelled RPC of cancellation request for " - + request.getCommandId()); + log.info( + "Client cancelled RPC of cancellation request for " + request.getCommandId()); } } } diff --git a/src/main/java/com/google/devtools/build/lib/syntax/EvalExceptionWithStackTrace.java b/src/main/java/com/google/devtools/build/lib/syntax/EvalExceptionWithStackTrace.java index f9d75bbce5..713f57fafc 100644 --- a/src/main/java/com/google/devtools/build/lib/syntax/EvalExceptionWithStackTrace.java +++ b/src/main/java/com/google/devtools/build/lib/syntax/EvalExceptionWithStackTrace.java @@ -130,7 +130,7 @@ public class EvalExceptionWithStackTrace extends EvalException { private boolean isSameLocation(Location first, Location second) { try { return Objects.equals(first.getPath(), second.getPath()) - && Objects.equals(first.getStartOffset(), second.getStartOffset()); + && first.getStartOffset() == second.getStartOffset(); } catch (NullPointerException ex) { return first == second; } diff --git a/src/main/java/com/google/devtools/build/lib/syntax/FunctionSignature.java b/src/main/java/com/google/devtools/build/lib/syntax/FunctionSignature.java index 401b4a307b..9b0fb008ab 100644 --- a/src/main/java/com/google/devtools/build/lib/syntax/FunctionSignature.java +++ b/src/main/java/com/google/devtools/build/lib/syntax/FunctionSignature.java @@ -13,10 +13,11 @@ // limitations under the License. package com.google.devtools.build.lib.syntax; +import static com.google.common.collect.ImmutableList.toImmutableList; + import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableList; import com.google.common.collect.Interner; -import com.google.common.collect.Lists; import com.google.devtools.build.lib.concurrent.BlazeInterners; import com.google.devtools.build.lib.syntax.SkylarkList.Tuple; import com.google.devtools.build.lib.util.Preconditions; @@ -159,8 +160,8 @@ public abstract class FunctionSignature implements Serializable { /** Intern a list of names */ public static ImmutableList<String> names(List<String> names) { - return namesInterner.intern(ImmutableList.<String>copyOf( - Lists.transform(names, StringCanonicalizer.INTERN))); + return namesInterner.intern( + names.stream().map(StringCanonicalizer::intern).collect(toImmutableList())); } /** Intern a list of names */ diff --git a/src/main/java/com/google/devtools/build/lib/syntax/GlobCriteria.java b/src/main/java/com/google/devtools/build/lib/syntax/GlobCriteria.java index c1bd88bcb2..91979fb3c3 100644 --- a/src/main/java/com/google/devtools/build/lib/syntax/GlobCriteria.java +++ b/src/main/java/com/google/devtools/build/lib/syntax/GlobCriteria.java @@ -14,15 +14,16 @@ package com.google.devtools.build.lib.syntax; +import static com.google.common.collect.ImmutableList.toImmutableList; + import com.google.common.base.Functions; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList.Builder; import com.google.common.collect.Iterables; import com.google.devtools.build.lib.util.Preconditions; - import java.util.List; - +import java.util.stream.Stream; import javax.annotation.Nullable; /** @@ -90,8 +91,9 @@ public class GlobCriteria { public static GlobCriteria createWithAdditionalExcludes(GlobCriteria base, List<String> excludes) { Preconditions.checkArgument(base.isGlob()); - return fromGlobCall(base.include, - ImmutableList.copyOf(Iterables.concat(base.exclude, excludes))); + return fromGlobCall( + base.include, + Stream.concat(base.exclude.stream(), excludes.stream()).collect(toImmutableList())); } /** diff --git a/src/main/java/com/google/devtools/build/lib/syntax/LineNumberTable.java b/src/main/java/com/google/devtools/build/lib/syntax/LineNumberTable.java index d16a83daf1..eda66098a9 100644 --- a/src/main/java/com/google/devtools/build/lib/syntax/LineNumberTable.java +++ b/src/main/java/com/google/devtools/build/lib/syntax/LineNumberTable.java @@ -215,11 +215,7 @@ public abstract class LineNumberTable implements Serializable { Map<String, PathFragment> pathCache = new HashMap<>(); while (m.find()) { String pathString = m.group(2); - PathFragment pathFragment = pathCache.get(pathString); - if (pathFragment == null) { - pathFragment = defaultPath.getRelative(pathString); - pathCache.put(pathString, pathFragment); - } + PathFragment pathFragment = pathCache.computeIfAbsent(pathString, defaultPath::getRelative); unorderedTable.add(new SingleHashLine( m.start(0) + 1, //offset (+1 to skip \n in pattern) Integer.parseInt(m.group(1)), // line number diff --git a/src/main/java/com/google/devtools/build/lib/syntax/MethodLibrary.java b/src/main/java/com/google/devtools/build/lib/syntax/MethodLibrary.java index 8f466b7ff0..3b1a7c03c6 100644 --- a/src/main/java/com/google/devtools/build/lib/syntax/MethodLibrary.java +++ b/src/main/java/com/google/devtools/build/lib/syntax/MethodLibrary.java @@ -14,11 +14,12 @@ package com.google.devtools.build.lib.syntax; +import static java.util.stream.Collectors.joining; + import com.google.common.base.CharMatcher; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Ordering; import com.google.devtools.build.lib.collect.nestedset.NestedSet; @@ -2063,39 +2064,48 @@ public class MethodLibrary { } }; - @SkylarkSignature(name = "print", returnType = Runtime.NoneType.class, - doc = "Prints <code>args</code> as output. It will be prefixed with the string <code>" - + "\"WARNING\"</code> and the location (file and line number) of this call. It can be " - + "used for debugging." - + "<p>Using <code>print</code> in production code is discouraged due to the spam it " - + "creates for users. For deprecations, prefer a hard error using <a href=\"#fail\">" - + "fail()</a> when possible.", - parameters = { - @Param(name = "sep", type = String.class, defaultValue = "' '", - named = true, positional = false, - doc = "The separator string between the objects, default is space (\" \").")}, - // NB: as compared to Python3, we're missing optional named-only arguments 'end' and 'file' - extraPositionals = @Param(name = "args", doc = "The objects to print."), - useLocation = true, useEnvironment = true) - private static final BuiltinFunction print = new BuiltinFunction("print") { - public Runtime.NoneType invoke(String sep, SkylarkList<?> starargs, - Location loc, Environment env) throws EvalException { - String msg = Joiner.on(sep).join(Iterables.transform(starargs, - new com.google.common.base.Function<Object, String>() { - @Override - public String apply(Object input) { - return Printer.str(input); - }})); - // As part of the integration test "skylark_flag_test.sh", if the - // "--internal_skylark_flag_test_canary" flag is enabled, append an extra marker string to the - // output. - if (env.getSemantics().skylarkFlagTestCanary) { - msg += "<== skylark flag test ==>"; - } - env.handleEvent(Event.warn(loc, msg)); - return Runtime.NONE; - } - }; + @SkylarkSignature( + name = "print", + returnType = Runtime.NoneType.class, + doc = + "Prints <code>args</code> as output. It will be prefixed with the string <code>" + + "\"WARNING\"</code> and the location (file and line number) of this call. It can be " + + "used for debugging." + + "<p>Using <code>print</code> in production code is discouraged due to the spam it " + + "creates for users. For deprecations, prefer a hard error using <a href=\"#fail\">" + + "fail()</a> when possible.", + parameters = { + @Param( + name = "sep", + type = String.class, + defaultValue = "' '", + named = true, + positional = false, + doc = "The separator string between the objects, default is space (\" \")." + ) + }, + // NB: as compared to Python3, we're missing optional named-only arguments 'end' and 'file' + extraPositionals = @Param(name = "args", doc = "The objects to print."), + useLocation = true, + useEnvironment = true + ) + private static final BuiltinFunction print = + new BuiltinFunction("print") { + public Runtime.NoneType invoke( + String sep, SkylarkList<?> starargs, Location loc, Environment env) + throws EvalException { + String msg = starargs.stream().map(Printer::str).collect(joining(sep)); + // As part of the integration test "skylark_flag_test.sh", if the + // "--internal_skylark_flag_test_canary" flag is enabled, append an extra marker string to + // the + // output. + if (env.getSemantics().skylarkFlagTestCanary) { + msg += "<== skylark flag test ==>"; + } + env.handleEvent(Event.warn(loc, msg)); + return Runtime.NONE; + } + }; @SkylarkSignature( name = "zip", diff --git a/src/main/java/com/google/devtools/build/lib/syntax/Mutability.java b/src/main/java/com/google/devtools/build/lib/syntax/Mutability.java index ead4df060e..1b00915ac6 100644 --- a/src/main/java/com/google/devtools/build/lib/syntax/Mutability.java +++ b/src/main/java/com/google/devtools/build/lib/syntax/Mutability.java @@ -13,7 +13,6 @@ // limitations under the License. package com.google.devtools.build.lib.syntax; -import com.google.common.base.Function; import com.google.common.collect.Iterables; import com.google.devtools.build.lib.events.Location; import com.google.devtools.build.lib.util.Preconditions; @@ -245,12 +244,8 @@ public final class Mutability implements AutoCloseable, Serializable { } if (env.mutability().isLocked(object)) { - Iterable<String> locs = Iterables.transform(env.mutability().getLockLocations(object), - new Function<Location, String>() { - @Override - public String apply(Location loc) { - return loc.print(); - }}); + Iterable<String> locs = + Iterables.transform(env.mutability().getLockLocations(object), Location::print); throw new MutabilityException( "trying to mutate a locked object (is it currently being iterated over by a for loop " + "or comprehension?)\n" diff --git a/src/main/java/com/google/devtools/build/lib/syntax/Parser.java b/src/main/java/com/google/devtools/build/lib/syntax/Parser.java index ae97362c95..f5e5b51659 100644 --- a/src/main/java/com/google/devtools/build/lib/syntax/Parser.java +++ b/src/main/java/com/google/devtools/build/lib/syntax/Parser.java @@ -568,7 +568,7 @@ public class Parser { // arg_list ::= ( (arg ',')* arg ','? )? private List<Argument.Passed> parseFuncallArguments() { - List<Argument.Passed> arguments = parseFunctionArguments(() -> parseFuncallArgument()); + List<Argument.Passed> arguments = parseFunctionArguments(this::parseFuncallArgument); try { Argument.validateFuncallArguments(arguments); } catch (Argument.ArgumentException e) { @@ -1306,7 +1306,7 @@ public class Parser { Identifier ident = parseIdent(); expect(TokenKind.LPAREN); List<Parameter<Expression, Expression>> params = - parseFunctionArguments(() -> parseFunctionParameter()); + parseFunctionArguments(this::parseFunctionParameter); FunctionSignature.WithValues<Expression, Expression> signature = functionSignature(params); expect(TokenKind.RPAREN); expect(TokenKind.COLON); diff --git a/src/main/java/com/google/devtools/build/lib/syntax/Runtime.java b/src/main/java/com/google/devtools/build/lib/syntax/Runtime.java index 428079441c..8f672127e7 100644 --- a/src/main/java/com/google/devtools/build/lib/syntax/Runtime.java +++ b/src/main/java/com/google/devtools/build/lib/syntax/Runtime.java @@ -146,9 +146,7 @@ public final class Runtime { Preconditions.checkArgument(nameSpace.equals(getCanonicalRepresentation(nameSpace))); Preconditions.checkArgument( getCanonicalRepresentation(function.getObjectType()).equals(nameSpace)); - if (!functions.containsKey(nameSpace)) { - functions.put(nameSpace, new HashMap<String, BaseFunction>()); - } + functions.computeIfAbsent(nameSpace, k -> new HashMap<String, BaseFunction>()); functions.get(nameSpace).put(function.getName(), function); } diff --git a/src/main/java/com/google/devtools/build/lib/util/CommandFailureUtils.java b/src/main/java/com/google/devtools/build/lib/util/CommandFailureUtils.java index ef787de045..9fb0c835b8 100644 --- a/src/main/java/com/google/devtools/build/lib/util/CommandFailureUtils.java +++ b/src/main/java/com/google/devtools/build/lib/util/CommandFailureUtils.java @@ -14,13 +14,13 @@ package com.google.devtools.build.lib.util; -import com.google.common.collect.Ordering; +import static java.util.Map.Entry.comparingByKey; +import com.google.common.collect.Ordering; import java.io.File; import java.util.Collection; import java.util.Comparator; import java.util.Map; - import javax.annotation.Nullable; /** @@ -127,15 +127,6 @@ public class CommandFailureUtils { private CommandFailureUtils() {} // Prevent instantiation. - private static Comparator<Map.Entry<String, String>> mapEntryComparator = - new Comparator<Map.Entry<String, String>>() { - @Override - public int compare(Map.Entry<String, String> x, Map.Entry<String, String> y) { - // A map can never have two keys with the same value, so we only need to compare the keys. - return x.getKey().compareTo(y.getKey()); - } - }; - /** * Construct a string that describes the command. * Currently this returns a message of the form "foo bar baz", @@ -191,6 +182,8 @@ public class CommandFailureUtils { */ if (environment != null) { describeCommandImpl.describeCommandEnvPrefix(message); + // A map can never have two keys with the same value, so we only need to compare the keys. + Comparator<Map.Entry<String, String>> mapEntryComparator = comparingByKey(); for (Map.Entry<String, String> entry : Ordering.from(mapEntryComparator).sortedCopy(environment.entrySet())) { message.append(" "); diff --git a/src/main/java/com/google/devtools/build/lib/util/FileType.java b/src/main/java/com/google/devtools/build/lib/util/FileType.java index b984e98d70..2eef5afdbf 100644 --- a/src/main/java/com/google/devtools/build/lib/util/FileType.java +++ b/src/main/java/com/google/devtools/build/lib/util/FileType.java @@ -14,18 +14,15 @@ package com.google.devtools.build.lib.util; -import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.devtools.build.lib.vfs.Path; import com.google.devtools.build.lib.vfs.PathFragment; - import java.util.ArrayList; import java.util.Arrays; import java.util.List; - import javax.annotation.concurrent.Immutable; /** @@ -130,14 +127,6 @@ public abstract class FileType implements Predicate<String> { String getFilename(); } - public static final Function<HasFilename, String> TO_FILENAME = - new Function<HasFilename, String>() { - @Override - public String apply(HasFilename input) { - return input.getFilename(); - } - }; - /** * Checks whether an Iterable<? extends HasFileType> contains any of the specified file types. * @@ -167,32 +156,17 @@ public abstract class FileType implements Predicate<String> { private static <T extends HasFilename> Predicate<T> typeMatchingPredicateFor( final FileType matchingType) { - return new Predicate<T>() { - @Override - public boolean apply(T item) { - return matchingType.matches(item.getFilename()); - } - }; + return item -> matchingType.matches(item.getFilename()); } private static <T extends HasFilename> Predicate<T> typeMatchingPredicateFor( final FileTypeSet matchingTypes) { - return new Predicate<T>() { - @Override - public boolean apply(T item) { - return matchingTypes.matches(item.getFilename()); - } - }; + return item -> matchingTypes.matches(item.getFilename()); } private static <T extends HasFilename> Predicate<T> typeMatchingPredicateFrom( final Predicate<String> fileTypePredicate) { - return new Predicate<T>() { - @Override - public boolean apply(T item) { - return fileTypePredicate.apply(item.getFilename()); - } - }; + return item -> fileTypePredicate.apply(item.getFilename()); } /** diff --git a/src/main/java/com/google/devtools/build/lib/util/Pair.java b/src/main/java/com/google/devtools/build/lib/util/Pair.java index 91d04c62f1..943f8c97f2 100644 --- a/src/main/java/com/google/devtools/build/lib/util/Pair.java +++ b/src/main/java/com/google/devtools/build/lib/util/Pair.java @@ -13,11 +13,7 @@ // limitations under the License. package com.google.devtools.build.lib.util; -import com.google.common.base.Function; - -import java.util.Comparator; import java.util.Objects; - import javax.annotation.Nullable; /** @@ -85,40 +81,4 @@ public final class Pair<A, B> { int hash2 = second == null ? 0 : second.hashCode(); return 31 * hash1 + hash2; } - - /** - * A function that maps to the first element in a pair. - */ - public static <A, B> Function<Pair<A, B>, A> firstFunction() { - return new Function<Pair<A, B>, A>() { - @Override - public A apply(Pair<A, B> pair) { - return pair.first; - } - }; - } - - /** - * A function that maps to the second element in a pair. - */ - public static <A, B> Function<Pair<A, B>, B> secondFunction() { - return new Function<Pair<A, B>, B>() { - @Override - public B apply(Pair<A, B> pair) { - return pair.second; - } - }; - } - - /** - * A comparator that compares pairs by comparing the first element. - */ - public static <T extends Comparable<T>, B> Comparator<Pair<T, B>> compareByFirst() { - return new Comparator<Pair<T, B>>() { - @Override - public int compare(Pair<T, B> o1, Pair<T, B> o2) { - return o1.first.compareTo(o2.first); - } - }; - } } diff --git a/src/main/java/com/google/devtools/build/lib/util/StringCanonicalizer.java b/src/main/java/com/google/devtools/build/lib/util/StringCanonicalizer.java index 8a850972f0..18ac47a754 100644 --- a/src/main/java/com/google/devtools/build/lib/util/StringCanonicalizer.java +++ b/src/main/java/com/google/devtools/build/lib/util/StringCanonicalizer.java @@ -13,7 +13,6 @@ // limitations under the License. package com.google.devtools.build.lib.util; -import com.google.common.base.Function; import com.google.common.collect.Interner; import com.google.devtools.build.lib.concurrent.BlazeInterners; @@ -25,14 +24,6 @@ public final class StringCanonicalizer { private static final Interner<String> interner = BlazeInterners.newWeakInterner(); - /** Functional interface, for use with e.g. transform */ - public static final Function<String, String> INTERN = new Function<String, String>() { - @Override - public String apply(String x) { - return intern(x); - } - }; - private StringCanonicalizer() { } diff --git a/src/main/java/com/google/devtools/build/lib/util/StringUtil.java b/src/main/java/com/google/devtools/build/lib/util/StringUtil.java index ff9b61f826..567f26f17d 100644 --- a/src/main/java/com/google/devtools/build/lib/util/StringUtil.java +++ b/src/main/java/com/google/devtools/build/lib/util/StringUtil.java @@ -13,11 +13,9 @@ // limitations under the License. package com.google.devtools.build.lib.util; -import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.collect.Iterables; - import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; @@ -127,12 +125,7 @@ public class StringUtil { */ public static Iterable<String> append(Iterable<String> values, final String prefix, final String suffix) { - return Iterables.transform(values, new Function<String, String>() { - @Override - public String apply(String input) { - return prefix + input + suffix; - } - }); + return Iterables.transform(values, input -> prefix + input + suffix); } /** diff --git a/src/main/java/com/google/devtools/build/lib/vfs/FileSystemUtils.java b/src/main/java/com/google/devtools/build/lib/vfs/FileSystemUtils.java index 5b3bc1e717..698b671d04 100644 --- a/src/main/java/com/google/devtools/build/lib/vfs/FileSystemUtils.java +++ b/src/main/java/com/google/devtools/build/lib/vfs/FileSystemUtils.java @@ -981,15 +981,13 @@ public class FileSystemUtils { // (a) name the function, (b) put it in a box and (c) use List not array // because of the generic type. *sigh*. final List<Predicate<Path>> dumpFunction = new ArrayList<>(); - dumpFunction.add(new Predicate<Path>() { - @Override - public boolean apply(Path child) { + dumpFunction.add( + child -> { Path path = child; out.println(" " + path + " (" + path.toDebugString() + ")"); path.applyToChildren(dumpFunction.get(0)); return false; - } - }); + }); fs.getRootDirectory().applyToChildren(dumpFunction.get(0)); } diff --git a/src/main/java/com/google/devtools/build/lib/vfs/Path.java b/src/main/java/com/google/devtools/build/lib/vfs/Path.java index d5aa5eef85..b41589caae 100644 --- a/src/main/java/com/google/devtools/build/lib/vfs/Path.java +++ b/src/main/java/com/google/devtools/build/lib/vfs/Path.java @@ -13,9 +13,9 @@ // limitations under the License. package com.google.devtools.build.lib.vfs; +import static com.google.common.collect.ImmutableList.toImmutableList; + import com.google.common.base.Predicate; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; import com.google.devtools.build.lib.concurrent.ThreadSafety.ThreadSafe; import com.google.devtools.build.lib.util.Preconditions; import com.google.devtools.build.lib.util.StringCanonicalizer; @@ -505,7 +505,7 @@ public class Path implements Comparable<Path>, Serializable { */ public Collection<Path> getDirectoryEntries(Predicate<? super Path> predicate) throws IOException, FileNotFoundException { - return ImmutableList.<Path>copyOf(Iterables.filter(getDirectoryEntries(), predicate)); + return getDirectoryEntries().stream().filter(predicate).collect(toImmutableList()); } /** diff --git a/src/main/java/com/google/devtools/build/lib/vfs/PathFragment.java b/src/main/java/com/google/devtools/build/lib/vfs/PathFragment.java index caad724f83..3f5ba0ef1b 100644 --- a/src/main/java/com/google/devtools/build/lib/vfs/PathFragment.java +++ b/src/main/java/com/google/devtools/build/lib/vfs/PathFragment.java @@ -13,8 +13,9 @@ // limitations under the License. package com.google.devtools.build.lib.vfs; +import static com.google.common.collect.ImmutableSet.toImmutableSet; + import com.google.common.base.Function; -import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; @@ -58,29 +59,8 @@ public abstract class PathFragment implements Comparable<PathFragment>, Serializ /** An empty path fragment. */ public static final PathFragment EMPTY_FRAGMENT = create(""); - public static final Function<String, PathFragment> TO_PATH_FRAGMENT = - new Function<String, PathFragment>() { - @Override - public PathFragment apply(String str) { - return create(str); - } - }; - - public static final Predicate<PathFragment> IS_ABSOLUTE = - new Predicate<PathFragment>() { - @Override - public boolean apply(PathFragment input) { - return input.isAbsolute(); - } - }; - - private static final Function<PathFragment, String> TO_SAFE_PATH_STRING = - new Function<PathFragment, String>() { - @Override - public String apply(PathFragment path) { - return path.getSafePathString(); - } - }; + // TODO(laurentlb): Inline this + public static final Function<String, PathFragment> TO_PATH_FRAGMENT = PathFragment::create; /** * A helper object for manipulating the various internal {@link PathFragment} implementations. @@ -332,22 +312,16 @@ public abstract class PathFragment implements Comparable<PathFragment>, Serializ * {@code fragments}. */ public static Iterable<String> safePathStrings(Iterable<PathFragment> fragments) { - return Iterables.transform(fragments, TO_SAFE_PATH_STRING); + return Iterables.transform(fragments, PathFragment::getSafePathString); } /** Returns the subset of {@code paths} that start with {@code startingWithPath}. */ - public static ImmutableSet<PathFragment> filterPathsStartingWith(Set<PathFragment> paths, - PathFragment startingWithPath) { - return ImmutableSet.copyOf(Iterables.filter(paths, startsWithPredicate(startingWithPath))); - } - - public static Predicate<PathFragment> startsWithPredicate(final PathFragment prefix) { - return new Predicate<PathFragment>() { - @Override - public boolean apply(PathFragment pathFragment) { - return pathFragment.startsWith(prefix); - } - }; + public static ImmutableSet<PathFragment> filterPathsStartingWith( + Set<PathFragment> paths, PathFragment startingWithPath) { + return paths + .stream() + .filter(pathFragment -> pathFragment.startsWith(startingWithPath)) + .collect(toImmutableSet()); } /** diff --git a/src/main/java/com/google/devtools/build/lib/vfs/UnixGlob.java b/src/main/java/com/google/devtools/build/lib/vfs/UnixGlob.java index 771b11a925..378f7275a3 100644 --- a/src/main/java/com/google/devtools/build/lib/vfs/UnixGlob.java +++ b/src/main/java/com/google/devtools/build/lib/vfs/UnixGlob.java @@ -615,18 +615,16 @@ public final class UnixGlob { totalOps.incrementAndGet(); pendingOps.incrementAndGet(); - Runnable wrapped = new Runnable() { - @Override - public void run() { - try { - if (!canceled && failure.get() == null) { - r.run(); + Runnable wrapped = + () -> { + try { + if (!canceled && failure.get() == null) { + r.run(); + } + } finally { + decrementAndCheckDone(); } - } finally { - decrementAndCheckDone(); - } - } - }; + }; if (executor == null) { wrapped.run(); diff --git a/src/main/java/com/google/devtools/build/lib/vfs/ZipFileSystem.java b/src/main/java/com/google/devtools/build/lib/vfs/ZipFileSystem.java index 353a684a82..5419f7a1f8 100644 --- a/src/main/java/com/google/devtools/build/lib/vfs/ZipFileSystem.java +++ b/src/main/java/com/google/devtools/build/lib/vfs/ZipFileSystem.java @@ -13,7 +13,6 @@ // limitations under the License. package com.google.devtools.build.lib.vfs; -import com.google.common.base.Predicate; import com.google.devtools.build.lib.concurrent.ThreadSafety.ThreadSafe; import com.google.devtools.build.lib.util.Preconditions; import com.google.devtools.build.lib.vfs.Path.PathFactory; @@ -205,15 +204,14 @@ public class ZipFileSystem extends ReadonlyFileSystem implements Closeable { Preconditions.checkState(open); zipEntryNonNull(path); final Collection<Path> result = new ArrayList<>(); - ((ZipPath) path).applyToChildren(new Predicate<Path>() { - @Override - public boolean apply(Path child) { - if (zipEntry(child) != null) { - result.add(child); - } - return true; - } - }); + ((ZipPath) path) + .applyToChildren( + child -> { + if (zipEntry(child) != null) { + result.add(child); + } + return true; + }); return result; } diff --git a/src/main/java/com/google/devtools/build/lib/vfs/inmemoryfs/InMemoryDirectoryInfo.java b/src/main/java/com/google/devtools/build/lib/vfs/inmemoryfs/InMemoryDirectoryInfo.java index 35a745a7b9..f47eb72a3c 100644 --- a/src/main/java/com/google/devtools/build/lib/vfs/inmemoryfs/InMemoryDirectoryInfo.java +++ b/src/main/java/com/google/devtools/build/lib/vfs/inmemoryfs/InMemoryDirectoryInfo.java @@ -13,7 +13,6 @@ // limitations under the License. package com.google.devtools.build.lib.vfs.inmemoryfs; -import com.google.common.base.Function; import com.google.common.collect.Collections2; import com.google.devtools.build.lib.concurrent.ThreadSafety; import com.google.devtools.build.lib.concurrent.ThreadSafety.ThreadSafe; @@ -29,13 +28,6 @@ import java.util.concurrent.ConcurrentMap; */ @ThreadSafe class InMemoryDirectoryInfo extends InMemoryContentInfo { - private static final Function<InMemoryFileName, String> FILENAME_TO_STRING = - new Function<InMemoryFileName, String>() { - @Override - public String apply(InMemoryFileName inMemoryFileName) { - return inMemoryFileName.value; - } - }; private final ConcurrentMap<InMemoryFileName, InMemoryContentInfo> directoryContent = new ConcurrentHashMap<>(); @@ -88,7 +80,8 @@ class InMemoryDirectoryInfo extends InMemoryContentInfo { * changed later. */ Collection<String> getAllChildren() { - return Collections2.transform(directoryContent.keySet(), FILENAME_TO_STRING); + return Collections2.transform( + directoryContent.keySet(), inMemoryFileName -> inMemoryFileName.value); } @Override diff --git a/src/main/java/com/google/devtools/build/lib/windows/WindowsFileSystem.java b/src/main/java/com/google/devtools/build/lib/windows/WindowsFileSystem.java index 893a563c3e..e1eb08fc3b 100644 --- a/src/main/java/com/google/devtools/build/lib/windows/WindowsFileSystem.java +++ b/src/main/java/com/google/devtools/build/lib/windows/WindowsFileSystem.java @@ -69,19 +69,15 @@ public class WindowsFileSystem extends JavaIoFileSystem { /** Resolves DOS-style, shortened path names, returning the last segment's long form. */ private static final Function<String, String> WINDOWS_SHORT_PATH_RESOLVER = - new Function<String, String>() { - @Override - @Nullable - public String apply(String path) { - try { - // Since Path objects are created hierarchically, we know for sure that every segment of - // the path, except the last one, is already canonicalized, so we can return just that. - // Plus the returned value is passed to Path.getChild so we must not return a full - // path here. - return PathFragment.create(WindowsFileOperations.getLongPath(path)).getBaseName(); - } catch (IOException e) { - return null; - } + path -> { + try { + // Since Path objects are created hierarchically, we know for sure that every segment of + // the path, except the last one, is already canonicalized, so we can return just that. + // Plus the returned value is passed to Path.getChild so we must not return a full + // path here. + return PathFragment.create(WindowsFileOperations.getLongPath(path)).getBaseName(); + } catch (IOException e) { + return null; } }; diff --git a/src/main/java/com/google/devtools/build/lib/windows/WindowsSubprocess.java b/src/main/java/com/google/devtools/build/lib/windows/WindowsSubprocess.java index 16f05e47e6..0aea491bd3 100644 --- a/src/main/java/com/google/devtools/build/lib/windows/WindowsSubprocess.java +++ b/src/main/java/com/google/devtools/build/lib/windows/WindowsSubprocess.java @@ -145,15 +145,8 @@ public class WindowsSubprocess implements Subprocess { waitLatch = new CountDownLatch(1); // Every Windows process we start consumes a thread here. This is suboptimal, but seems to be // the sanest way to reconcile WaitForMultipleObjects() and Java-style interruption. - @SuppressWarnings("unused") - Future<?> possiblyIgnoredError = - WAITER_POOL.submit( - new Runnable() { - @Override - public void run() { - waiterThreadFunc(); - } - }); + @SuppressWarnings("unused") + Future<?> possiblyIgnoredError = WAITER_POOL.submit(this::waiterThreadFunc); } private void waiterThreadFunc() { |