aboutsummaryrefslogtreecommitdiffstats
path: root/spec/lib/builtins/fn_spec.moon
blob: 337a4278c52c686b72bbef631d9dd2d865517fd7 (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
import TestPilot from require 'spec.test_setup'
import T, Struct, Array, Constant from require 'alv'

describe "function", ->
  COPILOT = TestPilot!

  it "returns constant results when constant", ->
    rt = COPILOT\eval_once '
    (import* math)

    (defn my-plus [a b]
      (+ a b))

    (my-plus 2 3)'
    assert.is.true rt\is_const!
    assert.is.equal (Constant.num 5), rt.result

  it "can have empty arguments", ->
    rt = COPILOT\eval_once '
    (import* math)

    (defn my-plus []
      (+ 1 2))

    (my-plus)'
    assert.is.equal (Constant.num 3), rt.result

  it "checks argument arity when invoked", ->
    err = assert.has.error -> COPILOT\eval_once '
    ([1]import* math)

    ([2]defn my-plus [a b]
      ([4]+ a b))

    ([3]my-plus 2)'
    assert.matches "argument error: expected 2 arguments, found 1", err
    assert.matches "while invoking function 'my%-plus' at %[3%]", err

    err = assert.has.error -> COPILOT\eval_once '
    ([1]import* math)

    ([2]defn my-plus [a b]
      ([4]+ a b))

    ([3]my-plus 2 3 4)'
    assert.matches "argument error: expected 2 arguments, found 3", err
    assert.matches "while invoking function 'my%-plus' at %[3%]", err

  it "can be anonymously invoked", ->
    rt = COPILOT\eval_once '
    ([1]
      ([2]fn [a b] b)
      3 4)'
    assert.is.equal (Constant.num 4), rt\const!

    err = assert.has.error -> COPILOT\eval_once '
    ([1]
      ([2]fn [a b] b)
      3)'
    assert.matches "argument error: expected 2 arguments, found 1", err
    assert.matches "while invoking function %(unnamed%) at %[1%]", err