Create UnloadedToolchainContexts for exec groups and make exec_group-related toolchains a dependency of their targets. Use a new helper class ToolchainCollection to handle the default/unnamed execution group.

PiperOrigin-RevId: 305695378
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/DependencyResolver.java b/src/main/java/com/google/devtools/build/lib/analysis/DependencyResolver.java
index 9d93523..54394c5 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/DependencyResolver.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/DependencyResolver.java
@@ -189,7 +189,7 @@
    *     This is needed to support {@link LateBoundDefault#useHostConfiguration()}.
    * @param aspect the aspect applied to this target (if any)
    * @param configConditions resolver for config_setting labels
-   * @param toolchainContext the toolchain context for this target
+   * @param toolchainContexts the toolchain contexts for this target
    * @param trimmingTransitionFactory the transition factory used to trim rules (note: this is a
    *     temporary feature; see the corresponding methods in ConfiguredRuleClassProvider)
    * @return a mapping of each attribute in this rule or aspects to its dependent nodes
@@ -199,7 +199,7 @@
       BuildConfiguration hostConfig,
       @Nullable Aspect aspect,
       ImmutableMap<Label, ConfigMatchingProvider> configConditions,
-      @Nullable ToolchainContext toolchainContext,
+      @Nullable ToolchainCollection<ToolchainContext> toolchainContexts,
       @Nullable TransitionFactory<Rule> trimmingTransitionFactory)
       throws EvalException, InterruptedException, InconsistentAspectOrderException {
     NestedSetBuilder<Cause> rootCauses = NestedSetBuilder.stableOrder();
@@ -209,7 +209,7 @@
             hostConfig,
             aspect != null ? ImmutableList.of(aspect) : ImmutableList.<Aspect>of(),
             configConditions,
-            toolchainContext,
+            toolchainContexts,
             rootCauses,
             trimmingTransitionFactory);
     if (!rootCauses.isEmpty()) {
@@ -243,7 +243,7 @@
    *     This is needed to support {@link LateBoundDefault#useHostConfiguration()}.
    * @param aspects the aspects applied to this target (if any)
    * @param configConditions resolver for config_setting labels
-   * @param toolchainContext the toolchain context for this target
+   * @param toolchainContexts the toolchain contexts for this target
    * @param trimmingTransitionFactory the transition factory used to trim rules (note: this is a
    *     temporary feature; see the corresponding methods in ConfiguredRuleClassProvider)
    * @param rootCauses collector for dep labels that can't be (loading phase) loaded
@@ -254,7 +254,7 @@
       BuildConfiguration hostConfig,
       Iterable<Aspect> aspects,
       ImmutableMap<Label, ConfigMatchingProvider> configConditions,
-      @Nullable ToolchainContext toolchainContext,
+      @Nullable ToolchainCollection<ToolchainContext> toolchainContexts,
       NestedSetBuilder<Cause> rootCauses,
       @Nullable TransitionFactory<Rule> trimmingTransitionFactory)
       throws EvalException, InterruptedException, InconsistentAspectOrderException {
@@ -279,7 +279,7 @@
     } else if (target instanceof Rule) {
       fromRule = (Rule) target;
       attributeMap = ConfiguredAttributeMapper.of(fromRule, configConditions);
-      visitRule(node, hostConfig, aspects, attributeMap, toolchainContext, outgoingLabels);
+      visitRule(node, hostConfig, aspects, attributeMap, toolchainContexts, outgoingLabels);
     } else if (target instanceof PackageGroup) {
       outgoingLabels.putAll(VISIBILITY_DEPENDENCY, ((PackageGroup) target).getIncludes());
     } else {
@@ -294,7 +294,7 @@
 
     OrderedSetMultimap<DependencyKind, PartiallyResolvedDependency> partiallyResolvedDeps =
         partiallyResolveDependencies(
-            outgoingLabels, fromRule, attributeMap, toolchainContext, aspects);
+            outgoingLabels, fromRule, attributeMap, toolchainContexts, aspects);
 
     OrderedSetMultimap<DependencyKind, Dependency> outgoingEdges =
         fullyResolveDependencies(
@@ -316,7 +316,7 @@
           OrderedSetMultimap<DependencyKind, Label> outgoingLabels,
           @Nullable Rule fromRule,
           ConfiguredAttributeMapper attributeMap,
-          @Nullable ToolchainContext toolchainContext,
+          @Nullable ToolchainCollection<ToolchainContext> toolchainContexts,
           Iterable<Aspect> aspects) {
     OrderedSetMultimap<DependencyKind, PartiallyResolvedDependency> partiallyResolvedDeps =
         OrderedSetMultimap.create();
@@ -361,8 +361,12 @@
           aspects, attribute.getName(), entry.getKey().getOwningAspect(), propagatingAspects);
 
       Label executionPlatformLabel = null;
-      if (toolchainContext != null && toolchainContext.executionPlatform() != null) {
-        executionPlatformLabel = toolchainContext.executionPlatform().label();
+      // TODO(b/151742236): support transitions to other ({@link ExecGroup defined}) execution
+      // platforms
+      if (toolchainContexts != null
+          && toolchainContexts.getDefaultToolchainContext().executionPlatform() != null) {
+        executionPlatformLabel =
+            toolchainContexts.getDefaultToolchainContext().executionPlatform().label();
       }
       AttributeTransitionData attributeTransitionData =
           AttributeTransitionData.builder()
@@ -426,7 +430,7 @@
       BuildConfiguration hostConfig,
       Iterable<Aspect> aspects,
       ConfiguredAttributeMapper attributeMap,
-      @Nullable ToolchainContext toolchainContext,
+      @Nullable ToolchainCollection<ToolchainContext> toolchainContexts,
       OrderedSetMultimap<DependencyKind, Label> outgoingLabels)
       throws EvalException {
     Preconditions.checkArgument(node.getTarget() instanceof Rule, node);
@@ -479,8 +483,8 @@
           rule.getPackage().getDefaultRestrictedTo());
     }
 
-    if (toolchainContext != null) {
-      outgoingLabels.putAll(TOOLCHAIN_DEPENDENCY, toolchainContext.resolvedToolchainLabels());
+    if (toolchainContexts != null) {
+      outgoingLabels.putAll(TOOLCHAIN_DEPENDENCY, toolchainContexts.getRequiredToolchains());
     }
 
     if (!rule.isAttributeValueExplicitlySpecified(RuleClass.APPLICABLE_LICENSES_ATTR)) {
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/ToolchainCollection.java b/src/main/java/com/google/devtools/build/lib/analysis/ToolchainCollection.java
new file mode 100644
index 0000000..1f62133
--- /dev/null
+++ b/src/main/java/com/google/devtools/build/lib/analysis/ToolchainCollection.java
@@ -0,0 +1,88 @@
+// Copyright 2020 The Bazel Authors. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//    http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+package com.google.devtools.build.lib.analysis;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.devtools.build.lib.cmdline.Label;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * A wrapper class for a map of exec_group names to their relevent ToolchainContext.
+ *
+ * @param <T> any class that extends ToolchainCollection so this can be used, e.g., both before and
+ *     after toolchain resolution.
+ */
+public class ToolchainCollection<T extends ToolchainContext> {
+  private static final String DEFAULT_EXEC_GROUP_NAME = "default_exec_group";
+
+  /** A map of execution group names to toolchain contexts. */
+  private final ImmutableMap<String, T> toolchainContexts;
+
+  private ToolchainCollection(Map<String, T> contexts) {
+    Preconditions.checkArgument(contexts.containsKey(DEFAULT_EXEC_GROUP_NAME));
+    toolchainContexts = ImmutableMap.copyOf(contexts);
+  }
+
+  /** Builder for ToolchainCollection. */
+  public static class Builder<T extends ToolchainContext> {
+    private final Map<String, T> toolchainContexts = new HashMap<>();
+
+    public ToolchainCollection<T> build() {
+      return new ToolchainCollection<>(toolchainContexts);
+    }
+
+    public void addContext(String execGroup, T context) {
+      Preconditions.checkArgument(
+          !toolchainContexts.containsKey(execGroup),
+          "Duplicate add of '%s' exec group to toolchain collection.",
+          execGroup);
+      toolchainContexts.put(execGroup, context);
+    }
+
+    public Builder<T> addDefaultContext(T context) {
+      addContext(DEFAULT_EXEC_GROUP_NAME, context);
+      return this;
+    }
+  }
+
+  public T getDefaultToolchainContext() {
+    return toolchainContexts.get(DEFAULT_EXEC_GROUP_NAME);
+  }
+
+  public T getToolchainContext(String execGroup) {
+    return toolchainContexts.get(execGroup);
+  }
+
+  public ImmutableSet<Label> getRequiredToolchains() {
+    Set<Label> requiredToolchains = new HashSet<>();
+    for (T context : toolchainContexts.values()) {
+      requiredToolchains.addAll(context.resolvedToolchainLabels());
+    }
+    return ImmutableSet.copyOf(requiredToolchains);
+  }
+
+  public ToolchainCollection<ToolchainContext> asToolchainContexts() {
+    return new ToolchainCollection<>(ImmutableMap.copyOf(toolchainContexts));
+  }
+
+  public Collection<T> getContexts() {
+    return toolchainContexts.values();
+  }
+}