forked from bazelbuild/bazel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
StarlarkRuleContext.java
1118 lines (1003 loc) · 43.9 KB
/
StarlarkRuleContext.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.starlark;
import static com.google.devtools.build.lib.analysis.config.transitions.ConfigurationTransition.PATCH_TRANSITION_KEY;
import static com.google.devtools.build.lib.packages.RuleClass.Builder.STARLARK_BUILD_SETTING_DEFAULT_ATTR_NAME;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
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.Iterables;
import com.google.common.collect.Ordering;
import com.google.common.hash.Hashing;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.ArtifactRoot;
import com.google.devtools.build.lib.analysis.ActionsProvider;
import com.google.devtools.build.lib.analysis.AliasProvider;
import com.google.devtools.build.lib.analysis.BashCommandConstructor;
import com.google.devtools.build.lib.analysis.CommandHelper;
import com.google.devtools.build.lib.analysis.ConfigurationMakeVariableContext;
import com.google.devtools.build.lib.analysis.DefaultInfo;
import com.google.devtools.build.lib.analysis.FileProvider;
import com.google.devtools.build.lib.analysis.FilesToRunProvider;
import com.google.devtools.build.lib.analysis.LocationExpander;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.Runfiles;
import com.google.devtools.build.lib.analysis.Runfiles.SymlinkEntry;
import com.google.devtools.build.lib.analysis.RunfilesProvider;
import com.google.devtools.build.lib.analysis.ShToolchain;
import com.google.devtools.build.lib.analysis.TransitiveInfoCollection;
import com.google.devtools.build.lib.analysis.config.BuildConfigurationValue;
import com.google.devtools.build.lib.analysis.config.CoreOptions;
import com.google.devtools.build.lib.analysis.config.FragmentCollection;
import com.google.devtools.build.lib.analysis.config.HostTransition;
import com.google.devtools.build.lib.analysis.config.transitions.NoTransition;
import com.google.devtools.build.lib.analysis.platform.ConstraintValueInfo;
import com.google.devtools.build.lib.analysis.stringtemplate.ExpansionException;
import com.google.devtools.build.lib.analysis.test.InstrumentedFilesCollector;
import com.google.devtools.build.lib.analysis.test.InstrumentedFilesInfo;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.collect.nestedset.Depset;
import com.google.devtools.build.lib.collect.nestedset.Depset.TypeException;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.Order;
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.Attribute.ComputedDefault;
import com.google.devtools.build.lib.packages.BuildSetting;
import com.google.devtools.build.lib.packages.BuildType;
import com.google.devtools.build.lib.packages.ImplicitOutputsFunction;
import com.google.devtools.build.lib.packages.OutputFile;
import com.google.devtools.build.lib.packages.Package;
import com.google.devtools.build.lib.packages.Provider;
import com.google.devtools.build.lib.packages.Rule;
import com.google.devtools.build.lib.packages.RuleClass.ConfiguredTargetFactory.RuleErrorException;
import com.google.devtools.build.lib.packages.StructImpl;
import com.google.devtools.build.lib.packages.StructProvider;
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.shell.ShellUtils;
import com.google.devtools.build.lib.shell.ShellUtils.TokenizationException;
import com.google.devtools.build.lib.starlarkbuildapi.StarlarkRuleContextApi;
import com.google.devtools.build.lib.starlarkbuildapi.platform.ToolchainContextApi;
import com.google.devtools.build.lib.vfs.PathFragment;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
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.Dict;
import net.starlark.java.eval.Dict.ImmutableKeyTrackingDict;
import net.starlark.java.eval.EvalException;
import net.starlark.java.eval.Printer;
import net.starlark.java.eval.Sequence;
import net.starlark.java.eval.Starlark;
import net.starlark.java.eval.StarlarkList;
import net.starlark.java.eval.StarlarkSemantics;
import net.starlark.java.eval.StarlarkThread;
import net.starlark.java.eval.StarlarkValue;
import net.starlark.java.eval.Structure;
import net.starlark.java.eval.Tuple;
/**
* A Starlark API for the ruleContext.
*
* <p>"This object becomes featureless once the rule implementation function that it was created for
* has completed. To achieve this, the {@link #nullify()} should be called once the evaluation of
* the function is completed. The method both frees memory by deleting all significant fields of the
* object and makes it impossible to accidentally use this object where it's not supposed to be used
* (such attempts will result in {@link EvalException}s).
*/
public final class StarlarkRuleContext implements StarlarkRuleContextApi<ConstraintValueInfo> {
public static final String EXECUTABLE_OUTPUT_NAME = "executable";
// This field is a copy of the info from ruleContext, stored separately so it can be accessed
// after this object has been nullified.
private final String ruleLabelCanonicalName;
private final boolean isForAspect;
private final StarlarkActionFactory actionFactory;
// The fields below are intended to be final except that they can be cleared by calling
// `nullify()` when the object becomes featureless (analogous to freezing).
private RuleContext ruleContext;
private FragmentCollection fragments;
private FragmentCollection hostFragments;
@Nullable private AspectDescriptor aspectDescriptor;
/**
* This variable is used to expose the state of {@link
* RuleContext#configurationMakeVariableContext} to the user via {@code ctx.var}.
*
* <p>Computing this field causes a side-effect of initializing the Make var context with an empty
* list of additional MakeVariableSuppliers. Historically, this was fine for Starlark-defined
* rules, but became a problem when we started giving StarlarkRuleContexts to native rules (to
* sandwich them with {@code @_builtins}, for Starlarkification). The native rules would then
* compete with this default initialization for control over the Make var context.
*
* <p>To work around this, we now compute and cache the Dict of all Make vars lazily at the first
* call to {@code ctx.var}. If a native rule provides custom MakeVariableSuppliers (via {@link
* RuleContext#initConfigurationMakeVariableContext}) and also passes {@code ctx} to a
* Starlark-defined function that accesses {@code ctx.var}, then the call to {@code
* initConfigurationMakeVariableContext} must come first or else that call will throw a
* precondition exception.
*
* <p>Note that StarlarkRuleContext can (for pathological user-written rules) survive the analysis
* phase and be accessed concurrently. Nonetheless, it is still safe to initialize {@code ctx.var}
* lazily without synchronization, because {@code ctx.var} is inaccessible once {@code nullify()}
* has been called.
*/
private Dict<String, String> cachedMakeVariables = null;
private StarlarkAttributesCollection attributesCollection;
private StarlarkAttributesCollection ruleAttributesCollection;
private StructImpl splitAttributes;
private Outputs outputsObject;
/**
* Creates a new StarlarkRuleContext wrapping ruleContext.
*
* <p>{@code aspectDescriptor} is the aspect for which the context is created, or <code>
* null</code> if it is for a rule.
*/
public StarlarkRuleContext(RuleContext ruleContext, @Nullable AspectDescriptor aspectDescriptor)
throws RuleErrorException {
// Init ruleContext first, we need it to obtain the StarlarkSemantics used by
// StarlarkActionFactory (and possibly others).
this.ruleContext = Preconditions.checkNotNull(ruleContext);
this.actionFactory = new StarlarkActionFactory(this);
this.ruleLabelCanonicalName = ruleContext.getLabel().getCanonicalForm();
this.fragments = new FragmentCollection(ruleContext, NoTransition.INSTANCE);
this.hostFragments = new FragmentCollection(ruleContext, HostTransition.INSTANCE);
this.aspectDescriptor = aspectDescriptor;
this.isForAspect = aspectDescriptor != null;
Rule rule = ruleContext.getRule();
if (aspectDescriptor == null) {
Collection<Attribute> attributes =
rule.getAttributes().stream()
.filter(attribute -> !attribute.getName().equals("aspect_hints"))
.collect(Collectors.toList());
// Populate ctx.outputs.
Outputs outputs = new Outputs(this);
// These getters do some computational work to return a view, so ensure we only do it once.
ImmutableListMultimap<String, OutputFile> explicitOutMap = rule.getExplicitOutputFileMap();
ImmutableMap<String, OutputFile> implicitOutMap = rule.getStarlarkImplicitOutputFileMap();
// Add the explicit outputs -- values of attributes of type OUTPUT or OUTPUT_LIST.
// We must iterate over the attribute definitions, and not just the entries in the
// explicitOutMap, because the latter omits empty output attributes, which must still
// generate None or [] fields in the struct.
for (Attribute a : attributes) {
// Skip non-output attrs.
String attrName = a.getName();
Type<?> type = a.getType();
if (type.getLabelClass() != LabelClass.OUTPUT) {
continue;
}
// Grab all associated outputs.
ImmutableList.Builder<Artifact> artifactsBuilder = ImmutableList.builder();
for (OutputFile outputFile : explicitOutMap.get(attrName)) {
artifactsBuilder.add(ruleContext.createOutputArtifact(outputFile));
}
StarlarkList<Artifact> artifacts = StarlarkList.immutableCopyOf(artifactsBuilder.build());
// For singular output attributes, unwrap sole element or else use None for arity mismatch.
if (type == BuildType.OUTPUT) {
if (artifacts.size() == 1) {
outputs.addOutput(attrName, Iterables.getOnlyElement(artifacts));
} else {
outputs.addOutput(attrName, Starlark.NONE);
}
} else if (type == BuildType.OUTPUT_LIST) {
outputs.addOutput(attrName, artifacts);
} else {
throw new AssertionError(
String.format("Attribute %s has unexpected output type %s", attrName, type));
}
}
// Add the implicit outputs. In the case where the rule has a native-defined implicit outputs
// function, nothing is added. Note that Rule ensures that Starlark-defined implicit output
// keys don't conflict with output attribute names.
// TODO(bazel-team): Also see about requiring the key to be a valid Starlark identifier.
for (Map.Entry<String, OutputFile> e : implicitOutMap.entrySet()) {
outputs.addOutput(e.getKey(), ruleContext.createOutputArtifact(e.getValue()));
}
this.outputsObject = outputs;
// Populate ctx.attr.
StarlarkAttributesCollection.Builder builder = StarlarkAttributesCollection.builder(this);
for (Attribute attribute : attributes) {
Object value = ruleContext.attributes().get(attribute.getName(), attribute.getType());
builder.addAttribute(attribute, value);
}
this.attributesCollection = builder.build();
this.splitAttributes = buildSplitAttributeInfo(attributes, ruleContext);
this.ruleAttributesCollection = null;
} else { // ASPECT
this.outputsObject = null;
ImmutableCollection<Attribute> attributes =
ruleContext.getMainAspect().getDefinition().getAttributes().values();
StarlarkAttributesCollection.Builder aspectBuilder =
StarlarkAttributesCollection.builder(this);
for (Attribute attribute : attributes) {
Object defaultValue = attribute.getDefaultValue(rule);
if (defaultValue instanceof ComputedDefault) {
defaultValue = ((ComputedDefault) defaultValue).getDefault(ruleContext.attributes());
}
aspectBuilder.addAttribute(attribute, defaultValue);
}
this.attributesCollection = aspectBuilder.build();
this.splitAttributes = null;
StarlarkAttributesCollection.Builder ruleBuilder = StarlarkAttributesCollection.builder(this);
for (Attribute attribute : rule.getAttributes()) {
// The aspect_hints attribute is experimental. When not enabled through the
// --enable_aspect_hints flag, we don't add it to the list of attributes that the aspect
// has access to.
if (attribute.getName().equals("aspect_hints")
&& !ruleContext
.getConfiguration()
.getOptions()
.get(CoreOptions.class)
.enableAspectHints) {
continue;
}
Object value = ruleContext.attributes().get(attribute.getName(), attribute.getType());
ruleBuilder.addAttribute(attribute, value);
}
for (Aspect aspect : ruleContext.getAspects()) {
if (aspect.equals(ruleContext.getMainAspect())) {
// Aspect's own attributes are in <code>attributesCollection</code>.
continue;
}
for (Attribute attribute : aspect.getDefinition().getAttributes().values()) {
Object defaultValue = attribute.getDefaultValue(rule);
if (defaultValue instanceof ComputedDefault) {
defaultValue = ((ComputedDefault) defaultValue).getDefault(ruleContext.attributes());
}
ruleBuilder.addAttribute(attribute, defaultValue);
}
}
this.ruleAttributesCollection = ruleBuilder.build();
}
}
/**
* Represents `ctx.outputs`.
*
* <p>The value of its {@code ctx.outputs.executable} field is computed on-demand.
*
* <p>Note: There is only one {@code Outputs} object per rule context, so default (object
* identity) equals and hashCode suffice.
*/
// TODO(adonovan): add StarlarkBuiltin(name="ctx.outputs") annotation.
private static class Outputs implements Structure, StarlarkValue {
private final Map<String, Object> outputs;
private final StarlarkRuleContext context;
private boolean executableCreated = false;
Outputs(StarlarkRuleContext context) {
this.outputs = new LinkedHashMap<>();
this.context = context;
}
private void addOutput(String key, Object value) throws RuleErrorException {
Preconditions.checkState(!context.isImmutable());
// TODO(bazel-team): We should reject outputs whose key is not an identifier. Today this is
// allowed, and the resulting ctx.outputs value can be retrieved using getattr().
if (outputs.containsKey(key)
|| (context.isExecutable() && EXECUTABLE_OUTPUT_NAME.equals(key))) {
context.getRuleContext().throwWithRuleError("Multiple outputs with the same key: " + key);
}
outputs.put(key, value);
}
@Override
public boolean isImmutable() {
return context.isImmutable();
}
@Override
public ImmutableCollection<String> getFieldNames() {
// TODO(b/175954936): There's an NPE here when accessing dir(ctx.outputs) after rule
// analysis has completed. Since we can't throw EvalException here, this may require that we
// preemptively copy the fields into this object, or at least keep a "nullified" bit so we
// know to produce an empty result here.
ImmutableList.Builder<String> result = ImmutableList.builder();
if (context.isExecutable() && executableCreated) {
result.add(EXECUTABLE_OUTPUT_NAME);
}
result.addAll(outputs.keySet());
return result.build();
}
@Nullable
@Override
public Object getValue(String name) throws EvalException {
checkMutable();
if (context.isExecutable() && EXECUTABLE_OUTPUT_NAME.equals(name)) {
executableCreated = true;
// createOutputArtifact() will cache the created artifact.
return context.getRuleContext().createOutputArtifact();
}
return outputs.get(name);
}
@Nullable
@Override
public String getErrorMessageForUnknownField(String name) {
return String.format(
"No attribute '%s' in outputs. Make sure you declared a rule output with this name.",
name);
}
@Override
public void repr(Printer printer) {
if (isImmutable()) {
printer.append("ctx.outputs(for ");
printer.append(context.ruleLabelCanonicalName);
printer.append(")");
return;
}
boolean first = true;
printer.append("ctx.outputs(");
// Sort by field name to ensure deterministic output.
try {
for (String field : Ordering.natural().sortedCopy(getFieldNames())) {
if (!first) {
printer.append(", ");
}
first = false;
printer.append(field);
printer.append(" = ");
printer.repr(getValue(field));
}
printer.append(")");
} catch (EvalException e) {
throw new AssertionError("mutable ctx.outputs should not throw", e);
}
}
private void checkMutable() throws EvalException {
if (isImmutable()) {
throw Starlark.errorf(
"cannot access outputs of rule '%s' outside of its own rule implementation function",
context.ruleLabelCanonicalName);
}
}
}
public boolean isExecutable() {
return ruleContext.getRule().getRuleClassObject().isExecutableStarlark();
}
public boolean isDefaultExecutableCreated() {
return this.outputsObject.executableCreated;
}
/**
* Nullifies fields of the object when it's not supposed to be used anymore to free unused memory
* and to make sure this object is not accessed when it's not supposed to (after the corresponding
* rule implementation function has exited).
*/
public void nullify() {
ruleContext = null;
fragments = null;
hostFragments = null;
aspectDescriptor = null;
cachedMakeVariables = null;
attributesCollection = null;
ruleAttributesCollection = null;
splitAttributes = null;
outputsObject = null;
}
/** Throws an EvalException mentioning {@code attrName} if we've already been nullified. */
public void checkMutable(String attrName) throws EvalException {
if (isImmutable()) {
throw Starlark.errorf(
"cannot access field or method '%s' of rule context for '%s' outside of its own rule "
+ "implementation function",
attrName, ruleLabelCanonicalName);
}
}
@Nullable
public AspectDescriptor getAspectDescriptor() {
return aspectDescriptor;
}
public String getRuleLabelCanonicalName() {
return ruleLabelCanonicalName;
}
private static StructImpl buildSplitAttributeInfo(
Collection<Attribute> attributes, RuleContext ruleContext) {
ImmutableMap.Builder<String, Object> splitAttrInfos = ImmutableMap.builder();
for (Attribute attr : attributes) {
if (!attr.getTransitionFactory().isSplit()) {
continue;
}
Map<Optional<String>, ? extends List<? extends TransitiveInfoCollection>> splitPrereqs =
ruleContext.getSplitPrerequisites(attr.getName());
Map<Object, Object> splitPrereqsMap = new LinkedHashMap<>();
for (Map.Entry<Optional<String>, ? extends List<? extends TransitiveInfoCollection>>
splitPrereq : splitPrereqs.entrySet()) {
// Skip a split with an empty dependency list.
// TODO(jungjw): Figure out exactly which cases trigger this and see if this can be made
// more error-proof.
if (splitPrereq.getValue().isEmpty()) {
continue;
}
Object value;
if (attr.getType() == BuildType.LABEL) {
Preconditions.checkState(splitPrereq.getValue().size() == 1);
value = splitPrereq.getValue().get(0);
} else {
// BuildType.LABEL_LIST
value = StarlarkList.immutableCopyOf(splitPrereq.getValue());
}
if (splitPrereq.getKey().isPresent()
&& !splitPrereq.getKey().get().equals(PATCH_TRANSITION_KEY)) {
splitPrereqsMap.put(splitPrereq.getKey().get(), value);
} else {
// If the split transition is not in effect, then the key will be missing since there's
// nothing to key on because the dependencies aren't split and getSplitPrerequisites()
// behaves like getPrerequisites(). This also means there should be only one entry in
// the map. Use None in Starlark to represent this.
Preconditions.checkState(splitPrereqs.size() == 1);
splitPrereqsMap.put(Starlark.NONE, value);
}
}
splitAttrInfos.put(attr.getPublicName(), Dict.immutableCopyOf(splitPrereqsMap));
}
return StructProvider.STRUCT.create(
splitAttrInfos.build(),
"No attribute '%s' in split_attr."
+ "This attribute is not defined with a split configuration.");
}
@Override
public boolean isImmutable() {
return ruleContext == null;
}
@Override
public void repr(Printer printer) {
if (isForAspect) {
printer.append("<aspect context for " + ruleLabelCanonicalName + ">");
} else {
printer.append("<rule context for " + ruleLabelCanonicalName + ">");
}
}
/** Returns the wrapped ruleContext. */
public RuleContext getRuleContext() {
return ruleContext;
}
@Override
public Provider getDefaultProvider() {
return DefaultInfo.PROVIDER;
}
@Override
public StarlarkActionFactory actions() {
return actionFactory;
}
@Override
public StarlarkValue createdActions() throws EvalException {
checkMutable("created_actions");
if (ruleContext.getRule().getRuleClassObject().isStarlarkTestable()) {
return ActionsProvider.create(ruleContext.getAnalysisEnvironment().getRegisteredActions());
} else {
return Starlark.NONE;
}
}
@Override
public StructImpl getAttr() throws EvalException {
checkMutable("attr");
return attributesCollection.getAttr();
}
@Override
public StructImpl getSplitAttr() throws EvalException {
checkMutable("split_attr");
if (splitAttributes == null) {
throw new EvalException("'split_attr' is available only in rule implementations");
}
return splitAttributes;
}
/** See {@link RuleContext#getExecutablePrerequisite(String)}. */
@Override
public StructImpl getExecutable() throws EvalException {
checkMutable("executable");
return attributesCollection.getExecutable();
}
/** See {@link RuleContext#getPrerequisiteArtifact(String)}. */
@Override
public StructImpl getFile() throws EvalException {
checkMutable("file");
return attributesCollection.getFile();
}
/** See {@link RuleContext#getPrerequisiteArtifacts(String)}. */
@Override
public StructImpl getFiles() throws EvalException {
checkMutable("files");
return attributesCollection.getFiles();
}
@Override
public String getWorkspaceName() throws EvalException {
checkMutable("workspace_name");
return ruleContext.getWorkspaceName();
}
@Override
public Label getLabel() throws EvalException {
checkMutable("label");
return ruleContext.getLabel();
}
@Override
public FragmentCollection getFragments() throws EvalException {
checkMutable("fragments");
return fragments;
}
@Override
public FragmentCollection getHostFragments() throws EvalException {
checkMutable("host_fragments");
return hostFragments;
}
@Override
public BuildConfigurationValue getConfiguration() throws EvalException {
checkMutable("configuration");
return ruleContext.getConfiguration();
}
@Override
public BuildConfigurationValue getHostConfiguration() throws EvalException {
checkMutable("host_configuration");
return ruleContext.getHostConfiguration();
}
@Override
@Nullable
public Object getBuildSettingValue() throws EvalException {
if (ruleContext.getRule().getRuleClassObject().getBuildSetting() == null) {
throw Starlark.errorf(
"attempting to access 'build_setting_value' of non-build setting %s",
ruleLabelCanonicalName);
}
ImmutableMap<Label, Object> starlarkFlagSettings =
ruleContext.getConfiguration().getOptions().getStarlarkOptions();
BuildSetting buildSetting = ruleContext.getRule().getRuleClassObject().getBuildSetting();
if (starlarkFlagSettings.containsKey(ruleContext.getLabel())) {
return starlarkFlagSettings.get(ruleContext.getLabel());
} else {
Object defaultValue =
ruleContext
.attributes()
.get(STARLARK_BUILD_SETTING_DEFAULT_ATTR_NAME, buildSetting.getType());
return buildSetting.allowsMultiple() ? ImmutableList.of(defaultValue) : defaultValue;
}
}
@Override
public boolean instrumentCoverage(Object targetUnchecked) throws EvalException {
checkMutable("coverage_instrumented");
BuildConfigurationValue config = ruleContext.getConfiguration();
if (!config.isCodeCoverageEnabled()) {
return false;
}
if (targetUnchecked == Starlark.NONE) {
return InstrumentedFilesCollector.shouldIncludeLocalSources(
ruleContext.getConfiguration(), ruleContext.getLabel(), ruleContext.isTestTarget());
}
TransitiveInfoCollection target = (TransitiveInfoCollection) targetUnchecked;
return (target.get(InstrumentedFilesInfo.STARLARK_CONSTRUCTOR) != null)
&& InstrumentedFilesCollector.shouldIncludeLocalSources(config, target);
}
@Override
public ImmutableList<String> getFeatures() throws EvalException {
checkMutable("features");
return ImmutableList.copyOf(ruleContext.getFeatures());
}
@Override
public ImmutableList<String> getDisabledFeatures() throws EvalException {
checkMutable("disabled_features");
return ImmutableList.copyOf(ruleContext.getDisabledFeatures());
}
@Override
public ArtifactRoot getBinDirectory() throws EvalException {
checkMutable("bin_dir");
return getConfiguration().getBinDirectory(ruleContext.getRule().getRepository());
}
@Override
public ArtifactRoot getGenfilesDirectory() throws EvalException {
checkMutable("genfiles_dir");
return getConfiguration().getGenfilesDirectory(ruleContext.getRule().getRepository());
}
@Override
public Structure outputs() throws EvalException {
checkMutable("outputs");
if (outputsObject == null) {
throw new EvalException("'outputs' is not defined");
}
return outputsObject;
}
@Override
public StarlarkAttributesCollection rule() throws EvalException {
checkMutable("rule");
if (!isForAspect) {
throw new EvalException("'rule' is only available in aspect implementations");
}
return ruleAttributesCollection;
}
@Override
public ImmutableList<String> aspectIds() throws EvalException {
checkMutable("aspect_ids");
if (!isForAspect) {
throw new EvalException("'aspect_ids' is only available in aspect implementations");
}
ImmutableList.Builder<String> result = ImmutableList.builder();
for (AspectDescriptor descriptor : ruleContext.getAspectDescriptors()) {
result.add(descriptor.getDescription());
}
return result.build();
}
@Override
public Dict<String, String> var() throws EvalException {
checkMutable("var");
if (cachedMakeVariables == null) {
Dict.Builder<String, String> vars;
try {
vars = ruleContext.getConfigurationMakeVariableContext().collectMakeVariables();
} catch (ExpansionException e) {
throw new EvalException(e.getMessage());
}
// When tracking required fragments, use a key-tracking dict to support lookedUpVariables().
cachedMakeVariables =
ruleContext.shouldIncludeRequiredConfigFragmentsProvider()
? vars.buildImmutableWithKeyTracking()
: vars.buildImmutable();
}
return cachedMakeVariables;
}
/** Returns the set of variables accessed through {@code ctx.var}. */
public ImmutableSet<String> lookedUpVariables() {
Preconditions.checkState(ruleContext.shouldIncludeRequiredConfigFragmentsProvider(), this);
return cachedMakeVariables == null
? ImmutableSet.of()
: ((ImmutableKeyTrackingDict<String, String>) cachedMakeVariables).getAccessedKeys();
}
@Override
public ToolchainContextApi toolchains() throws EvalException {
checkMutable("toolchains");
return StarlarkToolchainContext.create(ruleContext.getToolchainContext());
}
@Override
public boolean targetPlatformHasConstraint(ConstraintValueInfo constraintValue) {
return ruleContext.targetPlatformHasConstraint(constraintValue);
}
@Override
public StarlarkExecGroupCollection execGroups() {
// Create a thin wrapper around the toolchain collection, to expose the Starlark API.
return StarlarkExecGroupCollection.create(ruleContext.getToolchainContexts());
}
@Override
public String toString() {
return ruleLabelCanonicalName;
}
@Override
public Sequence<String> tokenize(String optionString) throws EvalException {
checkMutable("tokenize");
List<String> options = new ArrayList<>();
try {
ShellUtils.tokenize(options, optionString);
} catch (TokenizationException e) {
throw Starlark.errorf("%s while tokenizing '%s'", e.getMessage(), optionString);
}
return StarlarkList.immutableCopyOf(options);
}
boolean isForAspect() {
return isForAspect;
}
@Override
public Artifact newFile(Object var1, Object var2, Object fileSuffix) throws EvalException {
checkMutable("new_file");
checkDeprecated("ctx.actions.declare_file", "ctx.new_file", getStarlarkSemantics());
// Determine which of new_file's four signatures is being used. Yes, this is terrible.
// It's one major reason that this method is deprecated.
if (fileSuffix != Starlark.UNBOUND) {
// new_file(file_root, sibling_file, suffix)
ArtifactRoot root =
assertTypeForNewFile(
var1, ArtifactRoot.class, "expected first param to be of type 'root'");
Artifact siblingFile =
assertTypeForNewFile(var2, Artifact.class, "expected second param to be of type 'File'");
PathFragment original =
siblingFile.getOutputDirRelativePath(getConfiguration().isSiblingRepositoryLayout());
PathFragment fragment = original.replaceName(original.getBaseName() + fileSuffix);
return ruleContext.getDerivedArtifact(fragment, root);
} else if (var2 == Starlark.UNBOUND) {
// new_file(filename)
String filename =
assertTypeForNewFile(var1, String.class, "expected first param to be of type 'string'");
return actionFactory.declareFile(filename, Starlark.NONE);
} else {
String filename =
assertTypeForNewFile(var2, String.class, "expected second param to be of type 'string'");
if (var1 instanceof ArtifactRoot) {
// new_file(root, filename)
ArtifactRoot root = (ArtifactRoot) var1;
return ruleContext.getPackageRelativeArtifact(filename, root);
} else {
// new_file(sibling_file, filename)
Artifact siblingFile =
assertTypeForNewFile(
var1, Artifact.class, "expected first param to be of type 'File' or 'root'");
return actionFactory.declareFile(filename, siblingFile);
}
}
}
private static <T> T assertTypeForNewFile(Object obj, Class<T> type, String errorMessage)
throws EvalException {
if (type.isInstance(obj)) {
return type.cast(obj);
} else {
throw new EvalException(errorMessage);
}
}
@Override
public boolean checkPlaceholders(String template, Sequence<?> allowedPlaceholders) // <String>
throws EvalException {
checkMutable("check_placeholders");
List<String> actualPlaceHolders = new LinkedList<>();
Set<String> allowedPlaceholderSet =
ImmutableSet.copyOf(
Sequence.cast(allowedPlaceholders, String.class, "allowed_placeholders"));
ImplicitOutputsFunction.createPlaceholderSubstitutionFormatString(template, actualPlaceHolders);
for (String placeholder : actualPlaceHolders) {
if (!allowedPlaceholderSet.contains(placeholder)) {
return false;
}
}
return true;
}
@Override
public String expandMakeVariables(
String attributeName, String command, Dict<?, ?> additionalSubstitutions) // <String, String>
throws EvalException {
checkMutable("expand_make_variables");
final Map<String, String> additionalSubstitutionsMap =
Dict.cast(additionalSubstitutions, String.class, String.class, "additional_substitutions");
return expandMakeVariables(attributeName, command, additionalSubstitutionsMap);
}
private String expandMakeVariables(
String attributeName, String command, Map<String, String> additionalSubstitutionsMap) {
ConfigurationMakeVariableContext makeVariableContext =
new ConfigurationMakeVariableContext(
ruleContext,
ruleContext.getRule().getPackage(),
ruleContext.getConfiguration(),
ImmutableList.of()) {
@Override
public String lookupVariable(String variableName) throws ExpansionException {
if (additionalSubstitutionsMap.containsKey(variableName)) {
return additionalSubstitutionsMap.get(variableName);
} else {
return super.lookupVariable(variableName);
}
}
};
return ruleContext.getExpander(makeVariableContext).expand(attributeName, command);
}
FilesToRunProvider getExecutableRunfiles(Artifact executable) {
return attributesCollection.getExecutableRunfilesMap().get(executable);
}
@Override
public Artifact getStableWorkspaceStatus() throws InterruptedException, EvalException {
checkMutable("info_file");
return ruleContext.getAnalysisEnvironment().getStableWorkspaceStatusArtifact();
}
@Override
public Artifact getVolatileWorkspaceStatus() throws InterruptedException, EvalException {
checkMutable("version_file");
return ruleContext.getAnalysisEnvironment().getVolatileWorkspaceStatusArtifact();
}
@Override
public String getBuildFileRelativePath() throws EvalException {
checkMutable("build_file_path");
Package pkg = ruleContext.getRule().getPackage();
return pkg.getSourceRoot().get().relativize(pkg.getBuildFile().getPath()).getPathString();
}
@Override
public String expandLocation(String input, Sequence<?> targets, StarlarkThread thread)
throws EvalException {
checkMutable("expand_location");
try {
return LocationExpander.withExecPaths(
ruleContext,
makeLabelMap(Sequence.cast(targets, TransitiveInfoCollection.class, "targets")))
.expand(input);
} catch (IllegalStateException ise) {
throw new EvalException(ise);
}
}
@Override
public Runfiles runfiles(
Sequence<?> files,
Object transitiveFiles,
Boolean collectData,
Boolean collectDefault,
Object symlinks,
Object rootSymlinks)
throws EvalException, TypeException {
checkMutable("runfiles");
Runfiles.Builder builder =
new Runfiles.Builder(
ruleContext.getWorkspaceName(), getConfiguration().legacyExternalRunfiles());
boolean checkConflicts = false;
if (Starlark.truth(collectData)) {
builder.addRunfiles(ruleContext, RunfilesProvider.DATA_RUNFILES);
}
if (Starlark.truth(collectDefault)) {
builder.addRunfiles(ruleContext, RunfilesProvider.DEFAULT_RUNFILES);
}
if (!files.isEmpty()) {
builder.addArtifacts(Sequence.cast(files, Artifact.class, "files"));
}
if (transitiveFiles != Starlark.NONE) {
NestedSet<Artifact> transitiveArtifacts =
Depset.cast(transitiveFiles, Artifact.class, "transitive_files");
// Runfiles uses compile order. Check that the given transitive_files depset is compatible.
if (!Order.COMPILE_ORDER.isCompatible(transitiveArtifacts.getOrder())) {
throw Starlark.errorf(
"order '%s' is invalid for transitive_files",
transitiveArtifacts.getOrder().getStarlarkName());
}
builder.addTransitiveArtifacts(transitiveArtifacts);
}
if (isDepset(symlinks)) {
builder.addSymlinks(((Depset) symlinks).getSet(SymlinkEntry.class));
} else if (isNonEmptyDict(symlinks)) {
// If Starlark code directly manipulates symlinks, activate more stringent validity checking.
checkConflicts = true;
for (Map.Entry<String, Artifact> entry :
Dict.cast(symlinks, String.class, Artifact.class, "symlinks").entrySet()) {
builder.addSymlink(PathFragment.create(entry.getKey()), entry.getValue());
}
}
if (isDepset(rootSymlinks)) {
builder.addRootSymlinks(((Depset) rootSymlinks).getSet(SymlinkEntry.class));
} else if (isNonEmptyDict(rootSymlinks)) {
checkConflicts = true;
for (Map.Entry<String, Artifact> entry :
Dict.cast(rootSymlinks, String.class, Artifact.class, "root_symlinks").entrySet()) {
builder.addRootSymlink(PathFragment.create(entry.getKey()), entry.getValue());
}
}
Runfiles runfiles = builder.build();
if (checkConflicts) {
runfiles.setConflictPolicy(Runfiles.ConflictPolicy.ERROR);
}
return runfiles;
}
private static boolean isNonEmptyDict(Object o) {
return o instanceof Dict && !((Dict<?, ?>) o).isEmpty();
}
private static boolean isDepset(Object o) {
return o instanceof Depset;
}
@Override
public Tuple resolveCommand(
String command,
Object attributeUnchecked,
Boolean expandLocations,
Object makeVariablesUnchecked,
Sequence<?> tools,
Dict<?, ?> labelDictUnchecked,
Dict<?, ?> executionRequirementsUnchecked,
StarlarkThread thread)
throws EvalException {
checkMutable("resolve_command");
Label ruleLabel = getLabel();
Map<Label, Iterable<Artifact>> labelDict = checkLabelDict(labelDictUnchecked);
// The best way to fix this probably is to convert CommandHelper to Starlark.
CommandHelper helper =
CommandHelper.builder(ruleContext)
.addToolDependencies(Sequence.cast(tools, TransitiveInfoCollection.class, "tools"))
.addLabelMap(labelDict)
.build();
String attribute = Type.STRING.convertOptional(attributeUnchecked, "attribute", ruleLabel);