aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/tools/skylark/java/com/google/devtools/skylark/skylint/DeprecatedApiChecker.java
blob: 818796e33dfef04bee2b869f83b064ccda6d99a4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
// 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.skylark.skylint;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
import com.google.devtools.build.lib.syntax.Argument;
import com.google.devtools.build.lib.syntax.BuildFileAST;
import com.google.devtools.build.lib.syntax.DotExpression;
import com.google.devtools.build.lib.syntax.Expression;
import com.google.devtools.build.lib.syntax.FuncallExpression;
import com.google.devtools.build.lib.syntax.FunctionDefStatement;
import com.google.devtools.build.lib.syntax.Identifier;
import com.google.devtools.build.lib.syntax.ReturnStatement;
import com.google.devtools.build.lib.syntax.SyntaxTreeVisitor;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/** Checks for operations that are deprecated */
public class DeprecatedApiChecker extends AstVisitorWithNameResolution {
  private static final String DEPRECATED_API = "deprecated-api";
  private static final String RULE_IMPL_RETURN = "deprecated-rule-impl-return";

  private final List<Issue> issues = new ArrayList<>();

  /** True if we are currently visiting a rule implementation. */
  private boolean visitingRuleImplementation;

  /** Set of functions that are used as rule implementation. */
  private final Set<String> ruleImplSet = Sets.newHashSet();

  private DeprecatedApiChecker() {}

  public static List<Issue> check(BuildFileAST ast) {
    DeprecatedApiChecker checker = new DeprecatedApiChecker();
    checker.inferRuleImpl(ast);
    checker.visit(ast);
    return checker.issues;
  }

  /**
   * Convert a dotted expression to string, e.g. rule -> "rule" attr.label -> "attr.label"
   *
   * <p>If input contains anything else than Identifier or DotExpression, return empty string.
   */
  private static String dottedExpressionToString(Expression e) {
    if (e instanceof Identifier) {
      return ((Identifier) e).getName();
    }
    if (e instanceof DotExpression) {
      String result = dottedExpressionToString(((DotExpression) e).getObject());
      if (!result.isEmpty()) {
        return result + "." + ((DotExpression) e).getField().getName();
      }
    }

    return "";
  }

  private void inferRuleImpl(BuildFileAST ast) {
    new SyntaxTreeVisitor() {

      @Override
      public void visit(FuncallExpression node) {
        // Collect all 'x' that match this pattern:
        //   rule(implementation=x, ...)
        Expression fct = node.getFunction();
        if (!(fct instanceof Identifier) || !((Identifier) fct).getName().equals("rule")) {
          return;
        }

        boolean firstArg = true;
        for (Argument.Passed arg : node.getArguments()) {
          if (!"implementation".equals(arg.getName()) && (!firstArg || arg.isKeyword())) {
            firstArg = false;
            continue;
          }
          firstArg = false;
          Expression val = arg.getValue();
          if (val instanceof Identifier) {
            ruleImplSet.add(((Identifier) val).getName());
          }
        }
      }
    }.visit(ast);
  }

  private static final ImmutableMap<String, String> deprecatedMethods =
      ImmutableMap.<String, String>builder()
          .put("ctx.action", "Use ctx.actions.run or ctx.actions.run_shell.")
          .put("ctx.default_provider", "Use DefaultInfo.")
          .put("ctx.empty_action", "Use ctx.actions.do_nothing.")
          .put("ctx.expand_make_variables", "Use ctx.var to access the variables.")
          .put("ctx.file_action", "Use ctx.actions.write.")
          .put("ctx.new_file", "Use ctx.actions.declare_file.")
          .put("ctx.template_action", "Use ctx.actions.expand_template.")
          .put("PACKAGE_NAME", "Use native.package_name().")
          .put("REPOSITORY_NAME", "Use native.repository_name().")
          .put("FileType", "Use a list of strings.")
          .put(
              "ctx.outputs.executable",
              "See https://docs.bazel.build/versions/master/skylark/"
                  + "rules.html#executable-rules-and-test-rules")
          .build();

  private void checkDeprecated(Expression node) {
    String name = dottedExpressionToString(node);
    if (deprecatedMethods.containsKey(name)) {
      issues.add(
          Issue.create(
              DEPRECATED_API,
              name + " is deprecated: " + deprecatedMethods.get(name),
              node.getLocation()));
    }
  }

  @Override
  public void visit(Identifier node) {
    super.visit(node);
    checkDeprecated(node);
  }

  @Override
  public void visit(DotExpression node) {
    super.visit(node);
    checkDeprecated(node);
  }

  @Override
  public void visit(ReturnStatement node) {
    super.visit(node);

    // Check that rule implementation functions don't return a call to `struct`.
    if (!visitingRuleImplementation) {
      return;
    }
    Expression e = node.getReturnExpression();
    if (e == null) {
      return;
    }
    if (!(e instanceof FuncallExpression)) {
      return;
    }
    String fctName = dottedExpressionToString(((FuncallExpression) e).getFunction());
    if (fctName.equals("struct")) {
      issues.add(
          Issue.create(
              RULE_IMPL_RETURN,
              "Avoid using the legacy provider syntax. Instead of returning a `struct` from a rule "
                  + "implementation function, return a list of providers: "
                  + "https://docs.bazel.build/versions/master/skylark/rules.html"
                  + "#migrating-from-legacy-providers",
              node.getLocation()));
    }
  }

  @Override
  public void visit(FunctionDefStatement node) {
    visitingRuleImplementation = ruleImplSet.contains(node.getIdentifier().getName());
    super.visit(node);
  }
}