aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/main/java/com/google/devtools/build/lib/analysis/config/BuildConfigurationCollection.java
blob: 6fada4c2261277a1aa41a7c54c57fa0c5323f45c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
// Copyright 2014 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.config;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ListMultimap;
import com.google.devtools.build.lib.concurrent.ThreadSafety.ThreadSafe;
import com.google.devtools.build.lib.packages.Attribute;
import com.google.devtools.build.lib.packages.Attribute.SplitTransition;
import com.google.devtools.build.lib.packages.Attribute.Transition;
import com.google.devtools.build.lib.packages.InputFile;
import com.google.devtools.build.lib.packages.PackageGroup;
import com.google.devtools.build.lib.packages.Rule;
import com.google.devtools.build.lib.packages.Target;

import java.io.PrintStream;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * The primary container for all main {@link BuildConfiguration} instances,
 * currently "target", "data", and "host".
 *
 * <p>The target configuration is used for all targets specified on the command
 * line. Data dependencies of targets in the target configuration use the data
 * configuration instead.
 *
 * <p>The host configuration is used for tools that are executed during the
 * build, e. g, compilers.
 *
 * <p>The "related" configurations are also contained in this class.
 */
@ThreadSafe
public final class BuildConfigurationCollection {
  private final ImmutableList<BuildConfiguration> targetConfigurations;
  private final BuildConfiguration hostConfiguration;

  public BuildConfigurationCollection(List<BuildConfiguration> targetConfigurations,
      BuildConfiguration hostConfiguration)
      throws InvalidConfigurationException {
    this.targetConfigurations = ImmutableList.copyOf(targetConfigurations);
    this.hostConfiguration = hostConfiguration;

    // Except for the host configuration (which may be identical across target configs), the other
    // configurations must all have different cache keys or we will end up with problems.
    HashMap<String, BuildConfiguration> cacheKeyConflictDetector = new HashMap<>();
    for (BuildConfiguration config : getAllConfigurations()) {
      String cacheKey = config.checksum();
      if (cacheKeyConflictDetector.containsKey(cacheKey)) {
        throw new InvalidConfigurationException("Conflicting configurations: " + config + " & "
            + cacheKeyConflictDetector.get(cacheKey));
      }
      cacheKeyConflictDetector.put(cacheKey, config);
    }
  }

  public static BuildConfiguration configureTopLevelTarget(BuildConfiguration topLevelConfiguration,
      Target toTarget) {
    if (toTarget instanceof InputFile || toTarget instanceof PackageGroup) {
      return null;
    }
    return topLevelConfiguration.getTransitions().toplevelConfigurationHook(toTarget);
  }

  public ImmutableList<BuildConfiguration> getTargetConfigurations() {
    return targetConfigurations;
  }

  /**
   * Returns the host configuration for this collection.
   *
   * <p>Don't use this method. It's limited in that it assumes a single host configuration for
   * the entire collection. This may not be true in the future and more flexible interfaces based
   * on dynamic configurations will likely supplant this interface anyway. Its main utility is
   * to keep Bazel working while dynamic configuration progress is under way.
   */
  public BuildConfiguration getHostConfiguration() {
    return hostConfiguration;
  }

  /**
   * Returns all configurations that can be reached from the target configuration through any kind
   * of configuration transition.
   */
  public Collection<BuildConfiguration> getAllConfigurations() {
    Set<BuildConfiguration> result = new LinkedHashSet<>();
    for (BuildConfiguration config : targetConfigurations) {
      result.addAll(config.getAllReachableConfigurations());
    }
    return result;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj) {
      return true;
    }
    if (!(obj instanceof BuildConfigurationCollection)) {
      return false;
    }
    BuildConfigurationCollection that = (BuildConfigurationCollection) obj;
    return this.targetConfigurations.equals(that.targetConfigurations);
  }

  @Override
  public int hashCode() {
    return targetConfigurations.hashCode();
  }

  /**
   * Prints the configuration graph in dot format to the given print stream. This is only intended
   * for debugging.
   */
  public void dumpAsDotGraph(PrintStream out) {
    out.println("digraph g {");
    out.println("  ratio = 0.3;");
    for (BuildConfiguration config : getAllConfigurations()) {
      String from = config.checksum();
      for (Map.Entry<? extends Transition, ConfigurationHolder> entry :
          config.getTransitions().getTransitionTable().entrySet()) {
        BuildConfiguration toConfig = entry.getValue().getConfiguration();
        if (toConfig == config) {
          continue;
        }
        String to = toConfig == null ? "ERROR" : toConfig.checksum();
        out.println("  \"" + from + "\" -> \"" + to + "\" [label=\"" + entry.getKey() + "\"]");
      }
    }
    out.println("}");
  }

  /**
   * The outgoing transitions for a build configuration.
   */
  public abstract static class Transitions implements Serializable {
    protected final BuildConfiguration configuration;

    /**
     * Look up table for the configuration transitions, i.e., HOST, DATA, etc.
     */
    private final Map<? extends Transition, ConfigurationHolder> transitionTable;

    // TODO(bazel-team): Consider merging transitionTable into this.
    private final ListMultimap<? super SplitTransition<?>, BuildConfiguration> splitTransitionTable;

    public Transitions(BuildConfiguration configuration,
        Map<? extends Transition, ConfigurationHolder> transitionTable,
        ListMultimap<? extends SplitTransition<?>, BuildConfiguration> splitTransitionTable) {
      this.configuration = configuration;
      this.transitionTable = ImmutableMap.copyOf(transitionTable);
      this.splitTransitionTable = ImmutableListMultimap.copyOf(splitTransitionTable);
    }

    public Map<? extends Transition, ConfigurationHolder> getTransitionTable() {
      return transitionTable;
    }

    public ListMultimap<? super SplitTransition<?>, BuildConfiguration> getSplitTransitionTable() {
      return splitTransitionTable;
    }

    public List<BuildConfiguration> getSplitConfigurations(SplitTransition<?> transition) {
      if (splitTransitionTable.containsKey(transition)) {
        return splitTransitionTable.get(transition);
      } else {
        Preconditions.checkState(transition.defaultsToSelf());
        return ImmutableList.of(configuration);
      }
    }

    /**
     * Adds all configurations that are directly reachable from this configuration through
     * any kind of configuration transition.
     */
    public void addDirectlyReachableConfigurations(Collection<BuildConfiguration> queue) {
      for (ConfigurationHolder holder : transitionTable.values()) {
        if (holder.configuration != null) {
          queue.add(holder.configuration);
        }
      }
      queue.addAll(splitTransitionTable.values());
    }

    /**
     * Artifacts need an owner in Skyframe. By default it's the same configuration as what
     * the configured target has, but it can be overridden if necessary.
     *
     * @return the artifact owner configuration
     */
    public BuildConfiguration getArtifactOwnerConfiguration() {
      return configuration;
    }

    /**
     * Returns the new configuration after traversing a dependency edge with a
     * given configuration transition.
     *
     * <p>Only used for static configuration builds.
     *
     * @param configurationTransition the configuration transition
     * @return the new configuration
     */
    public BuildConfiguration getStaticConfiguration(Transition configurationTransition) {
      Preconditions.checkState(!configuration.useDynamicConfigurations());
      ConfigurationHolder holder = transitionTable.get(configurationTransition);
      if (holder == null && configurationTransition.defaultsToSelf()) {
        return configuration;
      }
      return holder.configuration;
    }

    /**
     * Translates a static configuration {@link Transition} reference into the corresponding
     * dynamic configuration transition.
     *
     * <p>The difference is that with static configurations, the transition just models a desired
     * type of transition that subsequently gets linked to a pre-built global configuration through
     * custom logic in {@link BuildConfigurationCollection.Transitions} and
     * {@link com.google.devtools.build.lib.analysis.ConfigurationCollectionFactory}.
     *
     * <p>With dynamic configurations, the transition directly embeds the semantics, e.g.
     * it includes not just a name but also the logic of how it should transform its input
     * configuration.
     *
     * <p>This is a connecting method meant to keep the two models in sync for the current time
     * in which they must co-exist. Once dynamic configurations are production-ready, we'll remove
     * the static configuration code entirely.
     */
    protected Transition getDynamicTransition(Transition transition) {
      Preconditions.checkState(configuration.useDynamicConfigurations());
      if (transition == Attribute.ConfigurationTransition.NONE) {
        return transition;
      } else if (transition == Attribute.ConfigurationTransition.NULL) {
        return transition;
      } else if (transition == Attribute.ConfigurationTransition.HOST) {
        return HostTransition.INSTANCE;
      } else {
        throw new UnsupportedOperationException("No dynamic mapping for " + transition.toString());
      }
    }

    /**
     * Arbitrary configuration transitions can be implemented by overriding this hook.
     */
    @SuppressWarnings("unused")
    public void configurationHook(Rule fromTarget, Attribute attribute, Target toTarget,
        BuildConfiguration.TransitionApplier transitionApplier) {
    }

    /**
     * Associating configurations to top-level targets can be implemented by overriding this hook.
     */
    @SuppressWarnings("unused")
    public BuildConfiguration toplevelConfigurationHook(Target toTarget) {
      return configuration;
    }
  }

  /**
   * A holder class for {@link BuildConfiguration} instances that allows {@code null} values,
   * because none of the Table implementations allow them.
   */
  public static final class ConfigurationHolder implements Serializable {
    private final BuildConfiguration configuration;

    public ConfigurationHolder(BuildConfiguration configuration) {
      this.configuration = configuration;
    }

    public BuildConfiguration getConfiguration() {
      return configuration;
    }

    @Override
    public int hashCode() {
      return configuration == null ? 0 : configuration.hashCode();
    }

    @Override
    public boolean equals(Object o) {
      if (o == this) {
        return true;
      }
      if (!(o instanceof ConfigurationHolder)) {
        return false;
      }
      return Objects.equals(configuration, ((ConfigurationHolder) o).configuration);
    }
  }
}