-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
RuleContext.java
2490 lines (2228 loc) · 98 KB
/
RuleContext.java
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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;
import static com.google.devtools.build.lib.analysis.ToolchainCollection.DEFAULT_EXEC_GROUP_NAME;
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.Predicates;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
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.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Sets;
import com.google.devtools.build.lib.actions.ActionAnalysisMetadata;
import com.google.devtools.build.lib.actions.ActionKeyContext;
import com.google.devtools.build.lib.actions.ActionLookupKey;
import com.google.devtools.build.lib.actions.ActionOwner;
import com.google.devtools.build.lib.actions.ActionRegistry;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.Artifact.SpecialArtifact;
import com.google.devtools.build.lib.actions.ArtifactRoot;
import com.google.devtools.build.lib.analysis.AliasProvider.TargetMode;
import com.google.devtools.build.lib.analysis.actions.ActionConstructionContext;
import com.google.devtools.build.lib.analysis.buildinfo.BuildInfoKey;
import com.google.devtools.build.lib.analysis.config.BuildConfiguration;
import com.google.devtools.build.lib.analysis.config.ConfigMatchingProvider;
import com.google.devtools.build.lib.analysis.config.CoreOptions;
import com.google.devtools.build.lib.analysis.config.CoreOptions.IncludeConfigFragmentsEnum;
import com.google.devtools.build.lib.analysis.config.Fragment;
import com.google.devtools.build.lib.analysis.config.FragmentCollection;
import com.google.devtools.build.lib.analysis.config.transitions.ConfigurationTransition;
import com.google.devtools.build.lib.analysis.config.transitions.NoTransition;
import com.google.devtools.build.lib.analysis.constraints.ConstraintSemantics;
import com.google.devtools.build.lib.analysis.constraints.RuleContextConstraintSemantics;
import com.google.devtools.build.lib.analysis.platform.ConstraintValueInfo;
import com.google.devtools.build.lib.analysis.platform.PlatformInfo;
import com.google.devtools.build.lib.analysis.stringtemplate.TemplateContext;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.cmdline.RepositoryName;
import com.google.devtools.build.lib.collect.ImmutableSortedKeyListMultimap;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.events.ExtendedEventHandler.Postable;
import com.google.devtools.build.lib.packages.Aspect;
import com.google.devtools.build.lib.packages.AspectDescriptor;
import com.google.devtools.build.lib.packages.Attribute;
import com.google.devtools.build.lib.packages.AttributeMap;
import com.google.devtools.build.lib.packages.BazelStarlarkContext;
import com.google.devtools.build.lib.packages.BuildType;
import com.google.devtools.build.lib.packages.BuiltinProvider;
import com.google.devtools.build.lib.packages.ConfigurationFragmentPolicy;
import com.google.devtools.build.lib.packages.ConfiguredAttributeMapper;
import com.google.devtools.build.lib.packages.FileTarget;
import com.google.devtools.build.lib.packages.FilesetEntry;
import com.google.devtools.build.lib.packages.ImplicitOutputsFunction;
import com.google.devtools.build.lib.packages.Info;
import com.google.devtools.build.lib.packages.InputFile;
import com.google.devtools.build.lib.packages.OutputFile;
import com.google.devtools.build.lib.packages.PackageSpecification.PackageGroupContents;
import com.google.devtools.build.lib.packages.RawAttributeMapper;
import com.google.devtools.build.lib.packages.RequiredProviders;
import com.google.devtools.build.lib.packages.Rule;
import com.google.devtools.build.lib.packages.RuleClass;
import com.google.devtools.build.lib.packages.SymbolGenerator;
import com.google.devtools.build.lib.packages.Target;
import com.google.devtools.build.lib.packages.TargetUtils;
import com.google.devtools.build.lib.packages.Type;
import com.google.devtools.build.lib.packages.Type.LabelClass;
import com.google.devtools.build.lib.packages.semantics.BuildLanguageOptions;
import com.google.devtools.build.lib.server.FailureDetails.Analysis;
import com.google.devtools.build.lib.server.FailureDetails.Analysis.Code;
import com.google.devtools.build.lib.server.FailureDetails.FailureDetail;
import com.google.devtools.build.lib.skyframe.ConfiguredTargetAndData;
import com.google.devtools.build.lib.skyframe.SaneAnalysisException;
import com.google.devtools.build.lib.util.DetailedExitCode;
import com.google.devtools.build.lib.util.FileTypeSet;
import com.google.devtools.build.lib.util.OS;
import com.google.devtools.build.lib.util.OrderedSetMultimap;
import com.google.devtools.build.lib.util.StringUtil;
import com.google.devtools.build.lib.vfs.FileSystemUtils;
import com.google.devtools.build.lib.vfs.PathFragment;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import net.starlark.java.eval.EvalException;
import net.starlark.java.eval.Mutability;
import net.starlark.java.eval.StarlarkSemantics;
import net.starlark.java.eval.StarlarkThread;
import net.starlark.java.syntax.Location;
/**
* The totality of data available during the analysis of a rule.
*
* <p>These objects should not outlast the analysis phase. Do not pass them to {@link
* com.google.devtools.build.lib.actions.Action} objects or other persistent objects. There are
* internal tests to ensure that RuleContext objects are not persisted that check the name of this
* class, so update those tests if you change this class's name.
*
* @see com.google.devtools.build.lib.analysis.RuleConfiguredTargetFactory
*/
public final class RuleContext extends TargetContext
implements ActionConstructionContext, ActionRegistry, RuleErrorConsumer, AutoCloseable {
public boolean isAllowTagsPropagation() {
return starlarkSemantics.getBool(BuildLanguageOptions.EXPERIMENTAL_ALLOW_TAGS_PROPAGATION);
}
/** Custom dependency validation logic. */
public interface PrerequisiteValidator {
/**
* Checks whether the rule in {@code contextBuilder} is allowed to depend on {@code
* prerequisite} through the attribute {@code attribute}.
*
* <p>Can be used for enforcing any organization-specific policies about the layout of the
* workspace.
*/
void validate(
Builder contextBuilder, ConfiguredTargetAndData prerequisite, Attribute attribute);
}
/** The configured version of FilesetEntry. */
@Immutable
public static final class ConfiguredFilesetEntry {
private final FilesetEntry entry;
private final TransitiveInfoCollection src;
private final ImmutableList<TransitiveInfoCollection> files;
ConfiguredFilesetEntry(FilesetEntry entry, TransitiveInfoCollection src) {
this.entry = entry;
this.src = src;
this.files = null;
}
ConfiguredFilesetEntry(FilesetEntry entry, ImmutableList<TransitiveInfoCollection> files) {
this.entry = entry;
this.src = null;
this.files = files;
}
public FilesetEntry getEntry() {
return entry;
}
public TransitiveInfoCollection getSrc() {
return src;
}
/**
* Targets from FilesetEntry.files, or null if the user omitted it.
*/
@Nullable
public ImmutableList<TransitiveInfoCollection> getFiles() {
return files;
}
}
private static final String HOST_CONFIGURATION_PROGRESS_TAG = "for host";
private final Rule rule;
/**
* A list of all aspects applied to the target. If this <code>RuleContext</code>
* is for a rule implementation, <code>aspects</code> is an empty list.
*
* Otherwise, the last aspect in <code>aspects</code> list is the aspect which
* this <code>RuleCointext</code> is for.
*/
private final ImmutableList<Aspect> aspects;
private final ImmutableList<AspectDescriptor> aspectDescriptors;
private final ListMultimap<String, ConfiguredTargetAndData> targetMap;
private final ListMultimap<String, ConfiguredFilesetEntry> filesetEntryMap;
private final ImmutableMap<Label, ConfigMatchingProvider> configConditions;
private final AspectAwareAttributeMapper attributes;
private final ImmutableSet<String> enabledFeatures;
private final ImmutableSet<String> disabledFeatures;
private final String ruleClassNameForLogging;
private final BuildConfiguration hostConfiguration;
private final ConfigurationFragmentPolicy configurationFragmentPolicy;
private final ImmutableList<Class<? extends Fragment>> universalFragments;
private final RuleErrorConsumer reporter;
@Nullable private final ToolchainCollection<ResolvedToolchainContext> toolchainContexts;
private final ConstraintSemantics<RuleContext> constraintSemantics;
private final ImmutableSet<String> requiredConfigFragments;
private final List<Expander> makeVariableExpanders = new ArrayList<>();
private final ImmutableMap<String, ImmutableMap<String, String>> execProperties;
/** Map of exec group names to ActionOwners. */
private final Map<String, ActionOwner> actionOwners = new HashMap<>();
private final SymbolGenerator<ActionLookupKey> actionOwnerSymbolGenerator;
/* lazily computed cache for Make variables, computed from the above. See get... method */
private transient ConfigurationMakeVariableContext configurationMakeVariableContext = null;
/**
* The StarlarkSemantics to use for rule analysis. Should be the same as what's reported by the
* AnalysisEnvironment, but saving it here is more convenient since {@link
* AnalysisEnvironment#getStarlarkSemantics()} can throw InterruptedException.
*/
private final StarlarkSemantics starlarkSemantics;
/**
* Thread used for any Starlark evaluation during analysis, e.g. rule implementation function for
* a Starlark-defined rule, or Starlarkified helper logic for native rules that have been
* partially migrated to {@code @_builtins}.
*/
private final StarlarkThread starlarkThread;
private RuleContext(
Builder builder,
AttributeMap attributes,
ListMultimap<String, ConfiguredTargetAndData> targetMap,
ListMultimap<String, ConfiguredFilesetEntry> filesetEntryMap,
ImmutableMap<Label, ConfigMatchingProvider> configConditions,
ImmutableList<Class<? extends Fragment>> universalFragments,
String ruleClassNameForLogging,
ActionLookupKey actionLookupKey,
ImmutableMap<String, Attribute> aspectAttributes,
@Nullable ToolchainCollection<ResolvedToolchainContext> toolchainContexts,
ConstraintSemantics<RuleContext> constraintSemantics,
ImmutableSet<String> requiredConfigFragments,
String toolsRepository,
StarlarkSemantics starlarkSemantics,
Mutability mutability)
throws InvalidExecGroupException {
super(
builder.env,
builder.target.getAssociatedRule(),
builder.configuration,
builder.prerequisiteMap.get(null),
builder.visibility);
this.rule = builder.target.getAssociatedRule();
this.aspects = builder.aspects;
this.aspectDescriptors =
builder
.aspects
.stream()
.map(a -> a.getDescriptor())
.collect(ImmutableList.toImmutableList());
this.configurationFragmentPolicy = builder.configurationFragmentPolicy;
this.universalFragments = universalFragments;
this.targetMap = targetMap;
this.filesetEntryMap = filesetEntryMap;
this.configConditions = configConditions;
this.attributes = new AspectAwareAttributeMapper(attributes, aspectAttributes);
Set<String> allEnabledFeatures = new HashSet<>();
Set<String> allDisabledFeatures = new HashSet<>();
getAllFeatures(allEnabledFeatures, allDisabledFeatures);
this.enabledFeatures = ImmutableSortedSet.copyOf(allEnabledFeatures);
this.disabledFeatures = ImmutableSortedSet.copyOf(allDisabledFeatures);
this.ruleClassNameForLogging = ruleClassNameForLogging;
this.hostConfiguration = builder.hostConfiguration;
this.actionOwnerSymbolGenerator = new SymbolGenerator<>(actionLookupKey);
reporter = builder.reporter;
this.toolchainContexts = toolchainContexts;
this.execProperties = parseExecProperties(builder.rawExecProperties);
this.constraintSemantics = constraintSemantics;
this.requiredConfigFragments = requiredConfigFragments;
this.starlarkSemantics = starlarkSemantics;
this.starlarkThread = createStarlarkThread(toolsRepository, mutability); // uses above state
}
private void getAllFeatures(Set<String> allEnabledFeatures, Set<String> allDisabledFeatures) {
Set<String> globallyEnabled = new HashSet<>();
Set<String> globallyDisabled = new HashSet<>();
parseFeatures(getConfiguration().getDefaultFeatures(), globallyEnabled, globallyDisabled);
Set<String> packageEnabled = new HashSet<>();
Set<String> packageDisabled = new HashSet<>();
parseFeatures(getRule().getPackage().getFeatures(), packageEnabled, packageDisabled);
Set<String> ruleEnabled = new HashSet<>();
Set<String> ruleDisabled = new HashSet<>();
if (attributes().has("features", Type.STRING_LIST)) {
parseFeatures(attributes().get("features", Type.STRING_LIST), ruleEnabled, ruleDisabled);
}
Set<String> ruleDisabledFeatures =
Sets.union(ruleDisabled, Sets.difference(packageDisabled, ruleEnabled));
allDisabledFeatures.addAll(Sets.union(ruleDisabledFeatures, globallyDisabled));
Set<String> packageFeatures =
Sets.difference(Sets.union(globallyEnabled, packageEnabled), packageDisabled);
Set<String> ruleFeatures =
Sets.difference(Sets.union(packageFeatures, ruleEnabled), ruleDisabled);
allEnabledFeatures.addAll(Sets.difference(ruleFeatures, globallyDisabled));
}
private void parseFeatures(Iterable<String> features, Set<String> enabled, Set<String> disabled) {
for (String feature : features) {
if (feature.startsWith("-")) {
disabled.add(feature.substring(1));
} else if (feature.equals("no_layering_check")) {
// TODO(bazel-team): Remove once we do not have BUILD files left that contain
// 'no_layering_check'.
disabled.add(feature.substring(3));
} else {
enabled.add(feature);
}
}
}
public RepositoryName getRepository() {
return rule.getRepository();
}
@Override
public ArtifactRoot getBinDirectory() {
return getConfiguration().getBinDirectory(getLabel().getRepository());
}
public ArtifactRoot getIncludeDirectory() {
return getConfiguration().getIncludeDirectory(getLabel().getRepository());
}
public ArtifactRoot getGenfilesDirectory() {
return getConfiguration().getGenfilesDirectory(getLabel().getRepository());
}
public ArtifactRoot getCoverageMetadataDirectory() {
return getConfiguration().getCoverageMetadataDirectory(getLabel().getRepository());
}
public ArtifactRoot getTestLogsDirectory() {
return getConfiguration().getTestLogsDirectory(getLabel().getRepository());
}
public PathFragment getBinFragment() {
return getConfiguration().getBinFragment(getLabel().getRepository());
}
public PathFragment getGenfilesFragment() {
return getConfiguration().getGenfilesFragment(getLabel().getRepository());
}
@Override
public ArtifactRoot getMiddlemanDirectory() {
return getConfiguration().getMiddlemanDirectory(getLabel().getRepository());
}
public Rule getRule() {
return rule;
}
public ImmutableList<Aspect> getAspects() {
return aspects;
}
/**
* If this target's configuration suppresses analysis failures, this returns a list
* of strings, where each string corresponds to a description of an error that occurred during
* processing this target.
*
* @throws IllegalStateException if this target's configuration does not suppress analysis
* failures (if {@code getConfiguration().allowAnalysisFailures()} is false)
*/
public List<String> getSuppressedErrorMessages() {
Preconditions.checkState(getConfiguration().allowAnalysisFailures(),
"Error messages can only be retrieved via RuleContext if allow_analysis_failures is true");
Preconditions.checkState(reporter instanceof SuppressingErrorReporter,
"Unexpected error reporter");
return ((SuppressingErrorReporter) reporter).getErrorMessages();
}
/**
* If this <code>RuleContext</code> is for an aspect implementation, returns that aspect.
* (it is the last aspect in the list of aspects applied to a target; all other aspects
* are the ones main aspect sees as specified by its "required_aspect_providers")
* Otherwise returns <code>null</code>.
*/
@Nullable
public Aspect getMainAspect() {
return aspects.isEmpty() ? null : aspects.get(aspects.size() - 1);
}
/**
* Returns a rule class name suitable for log messages, including an aspect name if applicable.
*/
public String getRuleClassNameForLogging() {
return ruleClassNameForLogging;
}
/**
* Returns the workspace name for the rule.
*/
public String getWorkspaceName() {
return rule.getRepository().strippedName();
}
/**
* The configuration conditions that trigger this rule's configurable attributes.
*/
public ImmutableMap<Label, ConfigMatchingProvider> getConfigConditions() {
return configConditions;
}
/**
* Returns the host configuration for this rule.
*/
public BuildConfiguration getHostConfiguration() {
return hostConfiguration;
}
/**
* All aspects applied to the rule.
*/
public ImmutableList<AspectDescriptor> getAspectDescriptors() {
return aspectDescriptors;
}
/**
* Accessor for the attributes of the rule and its aspects.
*
* <p>The rule's native attributes can be queried both on their structure / existence and values
* Aspect attributes can only be queried on their structure.
*
* <p>This should be the sole interface for reading rule/aspect attributes in {@link RuleContext}.
* Don't expose other access points through new public methods.
*/
public AttributeMap attributes() {
return attributes;
}
@Override
public boolean hasErrors() {
return reporter.hasErrors();
}
/**
* Returns an immutable map from attribute name to list of configured targets for that attribute.
*/
public ListMultimap<String, ? extends TransitiveInfoCollection> getConfiguredTargetMap() {
return Multimaps.transformValues(targetMap, ConfiguredTargetAndData::getConfiguredTarget);
}
/**
* Returns an immutable map from attribute name to list of {@link ConfiguredTargetAndData} objects
* for that attribute.
*/
public ListMultimap<String, ConfiguredTargetAndData> getConfiguredTargetAndDataMap() {
return targetMap;
}
/** Returns the {@link ConfiguredTargetAndData} the given attribute. */
public List<ConfiguredTargetAndData> getPrerequisiteConfiguredTargets(String attributeName) {
return targetMap.get(attributeName);
}
/**
* Returns an immutable map from attribute name to list of fileset entries.
*/
public ListMultimap<String, ConfiguredFilesetEntry> getFilesetEntryMap() {
return filesetEntryMap;
}
@Override
public ActionOwner getActionOwner() {
return getActionOwner(DEFAULT_EXEC_GROUP_NAME);
}
@Override
@Nullable
public ActionOwner getActionOwner(String execGroup) {
if (actionOwners.containsKey(execGroup)) {
return actionOwners.get(execGroup);
}
if (toolchainContexts != null && !toolchainContexts.hasToolchainContext(execGroup)) {
return null;
}
ActionOwner actionOwner =
createActionOwner(
rule,
aspectDescriptors,
getConfiguration(),
getExecProperties(execGroup, execProperties),
getExecutionPlatform(execGroup));
actionOwners.put(execGroup, actionOwner);
return actionOwner;
}
/**
* We have to re-implement this method here because it is declared in the interface {@link
* ActionConstructionContext}. This class inherits from {@link TargetContext} which doesn't
* implement the {@link ActionConstructionContext} interface.
*/
@Override
public ActionKeyContext getActionKeyContext() {
return super.getActionKeyContext();
}
/**
* An opaque symbol generator to be used when identifying objects by their action owner/index of
* creation. Only needed if an object needs to know whether it was created by the same action
* owner in the same order as another object. Each symbol must call {@link
* SymbolGenerator#generate} separately to obtain a unique object.
*/
public SymbolGenerator<?> getSymbolGenerator() {
return actionOwnerSymbolGenerator;
}
/**
* Returns a configuration fragment for this this target.
*/
@Nullable
public <T extends Fragment> T getFragment(Class<T> fragment, ConfigurationTransition transition) {
return getFragment(fragment, fragment.getSimpleName(), "", transition);
}
@Nullable
<T extends Fragment> T getFragment(
Class<T> fragment,
String name,
String additionalErrorMessage,
ConfigurationTransition transition) {
// TODO(bazel-team): The fragments can also be accessed directly through BuildConfiguration.
// Can we lock that down somehow?
Preconditions.checkArgument(isLegalFragment(fragment, transition),
"%s has to declare '%s' as a required fragment "
+ "in %s configuration in order to access it.%s",
getRuleClassNameForLogging(), name, FragmentCollection.getConfigurationName(transition),
additionalErrorMessage);
return getConfiguration(transition).getFragment(fragment);
}
@Nullable
public <T extends Fragment> T getFragment(Class<T> fragment) {
// No transition means target configuration.
return getFragment(fragment, NoTransition.INSTANCE);
}
@Nullable
public Fragment getStarlarkFragment(String name, ConfigurationTransition transition)
throws EvalException {
Class<? extends Fragment> fragmentClass =
getConfiguration(transition).getStarlarkFragmentByName(name);
if (fragmentClass == null) {
return null;
}
try {
return getFragment(
fragmentClass,
name,
String.format(
" Please update the '%1$sfragments' argument of the rule definition "
+ "(for example: %1$sfragments = [\"%2$s\"])",
transition.isHostTransition() ? "host_" : "", name),
transition);
} catch (IllegalArgumentException ex) { // fishy
throw new EvalException(ex.getMessage());
}
}
public ImmutableCollection<String> getStarlarkFragmentNames(ConfigurationTransition transition) {
return getConfiguration(transition).getStarlarkFragmentNames();
}
public <T extends Fragment> boolean isLegalFragment(
Class<T> fragment, ConfigurationTransition transition) {
return universalFragments.contains(fragment)
|| configurationFragmentPolicy.isLegalConfigurationFragment(fragment, transition);
}
public <T extends Fragment> boolean isLegalFragment(Class<T> fragment) {
// No transition means target configuration.
return isLegalFragment(fragment, NoTransition.INSTANCE);
}
private BuildConfiguration getConfiguration(ConfigurationTransition transition) {
return transition.isHostTransition() ? hostConfiguration : getConfiguration();
}
@Override
public ActionLookupKey getOwner() {
return getAnalysisEnvironment().getOwner();
}
public ImmutableList<Artifact> getBuildInfo(BuildInfoKey key) throws InterruptedException {
return getAnalysisEnvironment()
.getBuildInfo(
AnalysisUtils.isStampingEnabled(this, getConfiguration()), key, getConfiguration());
}
private static ImmutableMap<String, String> computeExecProperties(
Map<String, String> targetExecProperties, @Nullable PlatformInfo executionPlatform) {
Map<String, String> execProperties = new HashMap<>();
if (executionPlatform != null) {
execProperties.putAll(executionPlatform.execProperties());
}
// If the same key occurs both in the platform and in target-specific properties, the
// value is taken from target-specific properties (effectively overriding the platform
// properties).
execProperties.putAll(targetExecProperties);
return ImmutableMap.copyOf(execProperties);
}
@VisibleForTesting
public static ActionOwner createActionOwner(
Rule rule,
ImmutableList<AspectDescriptor> aspectDescriptors,
BuildConfiguration configuration,
Map<String, String> targetExecProperties,
@Nullable PlatformInfo executionPlatform) {
return ActionOwner.create(
rule.getLabel(),
aspectDescriptors,
rule.getLocation(),
configuration.getMnemonic(),
rule.getTargetKind(),
configuration.checksum(),
configuration.toBuildEvent(),
configuration.isHostConfiguration() ? HOST_CONFIGURATION_PROGRESS_TAG : null,
computeExecProperties(targetExecProperties, executionPlatform),
executionPlatform);
}
@Override
public void registerAction(ActionAnalysisMetadata... action) {
getAnalysisEnvironment().registerAction(action);
}
/**
* Convenience function for subclasses to report non-attribute-specific
* errors in the current rule.
*/
@Override
public void ruleError(String message) {
reporter.ruleError(message);
}
/**
* Convenience function for subclasses to report non-attribute-specific
* warnings in the current rule.
*/
@Override
public void ruleWarning(String message) {
reporter.ruleWarning(message);
}
/**
* Convenience function for subclasses to report attribute-specific errors in
* the current rule.
*
* <p>If the name of the attribute starts with <code>$</code>
* it is replaced with a string <code>(an implicit dependency)</code>.
*/
@Override
public void attributeError(String attrName, String message) {
reporter.attributeError(attrName, message);
}
/**
* Like attributeError, but does not mark the configured target as errored.
*
* <p>If the name of the attribute starts with <code>$</code>
* it is replaced with a string <code>(an implicit dependency)</code>.
*/
@Override
public void attributeWarning(String attrName, String message) {
reporter.attributeWarning(attrName, message);
}
/**
* Returns an artifact beneath the root of either the "bin" or "genfiles"
* tree, whose path is based on the name of this target and the current
* configuration. The choice of which tree to use is based on the rule with
* which this target (which must be an OutputFile or a Rule) is associated.
*/
public Artifact createOutputArtifact() {
Target target = getTarget();
PathFragment rootRelativePath = getPackageDirectory()
.getRelative(PathFragment.create(target.getName()));
return internalCreateOutputArtifact(rootRelativePath, target, OutputFile.Kind.FILE);
}
/**
* Returns an artifact beneath the root of either the "bin" or "genfiles"
* tree, whose path is based on the name of this target and the current
* configuration, with a script suffix appropriate for the current host platform. ({@code .cmd}
* for Windows, otherwise {@code .sh}). The choice of which tree to use is based on the rule with
* which this target (which must be an OutputFile or a Rule) is associated.
*/
public Artifact createOutputArtifactScript() {
Target target = getTarget();
// TODO(laszlocsomor): Use the execution platform, not the host platform.
boolean isExecutedOnWindows = OS.getCurrent() == OS.WINDOWS;
String fileExtension = isExecutedOnWindows ? ".cmd" : ".sh";
PathFragment rootRelativePath = getPackageDirectory()
.getRelative(PathFragment.create(target.getName() + fileExtension));
return internalCreateOutputArtifact(rootRelativePath, target, OutputFile.Kind.FILE);
}
/**
* Returns the output artifact of an {@link OutputFile} of this target.
*
* @see #createOutputArtifact()
*/
public Artifact createOutputArtifact(OutputFile out) {
PathFragment packageRelativePath = getPackageDirectory()
.getRelative(PathFragment.create(out.getName()));
return internalCreateOutputArtifact(packageRelativePath, out, out.getKind());
}
/**
* Implementation for {@link #createOutputArtifact()} and
* {@link #createOutputArtifact(OutputFile)}. This is private so that
* {@link #createOutputArtifact(OutputFile)} can have a more specific
* signature.
*/
private Artifact internalCreateOutputArtifact(PathFragment rootRelativePath,
Target target, OutputFile.Kind outputFileKind) {
Preconditions.checkState(
target.getLabel().getPackageIdentifier().equals(getLabel().getPackageIdentifier()),
"Creating output artifact for target '%s' in different package than the rule '%s' "
+ "being analyzed", target.getLabel(), getLabel());
ArtifactRoot root = getBinOrGenfilesDirectory();
switch (outputFileKind) {
case FILE:
return getDerivedArtifact(rootRelativePath, root);
case FILESET:
return getAnalysisEnvironment().getFilesetArtifact(rootRelativePath, root);
default:
throw new IllegalStateException();
}
}
/**
* Returns the root of either the "bin" or "genfiles" tree, based on this target and the current
* configuration. The choice of which tree to use is based on the rule with which this target
* (which must be an OutputFile or a Rule) is associated.
*/
@Override
public ArtifactRoot getBinOrGenfilesDirectory() {
return rule.hasBinaryOutput()
? getConfiguration().getBinDirectory(getLabel().getRepository())
: getConfiguration().getGenfilesDirectory(getLabel().getRepository());
}
/**
* Creates an artifact in a directory that is unique to the package that contains the rule, thus
* guaranteeing that it never clashes with artifacts created by rules in other packages.
*/
public Artifact getBinArtifact(String relative) {
return getBinArtifact(PathFragment.create(relative));
}
public Artifact getBinArtifact(PathFragment relative) {
return getPackageRelativeArtifact(
relative, getConfiguration().getBinDirectory(getLabel().getRepository()));
}
/**
* Creates an artifact in a directory that is unique to the package that contains the rule, thus
* guaranteeing that it never clashes with artifacts created by rules in other packages.
*/
public Artifact getGenfilesArtifact(String relative) {
return getGenfilesArtifact(PathFragment.create(relative));
}
public Artifact getGenfilesArtifact(PathFragment relative) {
return getPackageRelativeArtifact(
relative, getConfiguration().getGenfilesDirectory(getLabel().getRepository()));
}
@Override
public Artifact getShareableArtifact(PathFragment rootRelativePath, ArtifactRoot root) {
return getAnalysisEnvironment().getDerivedArtifact(rootRelativePath, root);
}
@Override
public Artifact.DerivedArtifact getPackageRelativeArtifact(
PathFragment relative, ArtifactRoot root) {
return getPackageRelativeArtifact(relative, root, /*contentBasedPath=*/ false);
}
/**
* Same as {@link #getPackageRelativeArtifact(PathFragment, ArtifactRoot)} but includes the option
* option to use a content-based path for this artifact (see {@link
* BuildConfiguration#useContentBasedOutputPaths()}).
*/
private Artifact.DerivedArtifact getPackageRelativeArtifact(
PathFragment relative, ArtifactRoot root, boolean contentBasedPath) {
return getDerivedArtifact(getPackageDirectory().getRelative(relative), root, contentBasedPath);
}
/**
* Creates an artifact in a directory that is unique to the package that contains the rule, thus
* guaranteeing that it never clashes with artifacts created by rules in other packages.
*/
public Artifact getPackageRelativeArtifact(String relative, ArtifactRoot root) {
return getPackageRelativeArtifact(relative, root, /*contentBasedPath=*/ false);
}
/**
* Same as {@link #getPackageRelativeArtifact(String, ArtifactRoot)} but includes the option to
* use a content-based path for this artifact (see {@link
* BuildConfiguration#useContentBasedOutputPaths()}).
*/
private Artifact getPackageRelativeArtifact(
String relative, ArtifactRoot root, boolean contentBasedPath) {
return getPackageRelativeArtifact(PathFragment.create(relative), root, contentBasedPath);
}
@Override
public PathFragment getPackageDirectory() {
return getLabel()
.getPackageIdentifier()
.getPackagePath(getConfiguration().isSiblingRepositoryLayout());
}
/**
* Creates an artifact under a given root with the given root-relative path.
*
* <p>Verifies that it is in the root-relative directory corresponding to the package of the rule,
* thus ensuring that it doesn't clash with other artifacts generated by other rules using this
* method.
*/
@Override
public Artifact.DerivedArtifact getDerivedArtifact(
PathFragment rootRelativePath, ArtifactRoot root) {
return getDerivedArtifact(rootRelativePath, root, /*contentBasedPath=*/ false);
}
/**
* Same as {@link #getDerivedArtifact(PathFragment, ArtifactRoot)} but includes the option to use
* a content-based path for this artifact (see {@link
* BuildConfiguration#useContentBasedOutputPaths()}).
*/
public Artifact.DerivedArtifact getDerivedArtifact(
PathFragment rootRelativePath, ArtifactRoot root, boolean contentBasedPath) {
Preconditions.checkState(rootRelativePath.startsWith(getPackageDirectory()),
"Output artifact '%s' not under package directory '%s' for target '%s'",
rootRelativePath, getPackageDirectory(), getLabel());
return getAnalysisEnvironment().getDerivedArtifact(rootRelativePath, root, contentBasedPath);
}
@Override
public SpecialArtifact getTreeArtifact(PathFragment rootRelativePath, ArtifactRoot root) {
Preconditions.checkState(rootRelativePath.startsWith(getPackageDirectory()),
"Output artifact '%s' not under package directory '%s' for target '%s'",
rootRelativePath, getPackageDirectory(), getLabel());
return getAnalysisEnvironment().getTreeArtifact(rootRelativePath, root);
}
/**
* Creates a tree artifact in a directory that is unique to the package that contains the rule,
* thus guaranteeing that it never clashes with artifacts created by rules in other packages.
*/
public Artifact getPackageRelativeTreeArtifact(PathFragment relative, ArtifactRoot root) {
return getTreeArtifact(getPackageDirectory().getRelative(relative), root);
}
/**
* Creates an artifact in a directory that is unique to the rule, thus guaranteeing that it never
* clashes with artifacts created by other rules.
*/
public Artifact getUniqueDirectoryArtifact(
String uniqueDirectory, String relative, ArtifactRoot root) {
return getUniqueDirectoryArtifact(uniqueDirectory, PathFragment.create(relative), root);
}
@Override
public Artifact getUniqueDirectoryArtifact(String uniqueDirectorySuffix, String relative) {
return getUniqueDirectoryArtifact(uniqueDirectorySuffix, relative, getBinOrGenfilesDirectory());
}
@Override
public Artifact getUniqueDirectoryArtifact(String uniqueDirectorySuffix, PathFragment relative) {
return getUniqueDirectoryArtifact(uniqueDirectorySuffix, relative, getBinOrGenfilesDirectory());
}
@Override
public Artifact getUniqueDirectoryArtifact(
String uniqueDirectory, PathFragment relative, ArtifactRoot root) {
return getDerivedArtifact(getUniqueDirectory(uniqueDirectory).getRelative(relative), root);
}
/**
* Returns true iff the rule, or any attached aspect, has an attribute with the given name and
* type.
*/
public boolean isAttrDefined(String attrName, Type<?> type) {
return attributes().has(attrName, type);
}
/**
* Returns the dependencies through a {@code LABEL_DICT_UNARY} attribute as a map from
* a string to a {@link TransitiveInfoCollection}.
*/
public Map<String, TransitiveInfoCollection> getPrerequisiteMap(String attributeName) {
Preconditions.checkState(attributes().has(attributeName, BuildType.LABEL_DICT_UNARY));
ImmutableMap.Builder<String, TransitiveInfoCollection> result = ImmutableMap.builder();
Map<String, Label> dict = attributes().get(attributeName, BuildType.LABEL_DICT_UNARY);
Map<Label, ConfiguredTarget> labelToDep = new HashMap<>();
for (ConfiguredTargetAndData dep : targetMap.get(attributeName)) {
labelToDep.put(dep.getTarget().getLabel(), dep.getConfiguredTarget());
}
for (Map.Entry<String, Label> entry : dict.entrySet()) {
result.put(entry.getKey(), Preconditions.checkNotNull(labelToDep.get(entry.getValue())));
}
return result.build();
}
/**
* Returns the prerequisites keyed by their configuration transition keys. If the split transition
* is not active (e.g. split() returned an empty list), the key is an empty Optional.
*/
public Map<Optional<String>, ? extends List<? extends TransitiveInfoCollection>>
getSplitPrerequisites(String attributeName) {
return Maps.transformValues(
getSplitPrerequisiteConfiguredTargetAndTargets(attributeName),
(ctatList) -> Lists.transform(ctatList, ConfiguredTargetAndData::getConfiguredTarget));
}
/**
* Returns the prerequisites keyed by their transition keys. If the split transition is not active
* (e.g. split() returned an empty list), the key is an empty Optional.
*/
public Map<Optional<String>, List<ConfiguredTargetAndData>>
getSplitPrerequisiteConfiguredTargetAndTargets(String attributeName) {
checkAttributeIsDependency(attributeName);
// Use an ImmutableListMultimap.Builder here to preserve ordering.
ImmutableListMultimap.Builder<Optional<String>, ConfiguredTargetAndData> result =
ImmutableListMultimap.builder();
List<ConfiguredTargetAndData> deps = getPrerequisiteConfiguredTargets(attributeName);
for (ConfiguredTargetAndData t : deps) {
ImmutableList<String> transitionKeys = t.getTransitionKeys();
if (transitionKeys.isEmpty()) {
// The split transition is not active, i.e. does not change build configurations.
// TODO(jungjw): Investigate if we need to do a check here.
return ImmutableMap.of(Optional.absent(), deps);
}
for (String key : transitionKeys) {
result.put(Optional.of(key), t);
}
}
return Multimaps.asMap(result.build());
}
/**
* Returns the specified provider of the prerequisite referenced by the attribute in the argument.
* If the attribute is empty or it does not support the specified provider, returns null.
*/
@Nullable
public <C extends TransitiveInfoProvider> C getPrerequisite(
String attributeName, Class<C> provider) {
TransitiveInfoCollection prerequisite = getPrerequisite(attributeName);
return prerequisite == null ? null : prerequisite.getProvider(provider);
}
/**
* Returns the transitive info collection that feeds into this target through the specified
* attribute. Returns null if the attribute is empty.
*/
@Nullable
public TransitiveInfoCollection getPrerequisite(String attributeName) {
ConfiguredTargetAndData result = getPrerequisiteConfiguredTargetAndData(attributeName);
return result == null ? null : result.getConfiguredTarget();
}
/**
* Returns the {@link ConfiguredTargetAndData} that feeds ino this target through the specified
* attribute. Returns null if the attribute is empty.