aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/main/java/com/google/devtools/build/lib/syntax/FunctionDefStatement.java
blob: 994f6f2b3db15c453733e6c9c2b0b3ecf3135fb9 (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
// 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.syntax;

import com.google.common.collect.ImmutableList;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Syntax node for a function definition.
 */
public final class FunctionDefStatement extends Statement {

  private final Identifier identifier;
  private final FunctionSignature.WithValues<Expression, Expression> signature;
  private final ImmutableList<Statement> statements;
  private final ImmutableList<Parameter<Expression, Expression>> parameters;

  public FunctionDefStatement(Identifier identifier,
      Iterable<Parameter<Expression, Expression>> parameters,
      FunctionSignature.WithValues<Expression, Expression> signature,
      Iterable<Statement> statements) {
    this.identifier = identifier;
    this.parameters = ImmutableList.copyOf(parameters);
    this.signature = signature;
    this.statements = ImmutableList.copyOf(statements);
  }

  @Override
  void doExec(Environment env) throws EvalException, InterruptedException {
    List<Expression> defaultExpressions = signature.getDefaultValues();
    ArrayList<Object> defaultValues = null;

    if (defaultExpressions != null) {
      defaultValues = new ArrayList<>(defaultExpressions.size());
      for (Expression expr : defaultExpressions) {
        defaultValues.add(expr.eval(env));
      }
    }

    FunctionSignature sig = signature.getSignature();
    if (env.getSemantics().incompatibleDisallowKeywordOnlyArgs
        && sig.getShape().getMandatoryNamedOnly() > 0) {
      throw new EvalException(
          getLocation(),
          "Keyword-only argument is forbidden. You can temporarily disable this "
              + "error using the flag --incompatible_disallow_keyword_only_args=false");
    }

    env.update(
        identifier.getName(),
        new UserDefinedFunction(
            identifier,
            FunctionSignature.WithValues.create(sig, defaultValues, /*types=*/null),
            statements,
            env.getGlobals()));
  }

  @Override
  public void prettyPrint(Appendable buffer, int indentLevel) throws IOException {
    printIndent(buffer, indentLevel);
    buffer.append("def ");
    identifier.prettyPrint(buffer);
    buffer.append('(');
    String sep = "";
    for (Parameter<?, ?> param : parameters) {
      buffer.append(sep);
      param.prettyPrint(buffer);
      sep = ", ";
    }
    buffer.append("):\n");
    printSuite(buffer, statements, indentLevel);
  }

  @Override
  public String toString() {
    return "def " + identifier + "(" + signature + "): ...\n";
  }

  public Identifier getIdentifier() {
    return identifier;
  }

  public ImmutableList<Statement> getStatements() {
    return statements;
  }

  public ImmutableList<Parameter<Expression, Expression>> getParameters() {
    return parameters;
  }

  public FunctionSignature.WithValues<Expression, Expression> getSignature() {
    return signature;
  }

  @Override
  public void accept(SyntaxTreeVisitor visitor) {
    visitor.visit(this);
  }

  @Override
  void validate(final ValidationEnvironment env) throws EvalException {
    FunctionSignature sig = signature.getSignature();
    FunctionSignature.Shape shape = sig.getShape();
    ImmutableList<String> names = sig.getNames();
    List<Expression> defaultExpressions = signature.getDefaultValues();

    int positionals = shape.getPositionals();
    int mandatoryPositionals = shape.getMandatoryPositionals();
    int namedOnly = shape.getNamedOnly();
    int mandatoryNamedOnly = shape.getMandatoryNamedOnly();
    boolean starArg = shape.hasStarArg();
    boolean kwArg = shape.hasKwArg();
    int named = positionals + namedOnly;
    int args = named + (starArg ? 1 : 0) + (kwArg ? 1 : 0);
    int startOptionals = mandatoryPositionals;
    int endOptionals = named - mandatoryNamedOnly;

    env.openScope();
    int j = 0; // index for the defaultExpressions
    for (int i = 0; i < args; i++) {
      String name = names.get(i);
      if (startOptionals <= i && i < endOptionals) {
        defaultExpressions.get(j++).validate(env);
      }
      env.declare(name, getLocation());
    }
    for (Statement stmts : statements) {
      stmts.validate(env);
    }
    env.closeScope();
  }
}