-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
julia-syntax.scm
3732 lines (3526 loc) · 167 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))
;; identify some expressions that are safe to repeat
(define (effect-free? e)
(or (not (pair? e)) (ssavalue? e) (sym-dot? e) (quoted? e) (equal? e '(null))))
;; 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? (cadr e)))
(length> e 5)
(pair? (cadddr (cdr e)))
(dotop? (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? (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? (cadr e))
(compare-one e)
(expand-scalar-compare e)))))
(define (expand-compare-chain e)
(car (expand-vector-compare e)))
;; return the appropriate computation for an `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 endof(a), trailingsize(a,n), or size(a,n)
(define (end-val a n tuples last)
(if (null? tuples)
(if last
(if (= n 1)
`(call (top endof) ,a)
`(call (top trailingsize) ,a ,n))
`(call (top size) ,a ,n))
(let ((dimno `(call (top +) ,(- n (length tuples))
,.(map (lambda (t) `(call (top length) ,t))
tuples))))
(if last
`(call (top trailingsize) ,a ,dimno)
`(call (top size) ,a ,dimno)))))
;; replace `end` for the closest ref expression, so doesn't go inside nested refs
(define (replace-end ex a n tuples last)
(cond ((eq? ex 'end) (end-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-end (cadr ex) a n tuples last)
(cddr ex)))
(else
(cons (car ex)
(map (lambda (x) (replace-end x a n tuples last))
(cdr ex))))))
;; go through indices and replace the `end` symbol
;; a = array being indexed, i = list of indexes
;; returns (values index-list stmts) where stmts are statements that need
;; to execute first.
(define (process-indexes 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-end (cadr idx) a n tuples last))
ret))
(let ((g (make-ssavalue)))
(loop (cdr lst) (+ n 1)
(cons `(= ,g ,(replace-end (cadr idx) a n tuples last))
stmts)
(cons g tuples)
(cons `(... ,g) ret))))
(loop (cdr lst) (+ n 1)
stmts tuples
(cons (replace-end 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 arg-name argl))
(body (if (and (pair? body) (eq? (car body) 'block))
(if (null? (cdr body))
`(block (null))
body)
`(block ,body))))
`(lambda ,argl ()
(scope-block
,(if (eq? rett 'Any)
body
(let ((meta (take-while (lambda (x) (and (pair? x)
(memq (car x) '(line meta))))
(cdr body)))
(val (last body)))
;; wrap one-liners in `convert` instead of adding an ssavalue
(if (and (length= (cdr body) (+ 1 (length meta)))
(not (expr-contains-p return? (if (return? val)
(cadr val)
val))))
`(,(car body) ,@meta
,(if (return? val)
`(return ,(convert-for-type-decl (cadr val) rett))
(convert-for-type-decl val rett)))
(let ((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)))
;; construct expression to allocate a TypeVar
(define (bounds-to-TypeVar v)
(let ((v (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)
(if (eq? (car (caddr m)) 'block)
(let ((lst '()))
(pattern-replace
(pattern-set
(pattern-lambda (= v (call (core (-/ TypeVar)) (quote T) ...))
(begin (set! lst (cons T lst)) __)))
(butlast (cdr (caddr m))))
(reverse! lst))
'()))
;; 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))))))
;; e.g. Base.(:+) is deprecated in favor of Base.:+
(define (deprecate-dotparen e)
(if (and (length= e 3) (eq? (car e) '|.|)
(or (atom? (cadr e)) (sym-ref? (cadr e)))
(length= (caddr e) 2) (eq? (caaddr e) 'tuple)
(pair? (cadr (caddr e))) (memq (caadr (caddr e)) '(quote inert)))
(let* ((s_ (cdadr (caddr e)))
(s (if (symbol? s_) s_
(if (and (length= s_ 1) (symbol? (car s_))) (car s_) #f))))
(if s
(let ((newe (list (car e) (cadr e) (cadr (caddr e))))
(S (deparse `(quote ,s)))) ; #16295
(syntax-deprecation #f (string (deparse (cadr e)) ".(" S ")")
(string (deparse (cadr e)) "." S))
newe)
e))
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 (hidden-name? s)
(and (symbol? s)
(eqv? (string.char (string s) 0) #\#)))
(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 (replace-outer-vars e renames)
(cond ((and (pair? e) (eq? (car e) 'outerref)) (lookup (cadr 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-outer-vars x renames))
(cdr e))))))
;; 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 isstaged (rett '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 isstaged
(append req opt vararg) rett)))))
;; no optional positional args
(let ((names (map car sparams)))
(let ((anames (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))) (eq? name 'true) (eq? name 'false))
(error (string "invalid function name \"" (deparse name) "\"")))
(let* ((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)))
,body ,isstaged)
`(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)))
,body ,isstaged))))
(if (symbol? name)
`(block (method ,name) ,mdef (unnecessary ,name)) ;; return the function
mdef)))))
;; keyword default values that can be assigned right away. however, this creates
;; a quasi-bug (part of issue #9535) where it can be hard to predict when a
;; keyword argument will throw an UndefVarError.
(define (const-default? x)
(or (number? x) (string? x) (char? x) (and (pair? x) (memq (car x) '(quote inert)))
(eq? x 'true) (eq? x 'false)))
(define empty-vector-any '(call (core AnyVector) 0))
(define (keywords-method-def-expr name sparams argl body isstaged rett)
(let* ((kargl (cdar argl)) ;; keyword expressions (= k v)
(pargl (cdr argl)) ;; positional args
(body (if (and (pair? body) (eq? (car body) 'block))
body
`(block ,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 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 (if (null? restkw) kargl (butlast kargl)))
;; 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))
;; body statements
(stmts (cdr body))
(positional-sparams
(filter (lambda (s)
(let ((name (car s)))
(or (expr-contains-eq name (cons 'list pargl))
(and (pair? vararg) (expr-contains-eq name (car vararg)))
(not (expr-contains-eq name (cons 'list kargl))))))
sparams))
(keyword-sparams
(filter (lambda (s)
(not (any (lambda (p) (eq? (car p) (car s)))
positional-sparams)))
sparams)))
(let ((kw (gensy)) (i (gensy)) (ii (gensy)) (elt (gensy))
(rkw (if (null? restkw) '() (symbol (string (car restkw) "..."))))
(mangled (symbol (string "#" (if name (undot-name name) 'call) "#"
(string (current-julia-module-counter)))))
(flags (map (lambda (x) (gensy)) vals)))
`(block
;; call with no keyword args
,(method-def-expr-
name positional-sparams (append pargl vararg)
`(block
,@prologue
,@(if (not ordered-defaults)
'()
(append! (map (lambda (kwname) `(local ,kwname)) keynames)
(map make-assignment keynames vals)))
;; call mangled(vals..., [rest_kw,] pargs..., [vararg]...)
(return (call ,mangled
,@(if ordered-defaults keynames vals)
,@(if (null? restkw) '() (list empty-vector-any))
,@(map arg-name pargl)
,@(if (null? vararg) '()
(list `(... ,(arg-name (car vararg))))))))
#f)
;; 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.
,(if (decl? (car not-optional))
(if (any (lambda (sp)
(expr-contains-eq (car sp) (caddr (car not-optional))))
positional-sparams)
(car not-optional)
(decl-var (car not-optional)))
(car not-optional))
,@(cdr not-optional) ,@vararg)
`(block
,@stmts) isstaged rett)
;; call with unsorted keyword args. this sorts and re-dispatches.
,(method-def-expr-
name
(filter ;; remove sparams that don't occur, to avoid printing the warning twice
(lambda (s) (expr-contains-eq (car s) (cons 'list argl)))
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 (core AnyVector)) ,@pargl ,@vararg)
`(block
;; initialize keyword args to their defaults, or set a flag telling
;; whether this keyword needs to be set.
,@(map (lambda (kwname) `(local ,kwname)) keynames)
,@(map (lambda (name dflt flag)
(if (const-default? dflt)
`(= ,name ,dflt)
`(= ,flag true)))
keynames vals flags)
,@(if (null? restkw) '()
`((= ,rkw ,empty-vector-any)))
;; for i = 1:(length(kw)>>1)
(for (= ,i (: 1 (call (top >>) (call (top length) ,kw) 1)))
(block
;; ii = i*2 - 1
(= ,ii (call (top -) (call (top *) ,i 2) 1))
(= ,elt (call (core arrayref) ,kw ,ii))
,(foldl (lambda (kvf else)
(let* ((k (car kvf))
(rval0 `(call (core arrayref) ,kw
(call (top +) ,ii 1)))
;; 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? k)
(not (any (lambda (s)
(expr-contains-eq (car s) (caddr k)))
keyword-sparams)))
`(call (core typeassert)
,rval0
,(caddr k))
rval0)))
;; if kw[ii] == 'k; k = kw[ii+1]::Type; end
`(if (comparison ,elt === (quote ,(decl-var k)))
(block
(= ,(decl-var k) ,rval)
,@(if (not (const-default? (cadr kvf)))
`((= ,(caddr kvf) false))
'()))
,else)))
(if (null? restkw)
;; if no rest kw, give error for unrecognized
`(call (top kwerr) ,kw ,@(map arg-name pargl)
,@(if (null? vararg) '()
(list `(... ,(arg-name (car vararg))))))
;; otherwise add to rest keywords
`(foreigncall 'jl_array_ptr_1d_push (core Void) (call (core svec) Any Any)
,rkw 0 (tuple ,elt
(call (core arrayref) ,kw
(call (top +) ,ii 1))) 0))
(map list vars vals flags))))
;; set keywords that weren't present to their default values
,@(apply append
(map (lambda (name dflt flag)
(if (const-default? dflt)
'()
`((if ,flag (= ,name ,dflt)))))
keynames vals flags))
;; finally, call the core function
(return (call ,mangled
,@keynames
,@(if (null? restkw) '() (list rkw))
,@(map arg-name pargl)
,@(if (null? vararg) '()
(list `(... ,(arg-name (car vararg))))))))
#f)
;; 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 (optional-positional-defs name sparams req opt dfl body isstaged overall-argl rett)
(let ((prologue (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 (lambda (sp)
(contains (lambda (e) (eq? e (car sp)))
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 #f)))
(iota (length opt)))
,(method-def-expr- name sparams overall-argl body isstaged 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))))
kw)))
(if (pair? invalid)
(if (and (pair? (car invalid)) (eq? 'parameters (caar invalid)))
(error "more than one semicolon in argument list")
(cond ((symbol? (car invalid))
(error (string "keyword argument \"" (car invalid) "\" needs a default value")))
(else
(error (string "invalid keyword argument syntax \""
(deparse (car invalid))
"\" (expected assignment)"))))))))
;; 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 isstaged rett)
(let ((argl (remove-empty-parameters argl)))
(if (has-parameters? argl)
;; has keywords
(begin (check-kw-args (cdar argl))
(keywords-method-def-expr name sparams argl body isstaged rett))
;; no keywords
(method-def-expr- name sparams argl body isstaged 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 (curly ,name ,@params) ,@field-names)
(map (lambda (b) (cons 'var-bounds b)) bounds))
(block
,@locs
(call new ,@field-names)))))
(if (and (null? params) (any (lambda (t) (not (eq? t 'Any))) field-types))
(list
;; definition with field types for all arguments
`(function (call ,name
,@(map make-decl field-names field-types))
(block
,@locs
(call new ,@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 params args field-names field-types)
(if (any vararg? args)
(error "... is not supported inside \"new\""))
(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{...}\""))
(let ((Texpr (if (null? type-params)
`(outerref ,Tname)
`(curly (outerref ,Tname)
,@type-params))))
(cond ((length> args (length field-names))
`(call (top error) "new: too many arguments"))
(else
(if (equal? type-params params)
`(new ,Texpr ,@(map (lambda (fty val)
`(call (top convert) ,fty ,val))
(list-head field-types (length args)) args))
(let ((tn (make-ssavalue)))
`(block
(= ,tn ,Texpr)
(new ,tn ,@(map (lambda (fld val)
`(call (top convert)
(call (core fieldtype) ,tn (quote ,fld))
,val))
(list-head field-names (length args)) args)))))))))
;; insert a statement after line number node
(define (prepend-stmt stmt body)
(if (and (pair? body) (eq? (car body) 'block))
(cond ((atom? (cdr body))
`(block ,stmt (null)))
((and (pair? (cadr body)) (eq? (caadr body) 'line))
`(block ,(cadr body) ,stmt ,@(cddr body)))
(else
`(block ,stmt ,@(cdr body))))
body))
;; 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 (ctor-signature name params bounds method-params sig)
(if (null? params)
(if (null? method-params)
(cons `(call (|::| (curly (core Type) ,name)) ,@sig)
params)
(cons `(call (curly (|::| (curly (core Type) ,name)) ,@method-params) ,@sig)
params))
(if (null? method-params)
(cons `(call (curly (|::| (curly (core Type) (curly ,name ,@params)))
,@(map (lambda (b) (cons 'var-bounds b)) bounds))
,@sig)
params)
;; rename parameters that conflict with user-written method parameters
(let ((new-params (map (lambda (p) (if (memq p method-params)
(gensy)
p))
params)))
(cons `(call (curly (|::| (curly (core Type) (curly ,name ,@new-params)))
,@(map (lambda (n b) (list* 'var-bounds n (cdr b))) new-params bounds)
,@method-params)
,@sig)
new-params)))))
(define (ctor-def keyword name Tname params bounds sig ctor-body body wheres)
(let* ((curly? (and (pair? name) (eq? (car name) 'curly)))
(curlyargs (if curly? (cddr name) '()))
(name (if curly? (cadr name) name)))
(cond ((not (eq? name Tname))
`(,keyword ,(with-wheres `(call (curly ,name ,@curlyargs) ,@sig) wheres)
;; pass '() in order to require user-specified parameters with
;; new{...} inside a non-ctor inner definition.
,(ctor-body body '())))
(wheres
`(,keyword (where (call (curly ,name ,@curlyargs) ,@sig) ,@wheres)
,(ctor-body body curlyargs)))
(else
(let* ((temp (ctor-signature name params bounds curlyargs sig))
(sig (car temp))
(params (cdr temp)))
(if (pair? params)
(let* ((lnos (filter (lambda (e) (and (pair? e) (eq? (car e) 'line)))
body))
(lno (if (null? lnos) '() (car lnos))))
(syntax-deprecation #f
(string "inner constructor " name "(...)"
(cond ((length= lno 2) (string " around line " (cadr lno)))
((length= lno 3) (string " around " (caddr lno) ":" (cadr lno)))
(else "")))
(deparse `(where (call (curly ,name ,@params) ...) ,@params)))))
`(,keyword ,sig ,(ctor-body body params)))))))
;; rewrite calls to `new( ... )` to `new` expressions on the appropriate
;; type, determined by the containing constructor definition.
(define (rewrite-ctor ctor Tname params bounds field-names field-types)
(define (ctor-body body type-params)
(pattern-replace (pattern-set
(pattern-lambda
(call (-/ new) . args)
(new-call Tname type-params params
(map (lambda (a) (ctor-body a type-params)) args)
field-names field-types))
(pattern-lambda
(call (curly (-/ new) . p) . args)
(new-call Tname p params
(map (lambda (a) (ctor-body a type-params)) args)
field-names field-types)))
body))
(pattern-replace
(pattern-set
;; definitions without `where`
(pattern-lambda (function (call name . sig) body)
(ctor-def (car __) name Tname params bounds sig ctor-body body #f))
(pattern-lambda (stagedfunction (call name . sig) body)
(ctor-def (car __) name Tname params bounds sig ctor-body body #f))
(pattern-lambda (= (call name . sig) body)
(ctor-def 'function name Tname params bounds sig ctor-body body #f))
;; definitions with `where`
(pattern-lambda (function (where (call name . sig) . wheres) body)
(ctor-def (car __) name Tname params bounds sig ctor-body body wheres))
(pattern-lambda (stagedfunction (where (call name . sig) . wheres) body)
(ctor-def (car __) name Tname params bounds sig ctor-body body wheres))
(pattern-lambda (= (where (call name . sig) . wheres) body)
(ctor-def 'function name Tname params bounds sig ctor-body 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) (pair? (car fields0)) (eq? (caar fields0) 'line))
(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
(scope-block
(block
(global ,name) (const ,name)
,@(map (lambda (v) `(local ,v)) params)
,@(map (lambda (n v) (make-assignment n (bounds-to-TypeVar v))) params bounds)
(composite_type ,name (call (core svec) ,@params)
(call (core svec) ,@(map (lambda (x) `',x) 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 bounds field-names field-types))
defs2)))
;; "outer" constructors
,@(if (and (null? defs)
(not (null? params))
;; don't generate an outer constructor if the type has
;; parameters not mentioned in the field types. such a
;; constructor would not be callable anyway.
(every (lambda (sp)
(expr-contains-eq sp (cons 'list field-types)))
params))
`((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))) params bounds)
(abstract_type ,name (call (core svec) ,@params) ,super))))))
(define (bits-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))) params bounds)
(bits_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 '() 'Any)) ex)
((pattern-lambda (curly (-- name (-s)) . params)
(values name params '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)
(let loop ((F atypes) ;; formals
(A args) ;; actuals
(stmts '()) ;; initializers
(C '())) ;; converted
(if (or (null? F) (null? A))
`(block
,.(reverse! stmts)
(foreigncall ,name ,RT (call (core svec) ,@(dots->vararg atypes))
,.(reverse! C)
,@A))
(let* ((a (car A))
(isseq (and (pair? (car F)) (eq? (caar F) '...)))
(ty (if isseq (cadar F) (car F))))
(if (eq? ty 'Any)
(loop (if isseq F (cdr F)) (cdr A) stmts (list* 0 a C))
(let* ((g (make-ssavalue))
(isamp (and (pair? a) (eq? (car a) '&)))
(a (if isamp (cadr a) a))
(stmts (cons `(= ,g (call (top ,(if isamp 'ptr_arg_cconvert 'cconvert)) ,ty ,a)) stmts))
(ca `(call (top ,(if isamp 'ptr_arg_unsafe_convert 'unsafe_convert)) ,ty ,g)))
(loop (if isseq F (cdr F)) (cdr A) stmts
(list* g (if isamp `(& ,ca) ca) C))))))))
(define (expand-function-def e) ;; handle function or stagedfunction
(let ((name (cadr e)))
(if (and (pair? name) (memq (car name) '(tuple block)))
(expand-forms (cons '-> (cdr e)))
(expand-function-def- e))))
;; convert (where (where x S) T) to (where x T S)
(define (flatten-where-expr e)
(let loop ((ex e)
(vars '()))
(if (and (pair? ex) (eq? (car ex) 'where))
(loop (cadr ex) (append! (reverse (cddr ex)) vars))
`(where ,ex ,.(reverse! vars)))))
(define (expand-function-def- e)
(let* ((name (cadr e))
(where (if (and (pair? name) (eq? (car name) 'where))
(let ((w (flatten-where-expr name)))
(begin0 (cddr w)
(if (not (and (pair? (cadr w)) (memq (caadr w) '(call |::|))))
(error (string "invalid assignment location \"" (deparse name) "\"")))
(set! name (cadr w))))
#f))
(dcl (and (pair? name) (eq? (car name) '|::|)))
(rett (if dcl (caddr name) 'Any))
(name (if dcl (cadr name) name)))
(cond ((and (length= e 2) (symbol? name))
(if (or (eq? name 'true) (eq? name 'false))
(error (string "invalid function name \"" name "\"")))
`(method ,name))
((not (pair? name)) e)
((eq? (car name) 'call)
(let* ((head (cadr name))
(argl (cddr name))
(has-sp (and (not where) (pair? head) (eq? (car head) 'curly)))
(name (deprecate-dotparen (if has-sp (cadr head) head)))
(op (let ((op_ (maybe-undotop name))) ; handle .op -> broadcast deprecation
(if op_
(syntax-deprecation #f (string "function " (deparse name) "(...)")
(string "function Base.broadcast(::typeof(" (deparse op_) "), ...)")))
op_))
(name (if op '(|.| Base (inert broadcast)) name))
(argl (if op (cons `(|::| (call (core Typeof) ,op)) argl) argl))
(sparams (map analyze-typevar (cond (has-sp (cddr head))
(where where)
(else '()))))
(isstaged (eq? (car e) 'stagedfunction))
(adj-decl (lambda (n) (if (and (decl? n) (length= n 2))
`(|::| |#self#| ,(cadr n))
n)))
;; fill in first (closure) argument
(farg (if (decl? name)
(adj-decl name)
`(|::| |#self#| (call (core Typeof) ,name))))
(argl (fix-arglist
(arglist-unshift argl farg)
(and (not (any kwarg? argl)) (not (and (pair? argl)
(pair? (car argl))
(eq? (caar argl) 'parameters))))))
(name (if (or (decl? name) (and (pair? name) (eq? (car name) 'curly)))
#f name)))