File: functions.hy

package info (click to toggle)
hy 1.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,632 kB
  • sloc: python: 7,299; makefile: 38; sh: 27
file content (363 lines) | stat: -rw-r--r-- 8,580 bytes parent folder | download
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
;; Tests of `fn`, `defn`, `return`, and `yield`

(import
  asyncio
  typing [List]
  pytest)


(defn test-fn []
  (setv square (fn [x] (* x x)))
  (assert (= 4 (square 2)))
  (setv lambda_list (fn [test #* args] #(test args)))
  (assert (= #(1 #(2 3)) (lambda_list 1 2 3))))


(defn test-immediately-call-lambda []
  (assert (= 2 ((fn [] (+ 1 1))))))


(defn test-fn-return []
  (setv fn-test ((fn [] (fn [] (+ 1 1)))))
  (assert (= (fn-test) 2))
  (setv fn-test (fn []))
  (assert (= (fn-test) None)))


(defn test-fn-async []
  (assert (= (asyncio.run ((fn :async [] (await (asyncio.sleep 0)) [1 2 3])))
             [1 2 3])))


(defn test-defn-evaluation-order []
  (setv acc [])
  (defn my-fun []
    (.append acc "Foo")
    (.append acc "Bar")
    (.append acc "Baz"))
  (my-fun)
  (assert (= acc ["Foo" "Bar" "Baz"])))


(defn test-defn-return []
  (defn my-fun [x]
    (+ x 1))
  (assert (= 43 (my-fun 42))))


(defn test-defn-lambdakey []
  "Test defn with a `&symbol` function name."
  (defn &hy [] 1)
  (assert (= (&hy) 1)))


(defn test-defn-evaluation-order-with-do []
  (setv acc [])
  (defn my-fun []
    (do
     (.append acc "Foo")
     (.append acc "Bar")
     (.append acc "Baz")))
  (my-fun)
  (assert (= acc ["Foo" "Bar" "Baz"])))


(defn test-defn-do-return []
  (defn my-fun [x]
    (do
     (+ x 42)  ; noop
     (+ x 1)))
  (assert (= 43 (my-fun 42))))


(defn test-defn-dunder-name []
  "`defn` should preserve `__name__`."

  (defn phooey [x]
    (+ x 1))
  (assert (= phooey.__name__ "phooey"))

  (defn mooey [x]
    (+= x 1)
    x)
  (assert (= mooey.__name__ "mooey")))


(defn test-defn-annotations []

  (defn #^ int f [#^ (get List int) p1 p2 #^ str p3 #^ str [o1 None] #^ int [o2 0]
           #^ str #* rest #^ str k1 #^ int [k2 0] #^ bool #** kwargs])

  (assert (is (. f __annotations__ ["return"]) int))
  (for [[k v] (.items (dict
                        :p1 (get List int)  :p3 str  :o1 str  :o2 int
                        :k1 str  :k2 int  :kwargs bool))]
    (assert (= (. f __annotations__ [k]) v))))


(do-mac (when hy.compat.PY3_12 '(defn test-type-params []
  (import tests.resources.tp :as ttp)

  (defn foo [])
  (assert (= (ttp.show foo) []))

  ; `defn` with a type parameter
  (defn :tp [T] #^ T foo [#^ T x]
    (+ x 1))
  (assert (= (foo 3) 4))
  (assert (= (ttp.show foo) [[ttp.TypeVar "T" None #()]]))

  ; `fn` with a type parameter
  (setv foo (fn :tp [T] #^ T [#^ T x]
    (+ x 2)))
  (assert (= (foo 3) 5))
  (assert (= (ttp.show foo) [[ttp.TypeVar "T" None #()]]))

  ; Bounds and constraints
  (defn :tp [#^ int T] foo [])
  (assert (= (ttp.show foo) [[ttp.TypeVar "T" int #()]]))
  (defn :tp [#^ #(int str) T] foo [])
  (assert (= (ttp.show foo) [[ttp.TypeVar "T" None #(int str)]]))

  ; `TypeVarTuple`s and `ParamSpec`s
  (defn :tp [#* T] foo [])
  (assert (= (ttp.show foo) [[ttp.TypeVarTuple "T" None #()]]))
  (defn :tp [#** T] foo [])
  (assert (= (ttp.show foo) [[ttp.ParamSpec "T" None #()]]))

  ; A more complex case
  (defn
    :tp [A  #^ int B  #* C  #** D  #* E  #^ #(bool float) F]
    foo [])
  (assert (= (ttp.show foo) [
    [ttp.TypeVar "A" None #()]
    [ttp.TypeVar "B" int #()]
    [ttp.TypeVarTuple "C" None #()]
    [ttp.ParamSpec "D" None #()]
    [ttp.TypeVarTuple "E" None #()]
    [ttp.TypeVar "F" None #(bool float)]]))

  ; Illegal attempts to annotate unpacking
  (with [(pytest.raises hy.errors.HySyntaxError)]
    (hy.eval '(defn :tp [#^ int #* T] foo [])))
  (with [(pytest.raises hy.errors.HySyntaxError)]
    (hy.eval '(defn :tp [#^ #(int str) #** T] foo []))))))


(defn test-lambda-keyword-lists []
  (defn foo [x #* xs #** kw] [x xs kw])
  (assert (= (foo 10 20 30) [10 #(20 30) {}])))


(defn test-optional-arguments []
  (defn foo [a b [c None] [d 42]] [a b c d])
  (assert (= (foo 1 2) [1 2 None 42]))
  (assert (= (foo 1 2 3) [1 2 3 42]))
  (assert (= (foo 1 2 3 4) [1 2 3 4])))


(defn test-kwonly []
  ;; keyword-only with default works
  (defn kwonly-foo-default-false [* [foo False]] foo)
  (assert (= (kwonly-foo-default-false) False))
  (assert (= (kwonly-foo-default-false :foo True) True))
  ;; keyword-only without default ...
  (defn kwonly-foo-no-default [* foo] foo)
  (with [e (pytest.raises TypeError)]
    (kwonly-foo-no-default))
  (assert (in "missing 1 required keyword-only argument: 'foo'"
              (. e value args [0])))
  ;; works
  (assert (= (kwonly-foo-no-default :foo "quux") "quux"))
  ;; keyword-only with other arg types works
  (defn function-of-various-args [a b #* args foo #** kwargs]
    #(a b args foo kwargs))
  (assert (= (function-of-various-args 1 2 3 4 :foo 5 :bar 6 :quux 7)
             #(1 2 #(3 4)  5 {"bar" 6 "quux" 7}))))


(defn test-only-parse-lambda-list-in-defn []
  (with [(pytest.raises NameError)]
    (setv x [#* spam]  y 1)))


(defn test-defn-async []
  (defn :async coro-test []
    (await (asyncio.sleep 0))
    [1 2 3])
  (assert (= (asyncio.run (coro-test)) [1 2 3])))


(defn test-no-async-gen-return []
  ; https://github.com/hylang/hy/issues/2523
  (defn :async runner [gen]
    (setv vals [])
    (for [:async val (gen)]
      (.append vals val))
    vals)
  (defn :async naysayer []
    (yield "nope"))
  (assert (= (asyncio.run (runner naysayer)) ["nope"]))
  (assert (= (asyncio.run (runner (fn :async [] (yield "dope!")) ["dope!"])))))


(defn test-root-set-correctly []
  ; https://github.com/hylang/hy/issues/2475
  ((. defn) not-async [] "ok")
  (assert (= (not-async) "ok"))
  (require builtins)
  (builtins.defn also-not-async [] "ok")
  (assert (= (also-not-async) "ok")))


(defn test-return []

  ; `return` in main line
  (defn f [x]
    (return (+ x "a"))
    (+ x "b"))
  (assert (= (f "q") "qa"))

  ; Nullary `return`
  (defn f [x]
    (return)
    5)
  (assert (is (f "q") None))

  ; `return` in `when`
  (defn f [x]
    (when (< x 3)
      (return [x 1]))
    [x 2])
  (assert (= (f 2) [2 1]))
  (assert (= (f 4) [4 2]))

  ; `return` in a loop
  (setv accum [])
  (defn f [x]
    (while True
      (when (= x 0)
        (return))
      (.append accum x)
      (-= x 1))
    (.append accum "this should never be appended")
    1)
  (assert (is (f 5) None))
  (assert (= accum [5 4 3 2 1]))

  ; `return` of a `do`
  (setv accum [])
  (defn f []
    (return (do
      (.append accum 1)
      3))
    4)
  (assert (= (f) 3))
  (assert (= accum [1]))

  ; `return` of an `if` that will need to be compiled to a statement
  (setv accum [])
  (defn f [x]
    (return (if (= x 1)
      (do
        (.append accum 1)
        "a")
      (do
        (.append accum 2)
        "b")))
    "c")
  (assert (= (f 2) "b"))
  (assert (= accum [2])))


(defn test-yield []
  (defn gen [] (for [x [1 2 3 4]] (yield x)))
  (setv ret 0)
  (for [y (gen)] (setv ret (+ ret y)))
  (assert (= ret 10)))


(defn test-yield-with-return []
  (defn gen [] (yield 3) "goodbye")
  (setv gg (gen))
  (assert (= 3 (next gg)))
  (with [e (pytest.raises StopIteration)]
    (next gg))
  (assert (= e.value.value "goodbye")))


(defn test-yield-in-try []
  (setv hit-finally False)
  (defn gen []
    (setv x 1)
    (try
      (yield x)
      (finally
        (nonlocal hit-finally)
        (setv hit-finally True))))
  (setv output (list (gen)))
  (assert (= [1] output))
  (assert hit-finally))


(defn test-midtree-yield []
  "Test yielding with a returnable."
  (defn kruft [] (yield) (+ 1 1)))


(defn test-midtree-yield-in-for []
  "Test yielding in a for with a return."
  (defn kruft-in-for []
    (for [i (range 5)]
      (yield i))
    (+ 1 2)))


(defn test-midtree-yield-in-while []
  "Test yielding in a while with a return."
  (defn kruft-in-while []
    (setv i 0)
    (while (< i 5)
      (yield i)
      (setv i (+ i 1)))
    (+ 2 3)))


(defn test-multi-yield []
  (defn multi-yield []
    (for [i (range 3)]
      (yield i))
    (yield "a")
    (yield "end"))
  (assert (= (list (multi-yield)) [0 1 2 "a" "end"])))


(defn test-yield-from []
  (defn yield-from-test []
    (for [i (range 3)]
      (yield i))
    (yield :from [1 2 3]))
  (assert (= (list (yield-from-test)) [0 1 2 1 2 3])))


(defn test-yield-from-exception-handling []
  (defn yield-from-subgenerator-test []
    (yield 1)
    (yield 2)
    (yield 3)
    (/ 1 0))
  (defn yield-from-test []
    (for [i (range 3)]
      (yield i))
    (try
      (yield :from (yield-from-subgenerator-test))
      (except [e ZeroDivisionError]
        (yield 4))))
  (assert (= (list (yield-from-test)) [0 1 2 1 2 3 4])))


(defn test-yield-from-notreally []
  (defn f []
    (yield :from)
    (yield :from))
  (assert (= (list (f)) [:from :from])))