summaryrefslogtreecommitdiff
path: root/lib/elixir/test/elixir/kernel/comprehension_test.exs
blob: 7c1ebf7615d299d21b5d7aff9b89021157b3831a (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
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
Code.require_file("../test_helper.exs", __DIR__)

defmodule Kernel.ComprehensionTest do
  use ExUnit.Case, async: true

  import ExUnit.CaptureIO
  require Integer

  defmodule Pdict do
    defstruct []

    defimpl Collectable do
      def into(struct) do
        fun = fn
          _, {:cont, x} -> Process.put(:into_cont, [x | Process.get(:into_cont)])
          _, :done -> Process.put(:into_done, true)
          _, :halt -> Process.put(:into_halt, true)
        end

        {struct, fun}
      end
    end
  end

  defp to_bin(x) do
    <<x>>
  end

  defp nilly, do: nil

  ## Enum comprehensions (the common case)

  test "for comprehensions" do
    enum = 1..3
    assert for(x <- enum, do: x * 2) == [2, 4, 6]
  end

  test "for comprehensions with matching" do
    assert for({_, x} <- 1..3, do: x * 2) == []
  end

  test "for comprehensions with pin matching" do
    maps = [x: 1, y: 2, x: 3]
    assert for({:x, v} <- maps, do: v * 2) == [2, 6]
    x = :x
    assert for({^x, v} <- maps, do: v * 2) == [2, 6]
  end

  test "for comprehensions with guards" do
    assert for(x when x < 4 <- 1..10, do: x) == [1, 2, 3]
    assert for(x when x == 3 when x == 7 <- 1..10, do: x) == [3, 7]
  end

  test "for comprehensions with guards and filters" do
    assert for(
             {var, _}
             when is_atom(var) <- [{:foo, 1}, {2, :bar}],
             var = Atom.to_string(var),
             do: var
           ) == ["foo"]
  end

  test "for comprehensions with map key matching" do
    maps = [%{x: 1}, %{y: 2}, %{x: 3}]
    assert for(%{x: v} <- maps, do: v * 2) == [2, 6]
    x = :x
    assert for(%{^x => v} <- maps, do: v * 2) == [2, 6]
  end

  test "for comprehensions with filters" do
    assert for(x <- 1..3, x > 1, x < 3, do: x * 2) == [4]
  end

  test "for comprehensions with unique values" do
    list = [1, 1, 2, 3]
    assert for(x <- list, uniq: true, do: x * 2) == [2, 4, 6]
    assert for(x <- list, uniq: true, into: [], do: x * 2) == [2, 4, 6]
    assert for(x <- list, uniq: true, into: %{}, do: {x, 1}) == %{1 => 1, 2 => 1, 3 => 1}
    assert for(x <- list, uniq: true, into: "", do: to_bin(x * 2)) == <<2, 4, 6>>
    assert for(<<x <- "abcabc">>, uniq: true, into: "", do: to_bin(x)) == "abc"

    Process.put(:into_cont, [])
    Process.put(:into_done, false)
    Process.put(:into_halt, false)

    for x <- list, uniq: true, into: %Pdict{} do
      x * 2
    end

    assert Process.get(:into_cont) == [6, 4, 2]
    assert Process.get(:into_done)
    refute Process.get(:into_halt)

    assert_raise RuntimeError, "oops", fn ->
      for _ <- [1, 2, 3], uniq: true, into: %Pdict{}, do: raise("oops")
    end

    assert Process.get(:into_halt)
  end

  test "nested for comprehensions with unique values" do
    assert for(x <- [1, 1, 2], uniq: true, do: for(y <- [3, 3], uniq: true, do: x * y)) == [
             [3],
             [6]
           ]

    assert for(<<x <- "abcabc">>,
             uniq: true,
             into: "",
             do: for(<<y <- "zz">>, uniq: true, into: "", do: to_bin(x) <> to_bin(y))
           ) == "azbzcz"
  end

  test "for comprehensions with nilly filters" do
    assert for(x <- 1..3, nilly(), do: x * 2) == []
  end

  test "for comprehensions with errors on filters" do
    assert_raise ArgumentError, fn ->
      for x <- 1..3, hd(x), do: x * 2
    end
  end

  test "for comprehensions with variables in filters" do
    assert for(x <- 1..3, y = x + 1, y > 2, z = y, do: x * z) == [6, 12]
  end

  test "for comprehensions with two enum generators" do
    assert for(
             x <- [1, 2, 3],
             y <- [4, 5, 6],
             do: x * y
           ) == [4, 5, 6, 8, 10, 12, 12, 15, 18]
  end

  test "for comprehensions with two enum generators and filters" do
    assert for(
             x <- [1, 2, 3],
             y <- [4, 5, 6],
             y / 2 == x,
             do: x * y
           ) == [8, 18]
  end

  test "for comprehensions generators precedence" do
    assert for({_, _} = x <- [foo: :bar], do: x) == [foo: :bar]
  end

  test "for comprehensions with shadowing" do
    assert for(
             a <-
               (
                 b = 1
                 _ = b
                 [1]
               ),
             b <- [2],
             do: a + b
           ) == [3]
  end

  test "for comprehensions with binary, enum generators and filters" do
    assert for(x <- [1, 2, 3], <<(y <- <<4, 5, 6>>)>>, y / 2 == x, do: x * y) == [8, 18]
  end

  test "for comprehensions into list" do
    enum = 1..3
    assert for(x <- enum, into: [], do: x * 2) == [2, 4, 6]
  end

  test "for comprehensions into binary" do
    enum = 0..3

    assert (for x <- enum, into: "" do
              to_bin(x * 2)
            end) == <<0, 2, 4, 6>>

    assert (for x <- enum, into: "" do
              if Integer.is_even(x), do: <<x::size(2)>>, else: <<x::size(1)>>
            end) == <<0::size(2), 1::size(1), 2::size(2), 3::size(1)>>
  end

  test "for comprehensions into dynamic binary" do
    enum = 0..3
    into = ""

    assert (for x <- enum, into: into do
              to_bin(x * 2)
            end) == <<0, 2, 4, 6>>

    assert (for x <- enum, into: into do
              if Integer.is_even(x), do: <<x::size(2)>>, else: <<x::size(1)>>
            end) == <<0::size(2), 1::size(1), 2::size(2), 3::size(1)>>

    into = <<7::size(1)>>

    assert (for x <- enum, into: into do
              to_bin(x * 2)
            end) == <<7::size(1), 0, 2, 4, 6>>

    assert (for x <- enum, into: into do
              if Integer.is_even(x), do: <<x::size(2)>>, else: <<x::size(1)>>
            end) == <<7::size(1), 0::size(2), 1::size(1), 2::size(2), 3::size(1)>>
  end

  test "for comprehensions where value is not used" do
    enum = 1..3

    assert capture_io(fn ->
             for x <- enum, do: IO.puts(x)
             nil
           end) == "1\n2\n3\n"
  end

  test "for comprehensions with into" do
    Process.put(:into_cont, [])
    Process.put(:into_done, false)
    Process.put(:into_halt, false)

    for x <- 1..3, into: %Pdict{} do
      x * 2
    end

    assert Process.get(:into_cont) == [6, 4, 2]
    assert Process.get(:into_done)
    refute Process.get(:into_halt)
  end

  test "for comprehension with into leading to errors" do
    Process.put(:into_cont, [])
    Process.put(:into_done, false)
    Process.put(:into_halt, false)

    catch_error(
      for x <- 1..3, into: %Pdict{} do
        if x > 2, do: raise("oops"), else: x
      end
    )

    assert Process.get(:into_cont) == [2, 1]
    refute Process.get(:into_done)
    assert Process.get(:into_halt)
  end

  test "for comprehension with into, generators and filters" do
    Process.put(:into_cont, [])

    for x <- 1..3, Integer.is_odd(x), <<y <- "hello">>, into: %Pdict{} do
      x + y
    end

    assert IO.iodata_to_binary(Process.get(:into_cont)) == "roohkpmmfi"
  end

  test "for comprehensions of map into map" do
    enum = %{a: 2, b: 3}
    assert for({k, v} <- enum, into: %{}, do: {k, v * v}) == %{a: 4, b: 9}
  end

  test "for comprehensions with reduce, generators and filters" do
    acc =
      for x <- 1..3, Integer.is_odd(x), <<y <- "hello">>, reduce: %{} do
        acc -> Map.update(acc, x, [y], &[y | &1])
      end

    assert acc == %{1 => 'olleh', 3 => 'olleh'}
  end

  test "for comprehensions with matched reduce" do
    acc =
      for entry <- [1, 2, 3], reduce: {:ok, nil} do
        {:ok, _} ->
          {:ok, entry}

        {:error, _} = error ->
          error
      end

    assert acc == {:ok, 3}
  end

  ## List generators (inlined by the compiler)

  test "list for comprehensions" do
    list = [1, 2, 3]
    assert for(x <- list, do: x * 2) == [2, 4, 6]
  end

  test "list for comprehensions with matching" do
    assert for({_, x} <- [1, 2, a: 3, b: 4, c: 5], do: x * 2) == [6, 8, 10]
  end

  test "list for comprehension matched to '_' on last line of block" do
    assert (if true_fun() do
              _ = for x <- [1, 2, 3], do: x * 2
            end) == [2, 4, 6]
  end

  defp true_fun(), do: true

  test "list for comprehensions with filters" do
    assert for(x <- [1, 2, 3], x > 1, x < 3, do: x * 2) == [4]
  end

  test "list for comprehensions with nilly filters" do
    assert for(x <- [1, 2, 3], nilly(), do: x * 2) == []
  end

  test "list for comprehensions with errors on filters" do
    assert_raise ArgumentError, fn ->
      for x <- [1, 2, 3], hd(x), do: x * 2
    end
  end

  test "list for comprehensions with variables in filters" do
    assert for(x <- [1, 2, 3], y = x + 1, y > 2, z = y, do: x * z) == [6, 12]
  end

  test "list for comprehensions into list" do
    enum = [1, 2, 3]
    assert for(x <- enum, into: [], do: x * 2) == [2, 4, 6]
  end

  test "list for comprehensions into binary" do
    enum = [0, 1, 2, 3]

    assert (for x <- enum, into: "" do
              to_bin(x * 2)
            end) == <<0, 2, 4, 6>>

    assert (for x <- enum, into: "" do
              if Integer.is_even(x), do: <<x::size(2)>>, else: <<x::size(1)>>
            end) == <<0::size(2), 1::size(1), 2::size(2), 3::size(1)>>
  end

  test "list for comprehensions into dynamic binary" do
    enum = [0, 1, 2, 3]
    into = ""

    assert (for x <- enum, into: into do
              to_bin(x * 2)
            end) == <<0, 2, 4, 6>>

    assert (for x <- enum, into: into do
              if Integer.is_even(x), do: <<x::size(2)>>, else: <<x::size(1)>>
            end) == <<0::size(2), 1::size(1), 2::size(2), 3::size(1)>>

    into = <<7::size(1)>>

    assert (for x <- enum, into: into do
              to_bin(x * 2)
            end) == <<7::size(1), 0, 2, 4, 6>>

    assert (for x <- enum, into: into do
              if Integer.is_even(x), do: <<x::size(2)>>, else: <<x::size(1)>>
            end) == <<7::size(1), 0::size(2), 1::size(1), 2::size(2), 3::size(1)>>
  end

  test "list for comprehensions where value is not used" do
    enum = [1, 2, 3]

    assert capture_io(fn ->
             for x <- enum, do: IO.puts(x)
             nil
           end) == "1\n2\n3\n"
  end

  test "list for comprehensions with reduce, generators and filters" do
    acc =
      for x <- [1, 2, 3], Integer.is_odd(x), <<y <- "hello">>, reduce: %{} do
        acc -> Map.update(acc, x, [y], &[y | &1])
      end

    assert acc == %{1 => 'olleh', 3 => 'olleh'}
  end

  ## Binary generators (inlined by the compiler)

  test "binary for comprehensions" do
    bin = <<1, 2, 3>>
    assert for(<<x <- bin>>, do: x * 2) == [2, 4, 6]
  end

  test "binary for comprehensions with inner binary" do
    bin = <<1, 2, 3>>
    assert for(<<(<<x>> <- bin)>>, do: x * 2) == [2, 4, 6]
  end

  test "binary for comprehensions with two generators" do
    assert for(<<(x <- <<1, 2, 3>>)>>, <<(y <- <<4, 5, 6>>)>>, y / 2 == x, do: x * y) == [8, 18]
  end

  test "binary for comprehensions into list" do
    bin = <<1, 2, 3>>
    assert for(<<x <- bin>>, into: [], do: x * 2) == [2, 4, 6]
  end

  test "binary for comprehensions into binary" do
    bin = <<0, 1, 2, 3>>

    assert (for <<x <- bin>>, into: "" do
              to_bin(x * 2)
            end) == <<0, 2, 4, 6>>

    assert (for <<x <- bin>>, into: "" do
              if Integer.is_even(x), do: <<x::size(2)>>, else: <<x::size(1)>>
            end) == <<0::size(2), 1::size(1), 2::size(2), 3::size(1)>>
  end

  test "binary for comprehensions into dynamic binary" do
    bin = <<0, 1, 2, 3>>
    into = ""

    assert (for <<x <- bin>>, into: into do
              to_bin(x * 2)
            end) == <<0, 2, 4, 6>>

    assert (for <<x <- bin>>, into: into do
              if Integer.is_even(x), do: <<x::size(2)>>, else: <<x::size(1)>>
            end) == <<0::size(2), 1::size(1), 2::size(2), 3::size(1)>>

    into = <<7::size(1)>>

    assert (for <<x <- bin>>, into: into do
              to_bin(x * 2)
            end) == <<7::size(1), 0, 2, 4, 6>>

    assert (for <<x <- bin>>, into: into do
              if Integer.is_even(x), do: <<x::size(2)>>, else: <<x::size(1)>>
            end) == <<7::size(1), 0::size(2), 1::size(1), 2::size(2), 3::size(1)>>
  end

  test "binary for comprehensions with literal matches" do
    # Integers
    bin = <<1, 2, 1, 3, 1, 4>>
    assert for(<<1, x <- bin>>, into: "", do: to_bin(x)) == <<2, 3, 4>>
    assert for(<<1, x <- bin>>, into: %{}, do: {x, x}) == %{2 => 2, 3 => 3, 4 => 4}

    bin = <<1, 2, 3, 1, 4>>
    assert for(<<1, x <- bin>>, into: "", do: to_bin(x)) == <<2>>
    assert for(<<1, x <- bin>>, into: %{}, do: {x, x}) == %{2 => 2}

    # Floats
    bin = <<1.0, 2, 1.0, 3, 1.0, 4>>
    assert for(<<1.0, x <- bin>>, into: "", do: to_bin(x)) == <<2, 3, 4>>
    assert for(<<1.0, x <- bin>>, into: %{}, do: {x, x}) == %{2 => 2, 3 => 3, 4 => 4}

    bin = <<1.0, 2, 3, 1.0, 4>>
    assert for(<<1.0, x <- bin>>, into: "", do: to_bin(x)) == <<2>>
    assert for(<<1.0, x <- bin>>, into: %{}, do: {x, x}) == %{2 => 2}

    # Binaries
    bin = <<"foo", 2, "foo", 3, "foo", 4>>
    assert for(<<"foo", x <- bin>>, into: "", do: to_bin(x)) == <<2, 3, 4>>
    assert for(<<"foo", x <- bin>>, into: %{}, do: {x, x}) == %{2 => 2, 3 => 3, 4 => 4}

    bin = <<"foo", 2, 3, "foo", 4>>
    assert for(<<"foo", x <- bin>>, into: "", do: to_bin(x)) == <<2>>
    assert for(<<"foo", x <- bin>>, into: %{}, do: {x, x}) == %{2 => 2}

    bin = <<"foo", 2, 3, 4, "foo", 5>>
    assert for(<<"foo", x <- bin>>, into: "", do: to_bin(x)) == <<2>>
    assert for(<<"foo", x <- bin>>, into: %{}, do: {x, x}) == %{2 => 2}
  end

  test "binary for comprehensions with variable size" do
    s = 16
    bin = <<1, 2, 3, 4, 5, 6>>
    assert for(<<x::size(s) <- bin>>, into: "", do: to_bin(div(x, 2))) == <<129, 130, 131>>

    # Aligned
    bin = <<8, 1, 16, 2, 3>>
    assert for(<<s, x::size(s) <- bin>>, into: "", do: <<x::size(s)>>) == <<1, 2, 3>>
    assert for(<<s, x::size(s) <- bin>>, into: %{}, do: {s, x}) == %{8 => 1, 16 => 515}

    # Unaligned
    bin = <<8, 1, 32, 2, 3>>
    assert for(<<s, x::size(s) <- bin>>, into: "", do: <<x::size(s)>>) == <<1>>
    assert for(<<s, x::size(s) <- bin>>, into: %{}, do: {s, x}) == %{8 => 1}
  end

  test "binary for comprehensions where value is not used" do
    bin = <<1, 2, 3>>

    assert capture_io(fn ->
             for <<x <- bin>>, do: IO.puts(x)
             nil
           end) == "1\n2\n3\n"
  end

  test "binary for comprehensions with reduce, generators and filters" do
    bin = <<1, 2, 3>>

    acc =
      for <<x <- bin>>, Integer.is_odd(x), <<y <- "hello">>, reduce: %{} do
        acc -> Map.update(acc, x, [y], &[y | &1])
      end

    assert acc == %{1 => 'olleh', 3 => 'olleh'}
  end
end