forked from bazelbuild/bazel
/
Package.java
2115 lines (1883 loc) · 79.1 KB
/
Package.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.packages;
import static com.google.common.base.MoreObjects.firstNonNull;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.BiMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Interner;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.devtools.build.lib.bugreport.BugReport;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.cmdline.LabelConstants;
import com.google.devtools.build.lib.cmdline.LabelSyntaxException;
import com.google.devtools.build.lib.cmdline.PackageIdentifier;
import com.google.devtools.build.lib.cmdline.RepositoryMapping;
import com.google.devtools.build.lib.cmdline.RepositoryName;
import com.google.devtools.build.lib.cmdline.TargetPattern;
import com.google.devtools.build.lib.collect.CollectionUtils;
import com.google.devtools.build.lib.concurrent.ThreadSafety.ThreadCompatible;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.events.EventHandler;
import com.google.devtools.build.lib.events.EventKind;
import com.google.devtools.build.lib.events.ExtendedEventHandler.Postable;
import com.google.devtools.build.lib.packages.License.DistributionType;
import com.google.devtools.build.lib.packages.Package.Builder.DefaultPackageSettings;
import com.google.devtools.build.lib.packages.Package.Builder.PackageSettings;
import com.google.devtools.build.lib.packages.semantics.BuildLanguageOptions;
import com.google.devtools.build.lib.server.FailureDetails.FailureDetail;
import com.google.devtools.build.lib.server.FailureDetails.PackageLoading;
import com.google.devtools.build.lib.server.FailureDetails.PackageLoading.Code;
import com.google.devtools.build.lib.skyframe.serialization.DeserializationContext;
import com.google.devtools.build.lib.skyframe.serialization.ObjectCodec;
import com.google.devtools.build.lib.skyframe.serialization.SerializationContext;
import com.google.devtools.build.lib.skyframe.serialization.SerializationException;
import com.google.devtools.build.lib.util.DetailedExitCode;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.devtools.build.lib.vfs.Root;
import com.google.devtools.build.lib.vfs.RootedPath;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.protobuf.CodedInputStream;
import com.google.protobuf.CodedOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import javax.annotation.Nullable;
import net.starlark.java.eval.Module;
import net.starlark.java.eval.StarlarkSemantics;
import net.starlark.java.eval.StarlarkThread;
import net.starlark.java.spelling.SpellChecker;
import net.starlark.java.syntax.Location;
/**
* A package, which is a container of {@link Rule}s, each of which contains a dictionary of named
* attributes.
*
* <p>Package instances are intended to be immutable and for all practical purposes can be treated
* as such. Note, however, that some member variables exposed via the public interface are not
* strictly immutable, so until their types are guaranteed immutable we're not applying the
* {@code @Immutable} annotation here.
*
* <p>This class should not be extended - it's only non-final for mocking!
*
* <p>When changing this class, make sure to make corresponding changes to serialization!
*/
@SuppressWarnings("JavaLangClash")
public class Package {
/**
* The "workspace name" of packages generated by Bzlmod to contain repo rules.
*
* <p>Normally, packages containing repo rules are differentiated from packages containing build
* rules by the {@link PackageIdentifier}: The singular repo-rule-containing package is {@code
* //external}. However, in Bzlmod, packages containing repo rules need to have meaningful {@link
* PackageIdentifier}s, so there needs to be some other way to distinguish them from
* build-rule-containing packages. We use the following magic string as the "workspace name" for
* repo-rule-containing packages generated by Bzlmod.
*
* @see #isRepoRulePackage()
*/
private static final String DUMMY_WORKSPACE_NAME_FOR_BZLMOD_PACKAGES = "__dummy_workspace_bzlmod";
/** Common superclass for all name-conflict exceptions. */
public static class NameConflictException extends Exception {
private NameConflictException(String message) {
super(message);
}
}
/**
* The repository identifier for this package.
*/
private final PackageIdentifier packageIdentifier;
private final boolean succinctTargetNotFoundErrors;
/** The filename of this package's BUILD file. */
private RootedPath filename;
/**
* The directory in which this package's BUILD file resides. All InputFile
* members of the packages are located relative to this directory.
*/
private Path packageDirectory;
/**
* The name of the workspace this package is in. Used as a prefix for the runfiles directory.
* This can be set in the WORKSPACE file. This must be a valid target name.
*/
private String workspaceName;
/**
* The root of the source tree in which this package was found. It is an invariant that {@code
* sourceRoot.getRelative(packageId.getSourceRoot()).equals(packageDirectory)}. Returns {@link
* Optional#empty} if this {@link Package} is derived from a WORKSPACE file.
*/
private Optional<Root> sourceRoot;
/**
* The "Make" environment of this package, containing package-local
* definitions of "Make" variables.
*/
private ImmutableMap<String, String> makeEnv;
/** The collection of all targets defined in this package, indexed by name. */
private ImmutableSortedMap<String, Target> targets;
/**
* Default visibility for rules that do not specify it.
*/
private RuleVisibility defaultVisibility;
private boolean defaultVisibilitySet;
/**
* How to enforce config_setting visibility settings.
*
* <p>This is a temporary setting in service of https://github.com/bazelbuild/bazel/issues/12669.
* After enough depot cleanup, config_setting will have the same visibility enforcement as all
* other rules.
*/
public enum ConfigSettingVisibilityPolicy {
/** Don't enforce visibility for any config_setting. */
LEGACY_OFF,
/** Honor explicit visibility settings on config_setting, else use //visibility:public. */
DEFAULT_PUBLIC,
/** Enforce config_setting visibility exactly the same as all other rules. */
DEFAULT_STANDARD
}
private ConfigSettingVisibilityPolicy configSettingVisibilityPolicy;
/**
* Default package-level 'testonly' value for rules that do not specify it.
*/
private boolean defaultTestOnly = false;
/**
* Default package-level 'deprecation' value for rules that do not specify it.
*/
private String defaultDeprecation;
/**
* Default header strictness checking for rules that do not specify it.
*/
private String defaultHdrsCheck;
/** Default copts for cc_* rules. The rules' individual copts will append to this value. */
private ImmutableList<String> defaultCopts;
/**
* The InputFile target corresponding to this package's BUILD file.
*/
private InputFile buildFile;
/**
* True iff this package's BUILD files contained lexical or grammatical
* errors, or experienced errors during evaluation, or semantic errors during
* the construction of any rule.
*
* <p>Note: A package containing errors does not necessarily prevent a build;
* if all the rules needed for a given build were constructed prior to the
* first error, the build may proceed.
*/
private boolean containsErrors;
/**
* The first detailed error encountered during this package's construction and evaluation, or
* {@code null} if there were no such errors or all its errors lacked details.
*/
@Nullable private FailureDetail failureDetail;
/** The list of transitive closure of the Starlark file dependencies. */
private ImmutableList<Label> starlarkFileDependencies;
/** The package's default "package_metadata" attribute. */
private ImmutableSet<Label> defaultPackageMetadata = ImmutableSet.of();
/**
* The package's default "licenses" and "distribs" attributes, as specified
* in calls to licenses() and distribs() in the BUILD file.
*/
// These sets contain the values specified by the most recent licenses() or
// distribs() declarations encountered during package parsing:
private License defaultLicense;
private Set<License.DistributionType> defaultDistributionSet;
/**
* The map from each repository to that repository's remappings map. This is only used in the
* //external package, it is an empty map for all other packages. For example, an entry of {"@foo"
* : {"@x", "@y"}} indicates that, within repository foo, "@x" should be remapped to "@y".
*/
private ImmutableMap<RepositoryName, ImmutableMap<String, RepositoryName>>
externalPackageRepositoryMappings;
/**
* The map of repository reassignments for BUILD packages. This will be empty for packages within
* the main workspace.
*/
private RepositoryMapping repositoryMapping;
/**
* The repository mapping of the main repository. This is only used internally to obtain
* user-friendly apparent names from canonical repository names in error message arising from this
* package.
*/
private RepositoryMapping mainRepositoryMapping;
private Set<Label> defaultCompatibleWith = ImmutableSet.of();
private Set<Label> defaultRestrictedTo = ImmutableSet.of();
private ImmutableSet<String> features;
private ImmutableList<TargetPattern> registeredExecutionPlatforms;
private ImmutableList<TargetPattern> registeredToolchains;
private long computationSteps;
private ImmutableMap<String, Module> loads;
/** Returns the number of Starlark computation steps executed by this BUILD file. */
public long getComputationSteps() {
return computationSteps;
}
/**
* Returns the mapping, for each load statement in this BUILD file in source order, from the load
* string to the module it loads. It thus indirectly records the package's complete load DAG. In
* some configurations the information may be unavailable (null).
*/
@Nullable
public ImmutableMap<String, Module> getLoads() {
return loads;
}
/**
* Package initialization, part 1 of 3: instantiates a new package with the given name.
*
* <p>As part of initialization, {@link Builder} constructs {@link InputFile} and {@link
* PackageGroup} instances that require a valid Package instance where {@link
* Package#getNameFragment()} is accessible. That's why these settings are applied here at the
* start.
*
* <p>{@code name} <b>MUST</b> be a suffix of {@code filename.getParentDirectory())}.
*/
private Package(
PackageIdentifier packageId, String workspaceName, boolean succinctTargetNotFoundErrors) {
this.packageIdentifier = packageId;
this.workspaceName = workspaceName;
this.succinctTargetNotFoundErrors = succinctTargetNotFoundErrors;
}
/** Returns this packages' identifier. */
public PackageIdentifier getPackageIdentifier() {
return packageIdentifier;
}
/**
* Whether this package should contain only repo rules (returns {@code true}) or only build rules
* (returns {@code false}).
*/
public boolean isRepoRulePackage() {
return packageIdentifier.equals(LabelConstants.EXTERNAL_PACKAGE_IDENTIFIER)
|| workspaceName.equals(DUMMY_WORKSPACE_NAME_FOR_BZLMOD_PACKAGES);
}
/**
* Returns the repository mapping for the requested external repository.
*
* @throws UnsupportedOperationException if called from a package other than the //external
* package
*/
public ImmutableMap<String, RepositoryName> getRepositoryMapping(RepositoryName repository) {
if (!isRepoRulePackage()) {
throw new UnsupportedOperationException("Can only access the external package repository"
+ "mappings from the //external package");
}
return externalPackageRepositoryMappings.getOrDefault(repository, ImmutableMap.of());
}
/** Get the repository mapping for this package. */
public RepositoryMapping getRepositoryMapping() {
return repositoryMapping;
}
/**
* Returns the full map of repository mappings collected so far.
*
* @throws UnsupportedOperationException if called from a package other than the //external
* package
*/
ImmutableMap<RepositoryName, ImmutableMap<String, RepositoryName>>
getExternalPackageRepositoryMappings() {
if (!isRepoRulePackage()) {
throw new UnsupportedOperationException(
"Can only access the external package repository"
+ "mappings from the //external package");
}
return this.externalPackageRepositoryMappings;
}
/**
* Package initialization: part 2 of 3: sets this package's default header
* strictness checking.
*
* <p>This is needed to support C++-related rule classes
* which accesses {@link #getDefaultHdrsCheck} from the still-under-construction
* package.
*/
private void setDefaultHdrsCheck(String defaultHdrsCheck) {
this.defaultHdrsCheck = defaultHdrsCheck;
}
/**
* Set the default 'testonly' value for this package.
*/
private void setDefaultTestOnly(boolean testOnly) {
defaultTestOnly = testOnly;
}
/**
* Set the default 'deprecation' value for this package.
*/
private void setDefaultDeprecation(String deprecation) {
defaultDeprecation = deprecation;
}
/**
* Sets the default value to use for a rule's {@link RuleClass#COMPATIBLE_ENVIRONMENT_ATTR}
* attribute when not explicitly specified by the rule.
*/
private void setDefaultCompatibleWith(Set<Label> environments) {
defaultCompatibleWith = environments;
}
/**
* Sets the default value to use for a rule's {@link RuleClass#RESTRICTED_ENVIRONMENT_ATTR}
* attribute when not explicitly specified by the rule.
*/
private void setDefaultRestrictedTo(Set<Label> environments) {
defaultRestrictedTo = environments;
}
/**
* Returns the source root (a directory) beneath which this package's BUILD file was found, or
* {@link Optional#empty} if this package was derived from a workspace file.
*
* <p>Assumes invariant: If non-empty, {@code
* getSourceRoot().get().getRelative(packageId.getSourceRoot()).equals(getPackageDirectory())}
*/
public Optional<Root> getSourceRoot() {
return sourceRoot;
}
private static Root getSourceRoot(RootedPath buildFileRootedPath, PathFragment packageFragment) {
PathFragment packageDirectory = buildFileRootedPath.getRootRelativePath().getParentDirectory();
if (packageFragment.equals(packageDirectory)) {
// Fast path: BUILD file path and package name are the same, don't create an extra root.
return buildFileRootedPath.getRoot();
}
PathFragment current = buildFileRootedPath.asPath().asFragment().getParentDirectory();
for (int i = 0, len = packageFragment.segmentCount(); i < len && current != null; i++) {
current = current.getParentDirectory();
}
if (current == null || current.isEmpty()) {
// This is never really expected to work. The check below in #finishInit should fail.
return buildFileRootedPath.getRoot();
}
// Note that current is an absolute path.
return Root.fromPath(buildFileRootedPath.getRoot().getRelative(current));
}
/**
* Package initialization: part 3 of 3: applies all other settings and completes
* initialization of the package.
*
* <p>Only after this method is called can this package be considered "complete"
* and be shared publicly.
*/
private void finishInit(Builder builder) {
// If any error occurred during evaluation of this package, consider all
// rules in the package to be "in error" also (even if they were evaluated
// prior to the error). This behaviour is arguably stricter than need be,
// but stopping a build only for some errors but not others creates user
// confusion.
if (builder.containsErrors) {
for (Rule rule : builder.getRules()) {
rule.setContainsErrors();
}
}
this.filename = builder.getFilename();
this.packageDirectory = filename.asPath().getParentDirectory();
String baseName = filename.getRootRelativePath().getBaseName();
if (isWorkspaceFile(baseName) || isModuleDotBazelFile(baseName)) {
Preconditions.checkState(isRepoRulePackage());
this.sourceRoot = Optional.empty();
} else {
Root sourceRoot = getSourceRoot(filename, packageIdentifier.getSourceRoot());
if (sourceRoot.asPath() == null
|| !sourceRoot.getRelative(packageIdentifier.getSourceRoot()).equals(packageDirectory)) {
throw new IllegalArgumentException(
"Invalid BUILD file name for package '"
+ packageIdentifier
+ "': "
+ filename
+ " (in source "
+ sourceRoot
+ " with packageDirectory "
+ packageDirectory
+ " and package identifier source root "
+ packageIdentifier.getSourceRoot()
+ ")");
}
this.sourceRoot = Optional.of(sourceRoot);
}
this.makeEnv = ImmutableMap.copyOf(builder.makeEnv);
this.targets = ImmutableSortedMap.copyOf(builder.targets);
this.defaultVisibility = builder.defaultVisibility;
this.defaultVisibilitySet = builder.defaultVisibilitySet;
this.configSettingVisibilityPolicy = builder.configSettingVisibilityPolicy;
if (builder.defaultCopts == null) {
this.defaultCopts = ImmutableList.of();
} else {
this.defaultCopts = ImmutableList.copyOf(builder.defaultCopts);
}
this.buildFile = builder.buildFile;
this.containsErrors = builder.containsErrors;
this.failureDetail = builder.getFailureDetail();
this.starlarkFileDependencies = builder.starlarkFileDependencies;
this.defaultLicense = builder.defaultLicense;
this.defaultDistributionSet = builder.defaultDistributionSet;
this.defaultPackageMetadata = ImmutableSortedSet.copyOf(builder.defaultPackageMetadata);
this.features = ImmutableSortedSet.copyOf(builder.features);
this.registeredExecutionPlatforms = ImmutableList.copyOf(builder.registeredExecutionPlatforms);
this.registeredToolchains = ImmutableList.copyOf(builder.registeredToolchains);
this.repositoryMapping = Preconditions.checkNotNull(builder.repositoryMapping);
this.mainRepositoryMapping = Preconditions.checkNotNull(builder.mainRepositoryMapping);
ImmutableMap.Builder<RepositoryName, ImmutableMap<String, RepositoryName>>
repositoryMappingsBuilder = ImmutableMap.builder();
if (!builder.externalPackageRepositoryMappings.isEmpty() && !builder.isRepoRulePackage()) {
// 'repo_mapping' should only be used in the //external package, i.e. should only appear
// in WORKSPACE files. Currently, if someone tries to use 'repo_mapping' in a BUILD rule, they
// will get a "no such attribute" error. This check is to protect against a 'repo_mapping'
// attribute being added to a rule in the future.
throw new IllegalArgumentException(
"'repo_mapping' may only be used in the //external package");
}
builder.externalPackageRepositoryMappings.forEach((k, v) ->
repositoryMappingsBuilder.put(k, ImmutableMap.copyOf(v)));
this.externalPackageRepositoryMappings = repositoryMappingsBuilder.buildOrThrow();
}
private static boolean isWorkspaceFile(String baseFileName) {
return baseFileName.equals(LabelConstants.WORKSPACE_DOT_BAZEL_FILE_NAME.getPathString())
|| baseFileName.equals(LabelConstants.WORKSPACE_FILE_NAME.getPathString());
}
private static boolean isModuleDotBazelFile(String baseFileName) {
return baseFileName.equals(LabelConstants.MODULE_DOT_BAZEL_FILE_NAME.getPathString());
}
/** Returns the list of transitive closure of the Starlark file dependencies of this package. */
public ImmutableList<Label> getStarlarkFileDependencies() {
return starlarkFileDependencies;
}
/**
* Returns the filename of the BUILD file which defines this package. The parent directory of the
* BUILD file is the package directory.
*/
public RootedPath getFilename() {
return filename;
}
/**
* Returns the directory containing the package's BUILD file.
*/
public Path getPackageDirectory() {
return packageDirectory;
}
/**
* Returns the name of this package. If this build is using external repositories then this name
* may not be unique!
*/
public String getName() {
return packageIdentifier.getPackageFragment().getPathString();
}
/**
* Like {@link #getName}, but has type {@code PathFragment}.
*/
public PathFragment getNameFragment() {
return packageIdentifier.getPackageFragment();
}
/**
* Returns all make variables for a given platform.
*/
public ImmutableMap<String, String> getMakeEnvironment() {
return makeEnv;
}
/**
* Returns the label of this package's BUILD file.
*
* <p> Typically <code>getBuildFileLabel().getName().equals("BUILD")</code> --
* though not necessarily: data in a subdirectory of a test package may use a
* different filename to avoid inadvertently creating a new package.
*/
public Label getBuildFileLabel() {
return buildFile.getLabel();
}
/**
* Returns the InputFile target for this package's BUILD file.
*/
public InputFile getBuildFile() {
return buildFile;
}
/**
* Returns true if errors were encountered during evaluation of this package.
* (The package may be incomplete and its contents should not be relied upon
* for critical operations. However, any Rules belonging to the package are
* guaranteed to be intact, unless their <code>containsErrors()</code> flag
* is set.)
*/
public boolean containsErrors() {
return containsErrors;
}
/**
* Returns the first {@link FailureDetail} describing one of the package's errors, or {@code null}
* if it has no errors or all its errors lack details.
*/
@Nullable
public FailureDetail getFailureDetail() {
return failureDetail;
}
/**
* Returns a {@link FailureDetail} attributing a target error to the package's {@link
* FailureDetail}, or a generic {@link Code#TARGET_MISSING} failure detail if the package has
* none.
*
* <p>May only be called when {@link #containsErrors()} is true and with a target whose package is
* this one.
*/
public FailureDetail contextualizeFailureDetailForTarget(Target target) {
Preconditions.checkState(
target.getPackage().packageIdentifier.equals(packageIdentifier),
"contextualizeFailureDetailForTarget called for target not in package. target=%s,"
+ " package=%s",
target,
this);
Preconditions.checkState(
containsErrors,
"contextualizeFailureDetailForTarget called for package not in error. target=%s",
target);
String prefix =
"Target '" + target.getLabel() + "' contains an error and its package is in error";
if (failureDetail == null) {
return FailureDetail.newBuilder()
.setMessage(prefix)
.setPackageLoading(PackageLoading.newBuilder().setCode(Code.TARGET_MISSING))
.build();
}
return failureDetail.toBuilder().setMessage(prefix + ": " + failureDetail.getMessage()).build();
}
/** Returns an (immutable, ordered) view of all the targets belonging to this package. */
public ImmutableSortedMap<String, Target> getTargets() {
return targets;
}
/** Common getTargets implementation, accessible by {@link Package.Builder}. */
private static Set<Target> getTargets(BiMap<String, Target> targetMap) {
return targetMap.values();
}
/**
* Returns a (read-only, ordered) iterable of all the targets belonging
* to this package which are instances of the specified class.
*/
public <T extends Target> Iterable<T> getTargets(Class<T> targetClass) {
return getTargets(targets, targetClass);
}
/**
* Common getTargets implementation, accessible by both {@link Package} and
* {@link Package.Builder}.
*/
private static <T extends Target> Iterable<T> getTargets(Map<String, Target> targetMap,
Class<T> targetClass) {
return Iterables.filter(targetMap.values(), targetClass);
}
/**
* Returns the rule that corresponds to a particular BUILD target name. Useful
* for walking through the dependency graph of a target.
* Fails if the target is not a Rule.
*/
public Rule getRule(String targetName) {
return (Rule) targets.get(targetName);
}
/**
* Returns this package's workspace name.
*/
public String getWorkspaceName() {
return workspaceName;
}
/**
* Returns the features specified in the <code>package()</code> declaration.
*/
public ImmutableSet<String> getFeatures() {
return features;
}
/**
* Returns the target (a member of this package) whose name is "targetName".
* First rules are searched, then output files, then input files. The target
* name must be valid, as defined by {@code LabelValidator#validateTargetName}.
*
* @throws NoSuchTargetException if the specified target was not found.
*/
public Target getTarget(String targetName) throws NoSuchTargetException {
Target target = targets.get(targetName);
if (target != null) {
return target;
}
Label label;
try {
label = Label.create(packageIdentifier, targetName);
} catch (LabelSyntaxException e) {
throw new IllegalArgumentException(targetName, e);
}
if (succinctTargetNotFoundErrors) {
throw new NoSuchTargetException(
label, String.format("target '%s' not declared in package '%s'", targetName, getName()));
} else {
String alternateTargetSuggestion = getAlternateTargetSuggestion(targetName);
throw new NoSuchTargetException(
label,
String.format(
"target '%s' not declared in package '%s' defined by %s%s",
targetName, getName(), filename.asPath().getPathString(), alternateTargetSuggestion));
}
}
private String getAlternateTargetSuggestion(String targetName) {
// If there's a file on the disk that's not mentioned in the BUILD file,
// produce a more informative error. NOTE! this code path is only executed
// on failure, which is (relatively) very rare. In the common case no
// stat(2) is executed.
Path filename = packageDirectory.getRelative(targetName);
if (!PathFragment.isNormalized(targetName) || "*".equals(targetName)) {
// Don't check for file existence if the target name is not normalized
// because the error message would be confusing and wrong. If the
// targetName is "foo/bar/.", and there is a directory "foo/bar", it
// doesn't mean that "//pkg:foo/bar/." is a valid label.
// Also don't check if the target name is a single * character since
// it's invalid on Windows.
return "";
} else if (filename.isDirectory()) {
return "; however, a source directory of this name exists. (Perhaps add "
+ "'exports_files([\""
+ targetName
+ "\"])' to "
+ getName()
+ "/BUILD, or define a "
+ "filegroup?)";
} else if (filename.exists()) {
return "; however, a source file of this name exists. (Perhaps add "
+ "'exports_files([\""
+ targetName
+ "\"])' to "
+ getName()
+ "/BUILD?)";
} else {
String suggestedTarget = SpellChecker.suggest(targetName, targets.keySet());
String targetSuggestion =
suggestedTarget == null ? null : String.format("did you mean '%s'?", suggestedTarget);
String blazeQuerySuggestion =
String.format(
"Tip: use `query \"%s:*\"` to see all the targets in that package",
packageIdentifier.getDisplayForm(mainRepositoryMapping));
return String.format(
" (%s)", Joiner.on(" ").skipNulls().join(targetSuggestion, blazeQuerySuggestion));
}
}
/**
* Returns the default visibility for this package.
*/
public RuleVisibility getDefaultVisibility() {
return defaultVisibility;
}
/**
* How to enforce visibility on <code>config_setting</code> See
* {@link ConfigSettingVisibilityPolicy} for details.
*/
public ConfigSettingVisibilityPolicy getConfigSettingVisibilityPolicy() {
return configSettingVisibilityPolicy;
}
/**
* Returns the default testonly value.
*/
public Boolean getDefaultTestOnly() {
return defaultTestOnly;
}
/**
* Returns the default deprecation value.
*/
public String getDefaultDeprecation() {
return defaultDeprecation;
}
/** Gets the default header checking mode. */
public String getDefaultHdrsCheck() {
return defaultHdrsCheck != null ? defaultHdrsCheck : "strict";
}
/**
* Returns the default copts value, to which rules should append their
* specific copts.
*/
public ImmutableList<String> getDefaultCopts() {
return defaultCopts;
}
/**
* Returns whether the default header checking mode has been set or it is the
* default value.
*/
public boolean isDefaultHdrsCheckSet() {
return defaultHdrsCheck != null;
}
public boolean isDefaultVisibilitySet() {
return defaultVisibilitySet;
}
/** Gets the package metadata list for the default metadata declared by this package. */
public Set<Label> getDefaultPackageMetadata() {
return defaultPackageMetadata;
}
/** Gets the parsed license object for the default license declared by this package. */
License getDefaultLicense() {
return defaultLicense;
}
/** Returns the parsed set of distributions declared as the default for this package. */
Set<License.DistributionType> getDefaultDistribs() {
return defaultDistributionSet;
}
/**
* Returns the default value to use for a rule's {@link RuleClass#COMPATIBLE_ENVIRONMENT_ATTR}
* attribute when not explicitly specified by the rule.
*/
public Set<Label> getDefaultCompatibleWith() {
return defaultCompatibleWith;
}
/**
* Returns the default value to use for a rule's {@link RuleClass#RESTRICTED_ENVIRONMENT_ATTR}
* attribute when not explicitly specified by the rule.
*/
public Set<Label> getDefaultRestrictedTo() {
return defaultRestrictedTo;
}
public ImmutableList<TargetPattern> getRegisteredExecutionPlatforms() {
return registeredExecutionPlatforms;
}
public ImmutableList<TargetPattern> getRegisteredToolchains() {
return registeredToolchains;
}
@Override
public String toString() {
return "Package("
+ getName()
+ ")="
+ (targets != null ? getTargets(Rule.class) : "initializing...");
}
/**
* Dumps the package for debugging. Do not depend on the exact format/contents of this debugging
* output.
*/
public void dump(PrintStream out) {
out.println(" Package " + getName() + " (" + filename.asPath() + ")");
// Rules:
out.println(" Rules");
for (Rule rule : getTargets(Rule.class)) {
out.println(" " + rule.getTargetKind() + " " + rule.getLabel());
for (Attribute attr : rule.getAttributes()) {
for (Object possibleValue : AggregatingAttributeMapper.of(rule)
.visitAttribute(attr.getName(), attr.getType())) {
out.println(" " + attr.getName() + " = " + possibleValue);
}
}
}
// Files:
out.println(" Files");
for (FileTarget file : getTargets(FileTarget.class)) {
out.print(" " + file.getTargetKind() + " " + file.getLabel());
if (file instanceof OutputFile) {
out.println(" (generated by " + ((OutputFile) file).getGeneratingRule().getLabel() + ")");
} else {
out.println();
}
}
}
public static Builder newExternalPackageBuilder(
PackageSettings helper,
RootedPath workspacePath,
String workspaceName,
RepositoryMapping mainRepoMapping,
StarlarkSemantics starlarkSemantics) {
return new Builder(
helper,
LabelConstants.EXTERNAL_PACKAGE_IDENTIFIER,
workspaceName,
starlarkSemantics.getBool(BuildLanguageOptions.INCOMPATIBLE_NO_IMPLICIT_FILE_EXPORT),
mainRepoMapping,
mainRepoMapping)
.setFilename(workspacePath);
}
public static Builder newExternalPackageBuilderForBzlmod(
RootedPath moduleFilePath,
StarlarkSemantics starlarkSemantics,
PackageIdentifier basePackageId,
RepositoryMapping repoMapping) {
return new Builder(
DefaultPackageSettings.INSTANCE,
basePackageId,
DUMMY_WORKSPACE_NAME_FOR_BZLMOD_PACKAGES,
starlarkSemantics.getBool(BuildLanguageOptions.INCOMPATIBLE_NO_IMPLICIT_FILE_EXPORT),
repoMapping,
// This mapping is *not* the main repository's mapping, but since it is only used to
// construct a query command in an error message and the package built here can't be
// seen by query, the particular value does not matter.
RepositoryMapping.ALWAYS_FALLBACK)
.setFilename(moduleFilePath);
}
/**
* Returns an error {@link Event} with {@link Location} and {@link DetailedExitCode} properties.
*/
public static Event error(Location location, String message, Code code) {
Event error = Event.error(location, message);
return error.withProperty(DetailedExitCode.class, createDetailedCode(message, code));
}
private static DetailedExitCode createDetailedCode(String errorMessage, Code code) {
return DetailedExitCode.of(
FailureDetail.newBuilder()
.setMessage(errorMessage)
.setPackageLoading(PackageLoading.newBuilder().setCode(code))
.build());
}
/**
* A builder for {@link Package} objects. Only intended to be used by {@link PackageFactory} and
* {@link com.google.devtools.build.lib.skyframe.PackageFunction}.
*/
public static class Builder {
/** Defines configuration to control the runtime behavior of {@link Package}s. */
public interface PackageSettings {
/**
* Returns whether or not extra detail should be added to {@link NoSuchTargetException}s
* thrown from {@link #getTarget}. Useful for toning down verbosity in situations where it can
* be less helpful.
*/
boolean succinctTargetNotFoundErrors();
/**
* Reports whether to record the set of Modules loaded by this package, which enables richer
* modes of blaze query.
*/
boolean recordLoadedModules();
}
/** Default {@link PackageSettings}. */
public static class DefaultPackageSettings implements PackageSettings {
public static final DefaultPackageSettings INSTANCE = new DefaultPackageSettings();
private DefaultPackageSettings() {}
@Override
public boolean succinctTargetNotFoundErrors() {
return false;
}
@Override
public boolean recordLoadedModules() {
return true;
}
}
/**
* The output instance for this builder. Needs to be instantiated and
* available with name info throughout initialization. All other settings
* are applied during {@link #build}. See {@link Package#Package}
* and {@link Package#finishInit} for details.
*/
private final Package pkg;
private final boolean noImplicitFileExport;
private static final CallStack.Factory callStackFactory = new CallStack.Factory();
// The map from each repository to that repository's remappings map.
// This is only used in the //external package, it is an empty map for all other packages.
private final HashMap<RepositoryName, HashMap<String, RepositoryName>>
externalPackageRepositoryMappings = new HashMap<>();
/**
* The map of repository reassignments for BUILD packages loaded within external repositories.
* It contains an entry from "@<main workspace name>" to "@" for packages within the main
* workspace.
*/
private final RepositoryMapping repositoryMapping;
/**
* The repository mapping of the main repository. This is only used to resolve user-friendly
* apparent names from canonical repository names in error message arising from this package.
*/
private final RepositoryMapping mainRepositoryMapping;
/** Converts label literals to Label objects within this package. */
private final LabelConverter labelConverter;
private RootedPath filename = null;
private Label buildFileLabel = null;
private InputFile buildFile = null;