aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/test/java/com/google/devtools/build/lib/syntax/FunctionTest.java
blob: ef87be7d50ab199198b57cb2179fa5a8aee8f3fc (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
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
// Copyright 2014 Google Inc. 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 static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.lib.syntax.util.EvaluationTestCase;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * A test class for functions and scoping.
 */
@RunWith(JUnit4.class)
public class FunctionTest extends EvaluationTestCase {

  @Test
  public void testFunctionDef() throws Exception {
    eval("def func(a,b,c):",
        "  a = 1",
        "  b = a\n");
    UserDefinedFunction stmt = (UserDefinedFunction) lookup("func");
    assertNotNull(stmt);
    assertThat(stmt.getName()).isEqualTo("func");
    assertThat(stmt.getFunctionSignature().getSignature().getShape().getMandatoryPositionals())
        .isEqualTo(3);
    assertThat(stmt.getStatements()).hasSize(2);
  }

  @Test
  public void testFunctionDefDuplicateArguments() throws Exception {
    setFailFast(false);
    parseFile("def func(a,b,a):",
        "  a = 1\n");
    assertContainsEvent("duplicate parameter name in function definition");
  }

  @Test
  public void testFunctionDefCallOuterFunc() throws Exception {
    List<Object> params = new ArrayList<>();
    createOuterFunction(params);
    eval("def func(a):",
        "  outer_func(a)",
        "func(1)",
        "func(2)");
    assertThat(params).containsExactly(1, 2).inOrder();
  }

  private void createOuterFunction(final List<Object> params) throws Exception {
    BaseFunction outerFunc = new BaseFunction("outer_func") {
      @Override
      public Object call(List<Object> args, Map<String, Object> kwargs, FuncallExpression ast,
          Environment env) throws EvalException, InterruptedException {
        params.addAll(args);
        return Runtime.NONE;
      }
    };
    update("outer_func", outerFunc);
  }

  @Test
  public void testFunctionDefNoEffectOutsideScope() throws Exception {
    update("a", 1);
    eval("def func():",
        "  a = 2",
        "func()\n");
    assertEquals(1, lookup("a"));
  }

  @Test
  public void testFunctionDefGlobalVaribleReadInFunction() throws Exception {
    eval("a = 1",
        "def func():",
        "  b = a",
        "  return b",
        "c = func()\n");
    assertEquals(1, lookup("c"));
  }

  @Test
  public void testFunctionDefLocalGlobalScope() throws Exception {
    eval("a = 1",
        "def func():",
        "  a = 2",
        "  b = a",
        "  return b",
        "c = func()\n");
    assertEquals(2, lookup("c"));
  }

  @Test
  public void testFunctionDefLocalVariableReferencedBeforeAssignment() throws Exception {
    checkEvalErrorContains("Variable 'a' is referenced before assignment.",
        "a = 1",
        "def func():",
        "  b = a",
        "  a = 2",
        "  return b",
        "c = func()\n");
  }

  @Test
  public void testFunctionDefLocalVariableReferencedAfterAssignment() throws Exception {
    eval("a = 1",
        "def func():",
        "  a = 2",
        "  b = a",
        "  a = 3",
        "  return b",
        "c = func()\n");
    assertEquals(2, lookup("c"));
  }

  @SuppressWarnings("unchecked")
  @Test
  public void testSkylarkGlobalComprehensionIsAllowed() throws Exception {
    eval("a = [i for i in [1, 2, 3]]\n");
    assertThat((Iterable<Object>) lookup("a")).containsExactly(1, 2, 3).inOrder();
  }

  @Test
  public void testFunctionReturn() throws Exception {
    eval("def func():",
        "  return 2",
        "b = func()\n");
    assertEquals(2, lookup("b"));
  }

  @Test
  public void testFunctionReturnFromALoop() throws Exception {
    eval("def func():",
        "  for i in [1, 2, 3, 4, 5]:",
        "    return i",
        "b = func()\n");
    assertEquals(1, lookup("b"));
  }

  @Test
  public void testFunctionExecutesProperly() throws Exception {
    eval("def func(a):",
        "  b = 1",
        "  if a:",
        "    b = 2",
        "  return b",
        "c = func(0)",
        "d = func(1)\n");
    assertEquals(1, lookup("c"));
    assertEquals(2, lookup("d"));
  }

  @Test
  public void testFunctionCallFromFunction() throws Exception {
    final List<Object> params = new ArrayList<>();
    createOuterFunction(params);
    eval("def func2(a):",
        "  outer_func(a)",
        "def func1(b):",
        "  func2(b)",
        "func1(1)",
        "func1(2)\n");
    assertThat(params).containsExactly(1, 2).inOrder();
  }

  @Test
  public void testFunctionCallFromFunctionReadGlobalVar() throws Exception {
    eval("a = 1",
        "def func2():",
        "  return a",
        "def func1():",
        "  return func2()",
        "b = func1()\n");
    assertEquals(1, lookup("b"));
  }

  @Test
  public void testSingleLineFunction() throws Exception {
    eval("def func(): return 'a'",
        "s = func()\n");
    assertEquals("a", lookup("s"));
  }

  @Test
  public void testFunctionReturnsDictionary() throws Exception {
    eval("def func(): return {'a' : 1}",
        "d = func()",
        "a = d['a']\n");
    assertEquals(1, lookup("a"));
  }

  @Test
  public void testFunctionReturnsList() throws Exception {
    eval("def func(): return [1, 2, 3]",
        "d = func()",
        "a = d[1]\n");
    assertEquals(2, lookup("a"));
  }

  @SuppressWarnings("unchecked")
  @Test
  public void testFunctionListArgumentsAreImmutable() throws Exception {
    eval("l = [1]",
        "def func(l):",
        "  l += [2]",
        "func(l)");
    assertThat((Iterable<Object>) lookup("l")).containsExactly(1);
  }

  @Test
  public void testFunctionDictArgumentsAreImmutable() throws Exception {
    eval("d = {'a' : 1}",
        "def func(d):",
        "  d += {'a' : 2}",
        "func(d)");
    assertEquals(ImmutableMap.of("a", 1), lookup("d"));
  }

  @Test
  public void testFunctionNameAliasing() throws Exception {
    eval("def func(a):",
        "  return a + 1",
        "alias = func",
        "r = alias(1)");
    assertEquals(2, lookup("r"));
  }

  @Test
  public void testCallingFunctionsWithMixedModeArgs() throws Exception {
    eval("def func(a, b, c):",
        "  return a + b + c",
        "v = func(1, c = 2, b = 3)");
    assertEquals(6, lookup("v"));
  }

  private String functionWithOptionalArgs() {
    return "def func(a, b = None, c = None):\n"
        + "  r = a + 'a'\n"
        + "  if b:\n"
        + "    r += 'b'\n"
        + "  if c:\n"
        + "    r += 'c'\n"
        + "  return r\n";
  }

  @Test
  public void testWhichOptionalArgsAreDefinedForFunctions() throws Exception {
    eval(functionWithOptionalArgs(),
        "v1 = func('1', 1, 1)",
        "v2 = func(b = 2, a = '2', c = 2)",
        "v3 = func('3')",
        "v4 = func('4', c = 1)\n");
    assertEquals("1abc", lookup("v1"));
    assertEquals("2abc", lookup("v2"));
    assertEquals("3a", lookup("v3"));
    assertEquals("4ac", lookup("v4"));
  }

  @Test
  public void testDefaultArguments() throws Exception {
    eval("def func(a, b = 'b', c = 'c'):",
        "  return a + b + c",
        "v1 = func('a', 'x', 'y')",
        "v2 = func(b = 'x', a = 'a', c = 'y')",
        "v3 = func('a')",
        "v4 = func('a', c = 'y')\n");
    assertEquals("axy", lookup("v1"));
    assertEquals("axy", lookup("v2"));
    assertEquals("abc", lookup("v3"));
    assertEquals("aby", lookup("v4"));
  }

  @Test
  public void testDefaultArgumentsInsufficientArgNum() throws Exception {
    checkEvalError("insufficient arguments received by func(a, b = \"b\", c = \"c\") "
        + "(got 0, expected at least 1)",
        "def func(a, b = 'b', c = 'c'):",
        "  return a + b + c",
        "func()");
  }

  @Test
  public void testKwargs() throws Exception {
    eval("def foo(a, b = 'b', *, c, d = 'd'):",
      "  return a + b + c + d",
      "args = {'a': 'x', 'c': 'z'}",
      "v1 = foo(**args)",
      "v2 = foo('x', c = 'c', d = 'e', **{'b': 'y'})",
      "v3 = foo(c = 'z', a = 'x', **{'b': 'y', 'd': 'f'})");
    assertEquals("xbzd", lookup("v1"));
    assertEquals("xyce", lookup("v2"));
    assertEquals("xyzf", lookup("v3"));
    UserDefinedFunction foo = (UserDefinedFunction) lookup("foo");
    assertEquals("foo(a, b = \"b\", *, c, d = \"d\")", foo.toString());
  }

  @Test
  public void testKwargsBadKey() throws Exception {
    checkEvalError("Keywords must be strings, not int",
        "def func(a, b): return a + b",
        "func('a', **{3: 1})");
  }

  @Test
  public void testKwargsIsNotDict() throws Exception {
    checkEvalError("Argument after ** must be a dictionary, not int",
        "def func(a, b): return a + b",
        "func('a', **42)");
  }

  @Test
  public void testKwargsCollision() throws Exception {
    checkEvalError("argument 'b' passed both by position and by name in call to func(a, b)",
        "def func(a, b): return a + b",
        "func('a', 'b', **{'b': 'foo'})");
  }

  @Test
  public void testKwargsCollisionWithNamed() throws Exception {
    checkEvalError("duplicate keyword 'b' in call to func",
        "def func(a, b): return a + b",
        "func('a', b = 'b', **{'b': 'foo'})");
  }

  @Test
  public void testDefaultArguments2() throws Exception {
    eval("a = 2",
        "def foo(x=a): return x",
        "def bar():",
        "  a = 3",
        "  return foo()",
        "v = bar()\n");
    assertEquals(2, lookup("v"));
  }

  @Test
  public void testMixingPositionalOptional() throws Exception {
    eval("def f(name, value = '', optional = ''): return value",
        "v = f('name', 'value')\n");
    assertEquals("value", lookup("v"));
  }

  @Test
  public void testStarArg() throws Exception {
    eval("def f(name, value = '1', optional = '2'): return name + value + optional",
        "v1 = f(*['name', 'value'])",
        "v2 = f('0', *['name', 'value'])",
        "v3 = f('0', *['b'], optional = '3')",
        "v4 = f(*[],name='a')\n");
    assertEquals("namevalue2", lookup("v1"));
    assertEquals("0namevalue", lookup("v2"));
    assertEquals("0b3", lookup("v3"));
    assertEquals("a12", lookup("v4"));
  }

  @Test
  public void testStarParam() throws Exception {
    eval("def f(name, value = '1', *rest, mandatory, optional = '2'):",
        "  r = name + value + mandatory + optional + '|'",
        "  for x in rest: r += x",
        "  return r",
        "v1 = f('a', 'b', mandatory = 'z')",
        "v2 = f('a', 'b', 'c', 'd', mandatory = 'z')",
        "v3 = f('a', *['b', 'c', 'd'], mandatory = 'y', optional = 'z')",
        "v4 = f(*['a'], **{'value': 'b', 'mandatory': 'c'})",
        "v5 = f('a', 'b', 'c', *['d', 'e'], mandatory = 'f', **{'optional': 'g'})\n");
    assertEquals("abz2|", lookup("v1"));
    assertEquals("abz2|cd", lookup("v2"));
    assertEquals("abyz|cd", lookup("v3"));
    assertEquals("abc2|", lookup("v4"));
    assertEquals("abfg|cde", lookup("v5"));
  }
}