aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/main/java/com/google/devtools/build/lib/bazel/rules/BazelPrerequisiteValidator.java
blob: a4f2f3d011e42718c210966b09630ffce95c99cb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
// Copyright 2017 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.bazel.rules;

import com.google.devtools.build.lib.analysis.AliasProvider;
import com.google.devtools.build.lib.analysis.AliasProvider.TargetMode;
import com.google.devtools.build.lib.analysis.ConfiguredRuleClassProvider;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.packages.Attribute;
import com.google.devtools.build.lib.packages.NonconfigurableAttributeMapper;
import com.google.devtools.build.lib.packages.PackageGroup;
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.Target;
import com.google.devtools.build.lib.skyframe.ConfiguredTargetAndData;
import com.google.devtools.build.lib.syntax.Type;

/** Ensures that a target's prerequisites are visible to it and match its testonly status. */
public class BazelPrerequisiteValidator
    implements ConfiguredRuleClassProvider.PrerequisiteValidator {

  @Override
  public void validate(
      RuleContext.Builder context, ConfiguredTargetAndData prerequisite, Attribute attribute) {
    validateDirectPrerequisiteVisibility(context, prerequisite, attribute.getName());
    validateDirectPrerequisiteForTestOnly(context, prerequisite);
    ConfiguredRuleClassProvider.DeprecationValidator.validateDirectPrerequisiteForDeprecation(
        context, context.getRule(), prerequisite, context.forAspect());
  }

  private void validateDirectPrerequisiteVisibility(
      RuleContext.Builder context, ConfiguredTargetAndData prerequisite, String attrName) {
    Rule rule = context.getRule();
    Target prerequisiteTarget = prerequisite.getTarget();
    if (!context
            .getRule()
            .getLabel()
            .getPackageIdentifier()
            .equals(
                AliasProvider.getDependencyLabel(prerequisite.getConfiguredTarget())
                    .getPackageIdentifier())
        && !context.isVisible(prerequisite.getConfiguredTarget())) {
      String errorMessage;
      if (!context.getConfiguration().checkVisibility()) {
        errorMessage =
            String.format(
                "Target '%s' violates visibility of "
                    + "%s. Continuing because --nocheck_visibility is active",
                rule.getLabel(), AliasProvider.describeTargetWithAliases(prerequisite,
                    TargetMode.WITHOUT_KIND));
        context.ruleWarning(errorMessage);
      } else {
        // Oddly enough, we use reportError rather than ruleError here.
        errorMessage =
            String.format(
                "%s is not visible from target '%s'. Check "
                    + "the visibility declaration of the former target if you think "
                    + "the dependency is legitimate",
                AliasProvider.describeTargetWithAliases(prerequisite, TargetMode.WITHOUT_KIND),
                rule.getLabel());
        context.reportError(rule.getLocation(), errorMessage);
      }
      // We can always post the visibility error as, regardless of the value of keep going,
      // that target will not be built.
      context.post(
          new VisibilityErrorEvent(context.getConfiguration(), rule.getLabel(), errorMessage));
    }

    if (prerequisiteTarget instanceof PackageGroup) {
      RequiredProviders requiredProviders =
          RawAttributeMapper.of(rule).getAttributeDefinition(attrName).getRequiredProviders();
      boolean containsPackageSpecificationProvider =
          requiredProviders.getDescription().contains("PackageSpecificationProvider");
      // TODO(plf): Add the PackageSpecificationProvider to the 'visibility' attribute.
      if (!attrName.equals("visibility") && !containsPackageSpecificationProvider) {
        context.reportError(
            rule.getAttributeLocation(attrName),
            "in "
                + attrName
                + " attribute of "
                + rule.getRuleClass()
                + " rule "
                + rule.getLabel()
                + ": "
                + AliasProvider.describeTargetWithAliases(prerequisite, TargetMode.WITH_KIND)
                + " is misplaced here "
                + "(they are only allowed in the visibility attribute)");
      }
    }
  }

  private void validateDirectPrerequisiteForTestOnly(
      RuleContext.Builder context, ConfiguredTargetAndData prerequisite) {
    Rule rule = context.getRule();

    if (rule.getRuleClassObject().getAdvertisedProviders().canHaveAnyProvider()) {
      // testonly-ness will be checked directly between the depender and the target of the alias;
      // getTarget() called by the depender will not return the alias rule, but its actual target
      return;
    }

    Target prerequisiteTarget = prerequisite.getTarget();
    String thisPackage = rule.getLabel().getPackageName();

    if (isTestOnlyRule(prerequisiteTarget) && !isTestOnlyRule(rule)) {
      String message =
          "non-test target '"
              + rule.getLabel()
              + "' depends on testonly "
              + AliasProvider.describeTargetWithAliases(prerequisite, TargetMode.WITHOUT_KIND)
              + " and doesn't have testonly attribute set";
      if (thisPackage.startsWith("experimental/")) {
        context.ruleWarning(message);
      } else {
        context.ruleError(message);
      }
    }
  }

  private static boolean isTestOnlyRule(Target target) {
    return (target instanceof Rule)
        && (NonconfigurableAttributeMapper.of((Rule) target)).has("testonly", Type.BOOLEAN)
        && (NonconfigurableAttributeMapper.of((Rule) target)).get("testonly", Type.BOOLEAN);
  }
}