forked from JuliaLang/julia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjulia-syntax.scm
4417 lines (4178 loc) · 200 KB
/
julia-syntax.scm
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;; ignored variable name. TODO replace with _?
(define UNUSED '|#unused#|)
;; pass 1: syntax desugaring
;; allow (:: T) => (:: #gensym T) in formal argument lists
(define (fill-missing-argname a unused)
(if (and (pair? a) (eq? (car a) '|::|) (null? (cddr a)))
`(|::| ,(if unused UNUSED (gensy)) ,(cadr a))
a))
(define (fix-arglist l (unused #t))
(if (any vararg? (butlast l))
(error "invalid \"...\" on non-final argument"))
(map (lambda (a)
(cond ((and (pair? a) (eq? (car a) 'kw))
`(kw ,(fill-missing-argname (cadr a) unused) ,(caddr a)))
((and (pair? a) (eq? (car a) '...))
`(... ,(fill-missing-argname (cadr a) unused)))
(else
(fill-missing-argname a unused))))
l))
;; expanding comparison chains: (comparison a op b op c ...)
;; accumulate a series of comparisons, with the given "and" constructor,
;; exit criteria, and "take" function that consumes part of a list,
;; returning (expression . rest)
(define (comp-accum e make-and done? take)
(let loop ((e e)
(expr '()))
(if (done? e) (cons expr e)
(let ((ex_rest (take e)))
(loop (cdr ex_rest)
(if (null? expr)
(car ex_rest)
(make-and expr (car ex_rest))))))))
(define (add-init arg arg2 expr)
(if (eq? arg arg2) expr
`(block (= ,arg2 ,arg) ,expr)))
;; generate first comparison call, converting e.g. (a < b < c)
;; to ((call < a b) b < c)
(define (compare-one e)
(let* ((arg (caddr e))
(arg2 (if (and (pair? arg)
(pair? (cdddr e)))
(make-ssavalue) arg)))
(if (and (not (dotop-named? (cadr e)))
(length> e 5)
(pair? (cadddr (cdr e)))
(dotop-named? (cadddr (cddr e))))
;; look ahead: if the 2nd argument of the next comparison is also
;; an argument to an eager (dot) op, make sure we don't skip the
;; initialization of its variable by short-circuiting
(let ((s (make-ssavalue)))
(cons `(block
,@(if (eq? arg arg2) '() `((= ,arg2 ,arg)))
(= ,s ,(cadddr (cdr e)))
(call ,(cadr e) ,(car e) ,arg2))
(list* arg2 (cadddr e) s (cddddr (cdr e)))))
(cons
(add-init arg arg2
`(call ,(cadr e) ,(car e) ,arg2))
(cons arg2 (cdddr e))))))
;; convert a series of scalar comparisons into && expressions
(define (expand-scalar-compare e)
(comp-accum e
(lambda (a b) `(&& ,a ,b))
(lambda (x) (or (not (length> x 2)) (dotop-named? (cadr x))))
compare-one))
;; convert a series of scalar and vector comparisons into & calls,
;; combining as many scalar comparisons as possible into short-circuit
;; && sequences.
(define (expand-vector-compare e)
(comp-accum e
(lambda (a b) `(call .& ,a ,b))
(lambda (x) (not (length> x 2)))
(lambda (e)
(if (dotop-named? (cadr e))
(compare-one e)
(expand-scalar-compare e)))))
(define (expand-compare-chain e)
(car (expand-vector-compare e)))
;; return the appropriate computation for a `begin` or `end` symbol for indexing
;; the array `a` in the `n`th index.
;; `tuples` are a list of the splatted arguments that precede index `n`
;; `last` = is this last index?
;; returns a call to lastindex(a) or lastindex(a,n)
(define (end-val a n tuples last)
(if (null? tuples)
(if (and last (= n 1))
`(call (top lastindex) ,a)
`(call (top lastindex) ,a ,n))
(let ((dimno `(call (top +) ,(- n (length tuples))
,.(map (lambda (t) `(call (top length) ,t))
tuples))))
`(call (top lastindex) ,a ,dimno))))
(define (begin-val a n tuples last)
(if (null? tuples)
(if (and last (= n 1))
`(call (top firstindex) ,a)
`(call (top first) (call (top axes) ,a ,n)))
(let ((dimno `(call (top +) ,(- n (length tuples))
,.(map (lambda (t) `(call (top length) ,t))
tuples))))
`(call (top first) (call (top axes) ,a ,dimno)))))
;; replace `begin` and `end` for the closest ref expression, so doesn't go inside nested refs
(define (replace-beginend ex a n tuples last)
(cond ((eq? ex 'end) (end-val a n tuples last))
((eq? ex 'begin) (begin-val a n tuples last))
((or (atom? ex) (quoted? ex)) ex)
((eq? (car ex) 'ref)
;; inside ref only replace within the first argument
(list* 'ref (replace-beginend (cadr ex) a n tuples last)
(cddr ex)))
(else
(cons (car ex)
(map (lambda (x) (replace-beginend x a n tuples last))
(cdr ex))))))
;; go through indices and replace the `begin` or `end` symbol
;; a = array being indexed, i = list of indices
;; returns (values index-list stmts) where stmts are statements that need
;; to execute first.
(define (process-indices a i)
(let loop ((lst i)
(n 1)
(stmts '())
(tuples '())
(ret '()))
(if (null? lst)
(values (reverse ret) (reverse stmts))
(let ((idx (car lst))
(last (null? (cdr lst))))
(if (and (pair? idx) (eq? (car idx) '...))
(if (symbol-like? (cadr idx))
(loop (cdr lst) (+ n 1)
stmts
(cons (cadr idx) tuples)
(cons `(... ,(replace-beginend (cadr idx) a n tuples last))
ret))
(let ((g (make-ssavalue)))
(loop (cdr lst) (+ n 1)
(cons `(= ,g ,(replace-beginend (cadr idx) a n tuples last))
stmts)
(cons g tuples)
(cons `(... ,g) ret))))
(loop (cdr lst) (+ n 1)
stmts tuples
(cons (replace-beginend idx a n tuples last) ret)))))))
;; GF method does not need to keep decl expressions on lambda args
;; except for rest arg
(define (method-lambda-expr argl body rett)
(let ((argl (map (lambda (x)
(let ((n (arg-name x)))
(if (underscore-symbol? n) UNUSED n)))
argl))
(body (blockify body)))
`(lambda ,argl ()
(scope-block
,(if (equal? rett '(core Any))
body
(let ((meta (take-while (lambda (x) (and (pair? x)
(memq (car x) '(line meta))))
(cdr body)))
(R (make-ssavalue)))
`(,(car body) ,@meta
(= ,R ,rett)
(meta ret-type ,R)
,@(list-tail body (+ 1 (length meta))))))))))
;; convert x<:T<:y etc. exprs into (name lower-bound upper-bound)
;; a bound is #f if not specified
(define (analyze-typevar e)
(define (check-sym s)
(if (symbol? s)
s
(error (string "invalid type parameter name \"" (deparse s) "\""))))
(cond ((atom? e) (list (check-sym e) #f #f))
((eq? (car e) 'var-bounds) (cdr e))
((and (eq? (car e) 'comparison) (length= e 6))
(cons (check-sym (cadddr e))
(cond ((and (eq? (caddr e) '|<:|) (eq? (caddr (cddr e)) '|<:|))
(list (cadr e) (last e)))
(else (error "invalid bounds in \"where\"")))))
((eq? (car e) '|<:|)
(list (check-sym (cadr e)) #f (caddr e)))
((eq? (car e) '|>:|)
(list (check-sym (cadr e)) (caddr e) #f))
(else (error "invalid variable expression in \"where\""))))
(define (sparam-name-bounds params)
(let ((bounds (map analyze-typevar params)))
(values (map car bounds) bounds)))
(define (unmangled-name v)
(if (eq? v '||)
v
(let ((s (string v)))
(if (eqv? (string.char s 0) #\#)
(symbol (last (string-split s "#")))
v))))
;; construct expression to allocate a TypeVar
(define (bounds-to-TypeVar v (unmangle #f))
(let ((v ((if unmangle unmangled-name identity) (car v)))
(lb (cadr v))
(ub (caddr v)))
`(call (core TypeVar) ',v
,@(if ub
(if lb (list lb ub) (list ub))
(if lb (list lb '(core Any)) '())))))
(define (method-expr-name m)
(let ((name (cadr m)))
(cond ((not (pair? name)) name)
((eq? (car name) 'outerref) (cadr name))
;((eq? (car name) 'globalref) (caddr name))
(else name))))
;; extract static parameter names from a (method ...) expression
(define (method-expr-static-parameters m)
(let ((type-ex (caddr m)))
(if (eq? (car type-ex) 'block)
;; extract ssavalue labels of sparams from the svec-of-sparams argument to `method`
(let ((sp-ssavals (cddr (cadddr (last type-ex)))))
(map (lambda (a) ;; extract T from (= v (call (core TypeVar) (quote T) ...))
(cadr (caddr (caddr a))))
(filter (lambda (e)
(and (pair? e) (eq? (car e) '=) (member (cadr e) sp-ssavals)))
(cdr type-ex))))
'())))
;; expressions of the form a.b.c... where everything is a symbol
(define (sym-ref? e)
(or (symbol? e)
(and (length= e 3) (eq? (car e) 'globalref))
(and (length= e 2) (eq? (car e) 'outerref))
(and (length= e 3) (eq? (car e) '|.|)
(or (atom? (cadr e)) (sym-ref? (cadr e)))
(pair? (caddr e)) (memq (car (caddr e)) '(quote inert))
(symbol? (cadr (caddr e))))))
;; convert final (... x) to (curly Vararg x)
(define (dots->vararg a)
(if (null? a) a
(let ((head (butlast a))
(las (last a)))
(if (vararg? las)
`(,@head (curly Vararg ,(cadr las)))
`(,@head ,las)))))
(define (replace-vars e renames)
(cond ((symbol? e) (lookup e renames e))
((or (not (pair? e)) (quoted? e)) e)
((memq (car e) '(-> function scope-block)) e)
(else
(cons (car e)
(map (lambda (x) (replace-vars x renames))
(cdr e))))))
(define (make-generator-function name sp-names arg-names body)
(let ((arg-names (append sp-names
(map (lambda (n)
(if (eq? n '|#self#|) (gensy) n))
arg-names))))
(let ((body (insert-after-meta body ;; don't specialize on generator arguments
`((meta nospecialize ,@arg-names)))))
`(block
(global ,name)
(function (call ,name ,@arg-names) ,body)))))
;; select the `then` or `else` part of `if @generated` based on flag `genpart`
(define (generated-part- x genpart)
(cond ((or (atom? x) (quoted? x) (function-def? x)) x)
((if-generated? x)
(if genpart `($ ,(caddr x)) (cadddr x)))
(else (cons (car x)
(map (lambda (e) (generated-part- e genpart)) (cdr x))))))
(define (generated-version body)
`(block
,(julia-bq-macro (generated-part- body #t))))
(define (non-generated-version body)
(generated-part- body #f))
;; Remove and return the line number for the start of the function definition
(define (maybe-remove-functionloc! body)
(let* ((prologue (extract-method-prologue body))
(prologue-lnos (filter linenum? prologue))
(functionloc (if (pair? prologue-lnos)
(car prologue-lnos)
; Fallback - take first line anywhere in body
(let ((lnos (filter linenum? body)))
(if (null? lnos) '(line 0 none) (car lnos))))))
(if (length> prologue-lnos 1)
; First of two line numbers in prologue is function definition location
; which should be removed from the body.
(let loop ((stmts body))
(if (eq? functionloc (cadr stmts))
(set-cdr! stmts (cddr stmts))
(loop (cdr body)))))
functionloc))
;; construct the (method ...) expression for one primitive method definition,
;; assuming optional and keyword args are already handled
(define (method-def-expr- name sparams argl body (rett '(core Any)))
(if
(any kwarg? argl)
;; has optional positional args
(begin
(let check ((l argl)
(seen? #f))
(if (pair? l)
(if (kwarg? (car l))
(check (cdr l) #t)
(if (and seen? (not (vararg? (car l))))
(error "optional positional arguments must occur at end")
(check (cdr l) #f)))))
(receive
(kws argl) (separate kwarg? argl)
(let ((opt (map cadr kws))
(dfl (map caddr kws)))
(receive
(vararg req) (separate vararg? argl)
(optional-positional-defs name sparams req opt dfl body
(append req opt vararg) rett)))))
;; no optional positional args
(let ((names (map car sparams))
(anames (map (lambda (x) (if (underscore-symbol? x) UNUSED x))
(llist-vars argl))))
(if (has-dups (filter (lambda (x) (not (eq? x UNUSED))) anames))
(error "function argument names not unique"))
(if (has-dups names)
(error "function static parameter names not unique"))
(if (any (lambda (x) (and (not (eq? x UNUSED)) (memq x names))) anames)
(error "function argument and static parameter names must be distinct"))
(if (or (and name (not (sym-ref? name))) (not (valid-name? name)))
(error (string "invalid function name \"" (deparse name) "\"")))
(let* ((loc (maybe-remove-functionloc! body))
(generator (if (expr-contains-p if-generated? body (lambda (x) (not (function-def? x))))
(let* ((gen (generated-version body))
(nongen (non-generated-version body))
(gname (symbol (string (gensy) "#" (current-julia-module-counter))))
(gf (make-generator-function gname names anames gen)))
(set! body (insert-after-meta
nongen
`((meta generated
(new (core GeneratedFunctionStub)
,gname
,(cons 'list anames)
,(if (null? sparams)
'nothing
(cons 'list (map car sparams)))
,(cadr loc)
(inert ,(caddr loc))
(false))))))
(list gf))
'()))
(types (llist-types argl))
(body (method-lambda-expr argl body rett))
;; HACK: the typevars need to be bound to ssavalues, since this code
;; might be moved to a different scope by closure-convert.
(temps (map (lambda (x) (make-ssavalue)) names))
(renames (map cons names temps))
(mdef
(if (null? sparams)
`(method ,name
(call (core svec)
(call (core svec) ,@(dots->vararg types))
(call (core svec))
(inert ,loc))
,body)
`(method ,name
(block
,@(let loop ((n names)
(t temps)
(sp (map bounds-to-TypeVar sparams))
(ren '())
(assigns '()))
(if (null? n)
(reverse! assigns)
(loop (cdr n) (cdr t) (cdr sp)
(cons (cons (car n) (car t)) ren)
;; each static param can see just the previous ones
(cons (make-assignment (car t) (replace-vars (car sp) ren))
assigns))))
(call (core svec) (call (core svec)
,@(dots->vararg
(map (lambda (ty)
(replace-vars ty renames))
types)))
(call (core svec) ,@temps)
(inert ,loc)))
,body))))
(if (or (symbol? name) (globalref? name))
`(block ,@generator (method ,name) ,mdef (unnecessary ,name)) ;; return the function
(if (not (null? generator))
`(block ,@generator ,mdef)
mdef))))))
;; wrap expr in nested scopes assigning names to vals
(define (scopenest names vals expr)
(if (null? names)
expr
`(let (= ,(car names) ,(car vals))
(block
,(scopenest (cdr names) (cdr vals) expr)))))
(define (keywords-method-def-expr name sparams argl body rett)
(let* ((kargl (cdar argl)) ;; keyword expressions (= k v)
(kargl (map (lambda (a)
(if (nospecialize-meta? a) (caddr a) a))
kargl))
(pargl (cdr argl)) ;; positional args
(body (blockify body))
(ftype (decl-type (car pargl)))
;; 1-element list of vararg argument, or empty if none
(vararg (let ((l (if (null? pargl) '() (last pargl))))
(if (or (vararg? l) (varargexpr? l))
(list l) '())))
;; positional args with vararg
(pargl-all pargl)
;; positional args without vararg
(pargl (if (null? vararg) pargl (butlast pargl)))
;; positional args with everything required; for use by the core function
(not-optional (map (lambda (a)
(if (kwarg? a) (cadr a) a))
pargl))
;; keywords glob
(restkw (let ((l (last kargl)))
(if (vararg? l)
(list (cadr l)) '())))
(kargl (let ((kws (if (null? restkw) kargl (butlast kargl))))
(if (any vararg? kws)
(error "invalid \"...\" on non-final keyword argument"))
kws))
;; the keyword::Type expressions
(vars (map cadr kargl))
;; keyword default values
(vals (map caddr kargl))
;; just the keyword names
(keynames (map decl-var vars))
;; do some default values depend on other keyword arguments?
(ordered-defaults (any (lambda (v) (contains
(lambda (x) (eq? x v))
vals))
keynames))
;; list of function's initial line number and meta nodes (empty if none)
(prologue (extract-method-prologue body))
(annotations (map (lambda (a) `(meta ,(cadr a) ,(arg-name (cadr (caddr a)))))
(filter nospecialize-meta? kargl)))
;; body statements
(stmts (cdr body))
(positional-sparams (filter-sparams (cons 'list pargl-all) sparams))
(keyword-sparams
(filter (lambda (s)
(not (any (lambda (p) (eq? (car p) (car s)))
positional-sparams)))
sparams)))
(let ((kw (gensy))
(rkw (if (null? restkw) (make-ssavalue) (symbol (string (car restkw) "..."))))
(mangled (let ((und (and name (undot-name name))))
(symbol (string (if (and name (= (string.char (string name) 0) #\#))
""
"#")
(or und '_) "#"
(string (current-julia-module-counter)))))))
;; this is a hack: nest these statements inside a call so they get closure
;; converted together, allowing all needed types to be defined before any methods.
`(call (core ifelse) (false) (false) (block
;; forward-declare function so its type can occur in the signature of the inner method below
,@(if (or (symbol? name) (globalref? name)) `((method ,name)) '())
;; call with keyword args pre-sorted - original method code goes here
,(method-def-expr-
mangled sparams
`((|::| ,mangled (call (core typeof) ,mangled)) ,@vars ,@restkw
;; strip type off function self argument if not needed for a static param.
;; then it is ok for cl-convert to move this definition above the original def.
,@not-optional ,@vararg)
(insert-after-meta `(block
,@stmts)
(cons `(meta nkw ,(+ (length vars) (length restkw)))
annotations))
rett)
;; call with no keyword args
,(method-def-expr-
name positional-sparams pargl-all
`(block
,@(without-generated prologue)
,(let (;; call mangled(vals..., [rest_kw,] pargs..., [vararg]...)
(ret `(return (call ,mangled
,@(if ordered-defaults keynames vals)
,@(if (null? restkw) '() `((call (top pairs) (call (core NamedTuple)))))
,@(map arg-name pargl)
,@(if (null? vararg) '()
(list `(... ,(arg-name (car vararg)))))))))
(if ordered-defaults
(scopenest keynames vals ret)
ret))))
;; call with unsorted keyword args. this sorts and re-dispatches.
,(method-def-expr-
name positional-sparams
`((|::|
;; if there are optional positional args, we need to be able to reference the function name
,(if (any kwarg? pargl) (gensy) UNUSED)
(call (core kwftype) ,ftype)) ,kw ,@pargl ,@vararg)
`(block
,@(filter linenum? prologue)
,(scopenest
keynames
(map (lambda (v dflt)
(let* ((k (decl-var v))
(rval0 `(call (top getindex) ,kw (inert ,k)))
;; note: if the "declared" type of a KW arg includes something
;; from keyword-sparams then don't assert it here, since those
;; static parameters don't have values yet. instead, the type
;; will be picked up when the underlying method is called.
(rval (if (and (decl? v)
(not (any (lambda (s)
(expr-contains-eq (car s) (caddr v)))
keyword-sparams)))
(let ((T (caddr v))
(temp (make-ssavalue)))
`(block (= ,temp ,rval0)
(if (call (core isa) ,temp ,T)
(null)
(call (core throw)
(new (core TypeError)
(inert |keyword argument|)
(inert ,k)
,T
,temp)))
,temp))
rval0)))
`(if (call (top haskey) ,kw (quote ,k))
,rval
,dflt)))
vars vals)
`(block
(= ,rkw (call (top pairs)
,(if (null? keynames)
kw
`(call (top structdiff) ,kw (curly (core NamedTuple)
(tuple ,@(map quotify keynames)))))))
,@(if (null? restkw)
`((if (call (top isempty) ,rkw)
(null)
(call (top kwerr) ,kw ,@(map arg-name pargl)
,@(if (null? vararg) '()
(list `(... ,(arg-name (car vararg))))))))
'())
(return (call ,mangled ;; finally, call the core function
,@keynames
,@(if (null? restkw) '() (list rkw))
,@(map arg-name pargl)
,@(if (null? vararg) '()
(list `(... ,(arg-name (car vararg)))))))))))
;; return primary function
,(if (not (symbol? name))
'(null) name))))))
;; prologue includes line number node and eventual meta nodes
(define (extract-method-prologue body)
(if (pair? body)
(take-while (lambda (e)
(and (pair? e) (or (eq? (car e) 'line) (eq? (car e) 'meta))))
(cdr body))
'()))
(define (without-generated stmts)
(filter (lambda (x) (not (or (generated-meta? x)
(generated_only-meta? x))))
stmts))
;; keep only sparams used by `expr` or other sparams
(define (filter-sparams expr sparams)
(let loop ((filtered '())
(params sparams))
(cond ((null? params)
(reverse! filtered))
((or (expr-contains-eq (caar params) expr)
(any (lambda (v) (expr-contains-eq (caar params) v))
(cdr params)))
(loop (cons (car params) filtered) (cdr params)))
(else
(loop filtered (cdr params))))))
(define (optional-positional-defs name sparams req opt dfl body overall-argl rett)
(let ((prologue (without-generated (extract-method-prologue body))))
`(block
,@(map (lambda (n)
(let* ((passed (append req (list-head opt n)))
;; only keep static parameters used by these arguments
(sp (filter-sparams (cons 'list passed) sparams))
(vals (list-tail dfl n))
(absent (list-tail opt n)) ;; absent arguments
(body
(if (any (lambda (defaultv)
;; does any default val expression...
(contains (lambda (e)
;; contain "e" such that...
(any (lambda (a)
;; "e" is in an absent arg
(contains (lambda (u)
(eq? u e))
a))
absent))
defaultv))
vals)
;; then add only one next argument
`(block
,@prologue
(call ,(arg-name (car req)) ,@(map arg-name (cdr passed)) ,(car vals)))
;; otherwise add all
`(block
,@prologue
(call ,(arg-name (car req)) ,@(map arg-name (cdr passed)) ,@vals)))))
(method-def-expr- name sp passed body)))
(iota (length opt)))
,(method-def-expr- name sparams overall-argl body rett))))
;; strip empty (parameters ...), normalizing `f(x;)` to `f(x)`.
(define (remove-empty-parameters argl)
(if (and (has-parameters? argl) (null? (cdar argl)))
(cdr argl)
argl))
(define (check-kw-args kw)
(let ((invalid (filter (lambda (x) (not (or (kwarg? x) (vararg? x)
(and (nospecialize-meta? x)
(or (kwarg? (caddr x)) (vararg? (caddr x)))))))
kw)))
(if (pair? invalid)
(if (and (pair? (car invalid)) (eq? 'parameters (caar invalid)))
(error "more than one semicolon in argument list")
(error (string "invalid keyword argument syntax \""
(deparse (car invalid)) "\""))))))
; replace unassigned kw args with assignment to throw() call (forcing the caller to assign the keyword)
(define (throw-unassigned-kw-args argl)
(define (throw-unassigned argname)
`(call (core throw) (call (core UndefKeywordError) (inert ,argname))))
(if (has-parameters? argl)
(cons (cons 'parameters
(map (lambda (x)
(cond ((symbol? x) `(kw ,x ,(throw-unassigned x)))
((decl? x) `(kw ,x ,(throw-unassigned (cadr x))))
(else x)))
(cdar argl)))
(cdr argl))
argl))
;; method-def-expr checks for keyword arguments, and if there are any, calls
;; keywords-method-def-expr to expand the definition into several method
;; definitions that do not use keyword arguments.
;; definitions without keyword arguments are passed to method-def-expr-,
;; which handles optional positional arguments by adding the needed small
;; boilerplate definitions.
(define (method-def-expr name sparams argl body rett)
(let ((argl (throw-unassigned-kw-args (remove-empty-parameters argl))))
(if (has-parameters? argl)
;; has keywords
(begin (check-kw-args (cdar argl))
(keywords-method-def-expr name sparams argl body rett))
;; no keywords
(method-def-expr- name sparams argl body rett))))
(define (struct-def-expr name params super fields mut)
(receive
(params bounds) (sparam-name-bounds params)
(struct-def-expr- name params bounds super (flatten-blocks fields) mut)))
;; replace field names with gensyms if they conflict with field-types
(define (safe-field-names field-names field-types)
(if (any (lambda (v) (contains (lambda (e) (eq? e v)) field-types))
field-names)
(map (lambda (x) (gensy)) field-names)
;; use a different name for a field called `_`
(map (lambda (x) (if (eq? x '_) (gensy) x)) field-names)))
(define (with-wheres call wheres)
(if (pair? wheres)
`(where ,call ,@wheres)
call))
(define (default-inner-ctors name field-names field-types params bounds locs)
(let* ((field-names (safe-field-names field-names field-types))
(any-ctor
;; definition with Any for all arguments
`(function ,(with-wheres
`(call ,(if (pair? params)
`(curly ,name ,@params)
name)
,@field-names)
(map (lambda (b) (cons 'var-bounds b)) bounds))
(block
,@locs
(call new ,@field-names)))))
(if (and (null? params) (any (lambda (t) (not (equal? t '(core Any))))
field-types))
(list
;; definition with field types for all arguments
;; only if any field type is not Any, checked at runtime
`(if ,(foldl (lambda (t u)
`(&& ,u (call (core ===) (core Any) ,t)))
`(call (core ===) (core Any) ,(car field-types))
(cdr field-types))
(block)
(function (call ,name
,@(map make-decl field-names field-types))
(block
,@locs
(new (outerref ,name) ,@field-names))))
any-ctor)
(list any-ctor))))
(define (default-outer-ctor name field-names field-types params bounds locs)
(let ((field-names (safe-field-names field-names field-types)))
`(function ,(with-wheres
`(call ,name ,@(map make-decl field-names field-types))
(map (lambda (b) (cons 'var-bounds b)) bounds))
(block
,@locs
(call (curly ,name ,@params) ,@field-names)))))
(define (new-call Tname type-params sparams params args field-names field-types)
(if (any kwarg? args)
(error "\"new\" does not accept keyword arguments"))
(if (length> params (length type-params))
(error "too few type parameters specified in \"new{...}\""))
(if (length> type-params (length params))
(error "too many type parameters specified in \"new{...}\""))
(let* ((Texpr (if (null? type-params)
`(outerref ,Tname)
`(curly (outerref ,Tname)
,@type-params)))
(tn (make-ssavalue))
(field-convert (lambda (fld fty val)
(if (equal? fty '(core Any))
val
`(call (top convert)
,(if (and (equal? type-params params) (memq fty params) (memq fty sparams))
fty ; the field type is a simple parameter, the usage here is of a
; local variable (currently just handles sparam) for the bijection of params to type-params
`(call (core fieldtype) ,tn ,(+ fld 1)))
,val)))))
(cond ((length> (filter (lambda (a) (not (vararg? a))) args) (length field-names))
`(call (core throw) (call (top ArgumentError)
,(string "new: too many arguments (expected " (length field-names) ")"))))
((any vararg? args)
(if (every (lambda (ty) (equal? ty '(core Any)))
field-types)
`(splatnew ,Texpr (call (core tuple) ,@args))
(let ((argt (make-ssavalue))
(nf (make-ssavalue)))
`(block
(= ,tn ,Texpr)
(= ,argt (call (core tuple) ,@args))
(= ,nf (call (core nfields) ,argt))
(if (call (top ult_int) ,nf ,(length field-names))
(call (core throw) (call (top ArgumentError)
,(string "new: too few arguments (expected " (length field-names) ")"))))
(if (call (top ult_int) ,(length field-names) ,nf)
(call (core throw) (call (top ArgumentError)
,(string "new: too many arguments (expected " (length field-names) ")"))))
(new ,tn ,@(map (lambda (fld fty) (field-convert fld fty `(call (core getfield) ,argt ,(+ fld 1) (false))))
(iota (length field-names)) (list-head field-types (length field-names))))))))
(else
`(block
(= ,tn ,Texpr)
(new ,tn ,@(map field-convert (iota (length args)) (list-head field-types (length args)) args)))))))
;; insert item at start of arglist
(define (arglist-unshift sig item)
(if (and (pair? sig) (pair? (car sig)) (eq? (caar sig) 'parameters))
`(,(car sig) ,item ,@(cdr sig))
`(,item ,@sig)))
(define (linenode-string lno)
(cond ((length= lno 2) (string " around line " (cadr lno)))
((length= lno 3) (string " around " (caddr lno) ":" (cadr lno)))
(else "")))
(define (ctor-def name Tname ctor-body sig body wheres)
(let* ((curly? (and (pair? name) (eq? (car name) 'curly)))
(curlyargs (if curly? (cddr name) '()))
(name (if curly? (cadr name) name))
(sparams (map car (map analyze-typevar wheres))))
(cond ((not (eq? name Tname))
`(function ,(with-wheres `(call ,(if curly?
`(curly ,name ,@curlyargs)
name)
,@sig)
wheres)
;; pass '() in order to require user-specified parameters with
;; new{...} inside a non-ctor inner definition.
,(ctor-body body '() sparams)))
(else
`(function ,(with-wheres `(call ,(if curly?
`(curly ,name ,@curlyargs)
name)
,@sig)
wheres)
,(ctor-body body curlyargs sparams))))))
;; rewrite calls to `new( ... )` to `new` expressions on the appropriate
;; type, determined by the containing constructor definition.
(define (rewrite-ctor ctor Tname params field-names field-types)
(define (ctor-body body type-params sparams)
(pattern-replace (pattern-set
(pattern-lambda
(call (-/ new) . args)
(new-call Tname type-params sparams params
(map (lambda (a) (ctor-body a type-params sparams)) args)
field-names field-types))
(pattern-lambda
(call (curly (-/ new) . p) . args)
(new-call Tname p sparams params
(map (lambda (a) (ctor-body a type-params sparams)) args)
field-names field-types)))
body))
(pattern-replace
(pattern-set
;; definitions without `where`
(pattern-lambda (function (-$ (call name . sig) (|::| (call name . sig) _t)) body)
(ctor-def name Tname ctor-body sig body #f))
(pattern-lambda (= (-$ (call name . sig) (|::| (call name . sig) _t)) body)
(ctor-def name Tname ctor-body sig body #f))
;; definitions with `where`
(pattern-lambda (function (where (-$ (call name . sig) (|::| (call name . sig) _t)) . wheres) body)
(ctor-def name Tname ctor-body sig body wheres))
(pattern-lambda (= (where (-$ (call name . sig) (|::| (call name . sig) _t)) . wheres) body)
(ctor-def name Tname ctor-body sig body wheres)))
;; flatten `where`s first
(pattern-replace
(pattern-set
(pattern-lambda (where (where . rest1) . rest2)
(flatten-where-expr __)))
ctor)))
;; check if there are any calls to new with fewer than n arguments
(define (ctors-min-initialized expr)
(and (pair? expr)
(min
((pattern-lambda (call (-/ new) . args)
(length args))
(car expr))
((pattern-lambda (call (curly (-/ new) . p) . args)
(length args))
(car expr))
(ctors-min-initialized (car expr))
(ctors-min-initialized (cdr expr)))))
(define (struct-def-expr- name params bounds super fields0 mut)
(receive
(fields defs) (separate (lambda (x) (or (symbol? x) (decl? x)))
fields0)
(let* ((defs (filter (lambda (x) (not (effect-free? x))) defs))
(locs (if (and (pair? fields0) (linenum? (car fields0)))
(list (car fields0))
'()))
(field-names (map decl-var fields))
(field-types (map decl-type fields))
(defs2 (if (null? defs)
(default-inner-ctors name field-names field-types params bounds locs)
defs))
(min-initialized (min (ctors-min-initialized defs) (length fields))))
(let ((dups (has-dups field-names)))
(if dups (error (string "duplicate field name: \"" (car dups) "\" is not unique"))))
(for-each (lambda (v)
(if (not (symbol? v))
(error (string "field name \"" (deparse v) "\" is not a symbol"))))
field-names)
`(block
(global ,name) (const ,name)
(scope-block
(block
,@(map (lambda (v) `(local ,v)) params)
,@(map (lambda (n v) (make-assignment n (bounds-to-TypeVar v #t))) params bounds)
(struct_type ,name (call (core svec) ,@params)
(call (core svec) ,@(map quotify field-names))
,super (call (core svec) ,@field-types) ,mut ,min-initialized)))
;; "inner" constructors
(scope-block
(block
(global ,name)
,@(map (lambda (c)
(rewrite-ctor c name params field-names field-types))
defs2)))
;; "outer" constructors
,@(if (and (null? defs)
(not (null? params))
;; To generate an outer constructor, each parameter must occur in a field
;; type, or in the bounds of a subsequent parameter.
;; Otherwise the constructor would not work, since the parameter values
;; would never be specified.
(let loop ((root-types field-types)
(sp (reverse bounds)))
(or (null? sp)
(let ((p (car sp)))
(and (expr-contains-eq (car p) (cons 'list root-types))
(loop (append (cdr p) root-types)
(cdr sp)))))))
`((scope-block
(block
(global ,name)
,(default-outer-ctor name field-names field-types
params bounds locs))))
'())
(null)))))
(define (abstract-type-def-expr name params super)
(receive
(params bounds) (sparam-name-bounds params)
`(block
(global ,name) (const ,name)
(scope-block
(block
,@(map (lambda (v) `(local ,v)) params)
,@(map (lambda (n v) (make-assignment n (bounds-to-TypeVar v #t))) params bounds)
(abstract_type ,name (call (core svec) ,@params) ,super))))))
(define (primitive-type-def-expr n name params super)
(receive
(params bounds) (sparam-name-bounds params)
`(block
(global ,name) (const ,name)
(scope-block
(block
,@(map (lambda (v) `(local ,v)) params)
,@(map (lambda (n v) (make-assignment n (bounds-to-TypeVar v #t))) params bounds)
(primitive_type ,name (call (core svec) ,@params) ,n ,super))))))
;; take apart a type signature, e.g. T{X} <: S{Y}
(define (analyze-type-sig ex)
(or ((pattern-lambda (-- name (-s))
(values name '() '(core Any))) ex)
((pattern-lambda (curly (-- name (-s)) . params)
(values name params '(core Any))) ex)
((pattern-lambda (|<:| (-- name (-s)) super)
(values name '() super)) ex)
((pattern-lambda (|<:| (curly (-- name (-s)) . params) super)
(values name params super)) ex)
(error "invalid type signature")))
;; insert calls to convert() in ccall, and pull out expressions that might
;; need to be rooted before conversion.
(define (lower-ccall name RT atypes args cconv)
(let loop ((F atypes) ;; formals
(A args) ;; actuals
(stmts '()) ;; initializers
(T '()) ;; argument types (F converted)
(C '()) ;; argument values (A converted)
(GC '())) ;; GC roots
(if (and (null? F) (not (null? A)))
(error "more arguments than types for ccall"))
(if (and (null? A) (not (or (null? F) (and (pair? F) (vararg? (car F)) (null? (cdr F))))))
(error "more types than arguments for ccall"))
(let ((isseq (and (not (null? F)) (vararg? (car F)))))
(if (and isseq (null? T))
(error "C ABI prohibits vararg without one required argument"))
(if (null? A)
`(block
,.(reverse! stmts)
(foreigncall ,name ,RT (call (core svec) ,@(reverse! T))
,(if isseq (- (length atypes) 1) 0) ; 0 or number of arguments before ... in definition
',cconv
,.(reverse! C)
,@GC)) ; GC root ordering is arbitrary
(let* ((a (car A))
(ty (if isseq (cadar F) (car F))))
(if (and isseq (not (null? (cdr F)))) (error "only the trailing ccall argument type should have \"...\""))
(if (eq? ty 'Any)
(loop (if isseq F (cdr F)) (cdr A) stmts (list* '(core Any) T) (list* a C) GC)
(let* ((g (make-ssavalue))
(stmts (cons `(= ,g (call (top cconvert) ,ty ,a)) stmts))
(ca `(call (top unsafe_convert) ,ty ,g)))
(loop (if isseq F (cdr F)) (cdr A) stmts
(list* ty T) (list* ca C) (list* g GC)))))))))
(define (expand-function-def e) ;; handle function definitions
(define (just-arglist? ex)
(and (pair? ex)
(or (memq (car ex) '(tuple block ...))
(and (eq? (car ex) 'where)
(just-arglist? (cadr ex))))))