~technomancy/fennel

ref: 0d2935bf5f1bdf410566173d59ce8f2cd486e146 fennel/src/fennel/specials.fnl -rw-r--r-- 55.9 KiB
0d2935bf — Andrew DeFilippo Initial fix and test case 2 months ago
                                                                                
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
;; This module contains all the special forms; all built in Fennel constructs
;; which cannot be implemented as macros. It also contains some core compiler
;; functionality which is kept in this module for circularity reasons.

(local utils (require :fennel.utils))
(local view (require :fennel.view))
(local parser (require :fennel.parser))
(local compiler (require :fennel.compiler))
(local unpack (or table.unpack _G.unpack))

(local SPECIALS compiler.scopes.global.specials)

(fn wrap-env [env]
  "Convert a fennel environment table to a Lua environment table.
This means automatically unmangling globals when getting a value,
and mangling values when setting a value. This means the original env
will see its values updated as expected, regardless of mangling rules."
  (setmetatable []
                {:__index (fn [_ key]
                            (if (= (type key) :string)
                                (. env (compiler.global-unmangling key))
                                (. env key)))
                 :__newindex (fn [_ key value]
                               (if (= (type key) :string)
                                   (tset env (compiler.global-unmangling key)
                                         value)
                                   (tset env key value)))
                 ;; manually in 5.1
                 :__pairs (fn []
                            (fn putenv [k v]
                              (values (if (= (type k) :string)
                                          (compiler.global-unmangling k)
                                          k)
                                      v))

                            (values next (utils.kvmap env putenv) nil))}))

(fn current-global-names [env]
  ;; if there's a metatable on env, we need to make sure it's one that has a
  ;; __pairs metamethod, otherwise we give up entirely on globals checking.
  (let [mt (match (getmetatable env)
             ;; newer lua versions know about __pairs natively not 5.1
             {: __pairs} (collect [k v (__pairs env)] (values k v))
             nil (or env _G))]
    (and mt (utils.kvmap mt compiler.global-unmangling))))

(fn load-code [code environment filename]
  "Load Lua code with an environment in all recent Lua versions"
  (let [environment (or environment (rawget _G :_ENV) _G)]
    (if (and (rawget _G :setfenv) (rawget _G :loadstring))
        (let [f (assert (_G.loadstring code filename))]
          (_G.setfenv f environment)
          f)
        (assert (load code filename :t environment)))))

(fn doc* [tgt name]
  "Return a docstring for tgt."
  (if (not tgt)
      (.. name " not found")
      (let [docstring (-> (: compiler.metadata :get tgt :fnl/docstring)
                          (or "#<undocumented>")
                          (: :gsub "\n$" "")
                          (: :gsub "\n" "\n  "))
            mt (getmetatable tgt)]
        (if (or (= (type tgt) :function)
                (and (= (type mt) :table) (= (type (. mt :__call)) :function)))
            (let [arglist (table.concat (or (: compiler.metadata :get tgt
                                               :fnl/arglist)
                                            ["#<unknown-arguments>"])
                                        " ")]
              (string.format "(%s%s%s)\n  %s" name
                             (if (> (length arglist) 0) " " "") arglist
                             docstring))
            (string.format "%s\n  %s" name docstring)))))

;; TODO: replace this with using the special fn's own docstring
(fn doc-special [name arglist docstring body-form?]
  "Add a docstring to a special form."
  (tset compiler.metadata (. SPECIALS name)
        {:fnl/arglist arglist :fnl/docstring docstring :fnl/body-form? body-form?}))

(fn compile-do [ast scope parent start]
  "Compile a list of forms for side effects."
  (let [start (or start 2)
        len (length ast)
        sub-scope (compiler.make-scope scope)]
    (for [i start len]
      (compiler.compile1 (. ast i) sub-scope parent {:nval 0}))))

(fn SPECIALS.do [ast scope parent opts start chunk sub-scope pre-syms]
  "Implements a do statement, starting at the 'start'-th element.
By default, start is 2."
  (let [start (or start 2)
        sub-scope (or sub-scope (compiler.make-scope scope))
        chunk (or chunk [])
        len (length ast)
        retexprs {:returned true}]
    (fn compile-body [outer-target outer-tail outer-retexprs]
      (if (< len start)
          ;; In the unlikely event we do a do with no arguments
          (compiler.compile1 nil sub-scope chunk
                             {:tail outer-tail :target outer-target})
          ;; There will be side-effects
          (for [i start len]
            (let [subopts {:nval (or (and (not= i len) 0) opts.nval)
                           :tail (or (and (= i len) outer-tail) nil)
                           :target (or (and (= i len) outer-target) nil)}
                  _ (utils.propagate-options opts subopts)
                  subexprs (compiler.compile1 (. ast i) sub-scope chunk subopts)]
              (when (not= i len)
                (compiler.keep-side-effects subexprs parent nil (. ast i))))))
      (compiler.emit parent chunk ast)
      (compiler.emit parent :end ast)
      (or outer-retexprs retexprs))

    ;; See if we need special handling to get the return values of the do block
    (if (or opts.target (= opts.nval 0) opts.tail)
        (do
          (compiler.emit parent :do ast)
          (compile-body opts.target opts.tail))
        opts.nval
        ;; generate a local target
        (let [syms []]
          (for [i 1 opts.nval]
            (let [s (or (and pre-syms (. pre-syms i)) (compiler.gensym scope))]
              (tset syms i s)
              (tset retexprs i (utils.expr s :sym))))
          (let [outer-target (table.concat syms ", ")]
            (compiler.emit parent (string.format "local %s" outer-target) ast)
            (compiler.emit parent :do ast)
            (compile-body outer-target opts.tail)))
        ;; we will use an IIFE for the do
        (let [fname (compiler.gensym scope)
              fargs (if scope.vararg "..." "")]
          (compiler.emit parent
                         (string.format "local function %s(%s)" fname fargs) ast)
          (utils.hook :do ast sub-scope)
          (compile-body nil true
                        (utils.expr (.. fname "(" fargs ")") :statement))))))

(doc-special :do ["..."] "Evaluate multiple forms; return last value." true)

(fn SPECIALS.values [ast scope parent]
  "Unlike most expressions and specials, 'values' resolves with multiple
values, one for each argument, allowing multiple return values. The last
expression can return multiple arguments as well, allowing for more than
the number of expected arguments."
  (let [len (length ast)
        exprs []]
    (for [i 2 len]
      (let [subexprs (compiler.compile1 (. ast i) scope parent
                                        {:nval (and (not= i len) 1)})]
        (table.insert exprs (. subexprs 1))
        (when (= i len)
          (for [j 2 (length subexprs)]
            (table.insert exprs (. subexprs j))))))
    exprs))

(doc-special :values ["..."]
             "Return multiple values from a function. Must be in tail position.")

(fn deep-tostring [x key?]
  "Tostring for literal tables created with {} or [].
Recursively transforms tables into one-line string representation.
Main purpose to print function argument list in docstring."
  (let [elems []]
    (if (utils.sequence? x)
        (.. "[" (table.concat (icollect [_ v (ipairs x)]
                                (deep-tostring v))
                              " ") "]")
        (utils.table? x)
        (.. "{" (table.concat (icollect [k v (pairs x)]
                                (.. (deep-tostring k true) " "
                                    (deep-tostring v)))
                              " ") "}")
        (and key? (= (type x) :string) (x:find "^[-%w?\\^_!$%&*+./@:|<=>]+$"))
        (.. ":" x)
        (= (type x) :string)
        (-> (string.format "%q" x)
            (: :gsub "\\\"" "\\\\\"")
            (: :gsub "\"" "\\\""))
        (tostring x))))

(fn set-fn-metadata [arg-list docstring parent fn-name]
  (when utils.root.options.useMetadata
    (let [args (utils.map arg-list #(: "\"%s\"" :format (deep-tostring $)))
          meta-fields ["\"fnl/arglist\"" (.. "{" (table.concat args ", ") "}")]]
      (when docstring
        (table.insert meta-fields "\"fnl/docstring\"")
        (table.insert meta-fields (.. "\""
                                      (-> docstring
                                          (: :gsub "%s+$" "")
                                          (: :gsub "\\" "\\\\")
                                          (: :gsub "\n" "\\n")
                                          (: :gsub "\"" "\\\""))
                                      "\"")))
      (let [meta-str (: "require(\"%s\").metadata" :format
                        (or utils.root.options.moduleName :fennel))]
        (compiler.emit parent
                       (: "pcall(function() %s:setall(%s, %s) end)" :format
                          meta-str fn-name (table.concat meta-fields ", ")))))))

(fn get-fn-name [ast scope fn-name multi]
  (if (and fn-name (not= (. fn-name 1) :nil))
      (values (if (not multi)
                  (compiler.declare-local fn-name [] scope ast)
                  (. (compiler.symbol-to-expression fn-name scope) 1))
              (not multi) 3)
      (values nil true 2)))

(fn compile-named-fn [ast f-scope f-chunk parent index fn-name local?
                      arg-name-list arg-list docstring]
  (for [i (+ index 1) (length ast)]
    (compiler.compile1 (. ast i) f-scope f-chunk
                       {:nval (or (and (not= i (length ast)) 0) nil)
                        :tail (= i (length ast))}))
  (compiler.emit parent
                 (string.format (if local? "local function %s(%s)"
                                    "%s = function(%s)")
                                fn-name (table.concat arg-name-list ", "))
                 ast)
  (compiler.emit parent f-chunk ast)
  (compiler.emit parent :end ast)
  (set-fn-metadata arg-list docstring parent fn-name)
  (utils.hook :fn ast f-scope)
  (utils.expr fn-name :sym))

(fn compile-anonymous-fn [ast f-scope f-chunk parent index
                          arg-name-list arg-list docstring scope]
  ;; TODO: eventually compile this to an actual function value instead of
  ;; binding it to a local and using the symbol. the difficulty here is that
  ;; a function is a chunk with many lines, and the current representation of
  ;; an expr can only be a string, making it difficult to pass around without
  ;; losing line numbering information.
  (let [fn-name (compiler.gensym scope)]
    (compile-named-fn ast f-scope f-chunk parent index fn-name true
                      arg-name-list arg-list docstring)))

(fn SPECIALS.fn [ast scope parent]
  (let [f-scope (doto (compiler.make-scope scope)
                  (tset :vararg false))
        f-chunk []
        fn-sym (utils.sym? (. ast 2))
        multi (and fn-sym (utils.multi-sym? (. fn-sym 1)))
        (fn-name local? index) (get-fn-name ast scope fn-sym multi)
        arg-list (compiler.assert (utils.table? (. ast index))
                                  "expected parameters table" ast)]
    (compiler.assert (or (not multi) (not multi.multi-sym-method-call))
                     (.. "unexpected multi symbol " (tostring fn-name)) fn-sym)

    (fn get-arg-name [arg]
      (if (utils.varg? arg)
          (do
            (compiler.assert (= arg (. arg-list (length arg-list)))
                             "expected vararg as last parameter" ast)
            (set f-scope.vararg true)
            "...")
          (and (utils.sym? arg) (not= (utils.deref arg) :nil)
               (not (utils.multi-sym? (utils.deref arg))))
          (compiler.declare-local arg [] f-scope ast)
          (utils.table? arg)
          (let [raw (utils.sym (compiler.gensym scope))
                declared (compiler.declare-local raw [] f-scope ast)]
            (compiler.destructure arg raw ast f-scope f-chunk
                                  {:declaration true
                                   :nomulti true
                                   :symtype :arg})
            declared)
          (compiler.assert false
                           (: "expected symbol for function parameter: %s"
                              :format (tostring arg))
                           (. ast 2))))

    (let [arg-name-list (utils.map arg-list get-arg-name)
          (index docstring) (if (and (= (type (. ast (+ index 1))) :string)
                                     (< (+ index 1) (length ast)))
                                (values (+ index 1) (. ast (+ index 1)))
                                (values index nil))]
      (if fn-name
          (compile-named-fn ast f-scope f-chunk parent index fn-name local?
                            arg-name-list arg-list docstring)
          (compile-anonymous-fn ast f-scope f-chunk parent index
                                arg-name-list arg-list docstring scope)))))

(doc-special :fn [:name? :args :docstring? "..."]
             "Function syntax. May optionally include a name and docstring.
If a name is provided, the function will be bound in the current scope.
When called with the wrong number of args, excess args will be discarded
and lacking args will be nil, use lambda for arity-checked functions." true)

;; FORBIDDEN KNOWLEDGE:
;; (lua "print('hello!')") -> prints hello, evaluates to nil
;; (lua "print 'hello!'" "10") -> prints hello, evaluates to the number 10
;; (lua nil "{1,2,3}") -> Evaluates to a table literal
(fn SPECIALS.lua [ast _ parent]
  (compiler.assert (or (= (length ast) 2) (= (length ast) 3))
                   "expected 1 or 2 arguments" ast)
  (when (not= :nil (-?> (utils.sym? (. ast 2)) utils.deref))
    (table.insert parent {: ast :leaf (tostring (. ast 2))}))
  (when (not= :nil (-?> (utils.sym? (. ast 3)) utils.deref))
    (tostring (. ast 3))))

(fn SPECIALS.doc [ast scope parent]
  (assert utils.root.options.useMetadata
          "can't look up doc with metadata disabled.")
  (compiler.assert (= (length ast) 2) "expected one argument" ast)
  (let [target (utils.deref (. ast 2))
        special-or-macro (or (. scope.specials target) (. scope.macros target))]
    (if special-or-macro
        (: "print(%q)" :format (doc* special-or-macro target))
        (let [[value] (compiler.compile1 (. ast 2) scope parent {:nval 1})]
          ;; need to require here since the metadata is stored in the module
          ;; and we need to make sure we look it up in the same module it was
          ;; declared from.
          (: "print(require('%s').doc(%s, '%s'))" :format
             (or utils.root.options.moduleName :fennel) (tostring value)
             (tostring (. ast 2)))))))

(doc-special :doc [:x]
             "Print the docstring and arglist for a function, macro, or special form.")

(fn dot [ast scope parent]
  "Table lookup; equivalent to tbl[] in Lua."
  (compiler.assert (< 1 (length ast)) "expected table argument" ast)
  (let [len (length ast)
        [lhs] (compiler.compile1 (. ast 2) scope parent {:nval 1})]
    (if (= len 2)
        (tostring lhs)
        (let [indices []]
          (for [i 3 len]
            (let [index (. ast i)]
              (if (and (= (type index) :string)
                       (utils.valid-lua-identifier? index))
                  (table.insert indices (.. "." index))
                  (let [[index] (compiler.compile1 index scope parent {:nval 1})]
                    (table.insert indices (.. "[" (tostring index) "]"))))))
          ;; Extra parens are needed unless the target is a table literal
          (if (or (: (tostring lhs) :find "[{\"0-9]") (= :nil (tostring lhs)))
              (.. "(" (tostring lhs) ")" (table.concat indices))
              (.. (tostring lhs) (table.concat indices)))))))

(tset SPECIALS "." dot)

(doc-special "." [:tbl :key1 "..."]
             "Look up key1 in tbl table. If more args are provided, do a nested lookup.")

(fn SPECIALS.global [ast scope parent]
  (compiler.assert (= (length ast) 3) "expected name and value" ast)
  (compiler.destructure (. ast 2) (. ast 3) ast scope parent
                        {:forceglobal true :nomulti true :symtype :global})
  nil)

(doc-special :global [:name :val] "Set name as a global with val.")

(fn SPECIALS.set [ast scope parent]
  (compiler.assert (= (length ast) 3) "expected name and value" ast)
  (compiler.destructure (. ast 2) (. ast 3) ast scope parent
                        {:noundef true :symtype :set})
  nil)

(doc-special :set [:name :val]
             "Set a local variable to a new value. Only works on locals using var.")

(fn set-forcibly!* [ast scope parent]
  (compiler.assert (= (length ast) 3) "expected name and value" ast)
  (compiler.destructure (. ast 2) (. ast 3) ast scope parent
                        {:forceset true :symtype :set})
  nil)

(tset SPECIALS :set-forcibly! set-forcibly!*)

(fn local* [ast scope parent]
  (compiler.assert (= (length ast) 3) "expected name and value" ast)
  (compiler.destructure (. ast 2) (. ast 3) ast scope parent
                        {:declaration true :nomulti true :symtype :local})
  nil)

(tset SPECIALS :local local*)

(doc-special :local [:name :val] "Introduce new top-level immutable local.")

(fn SPECIALS.var [ast scope parent]
  (compiler.assert (= (length ast) 3) "expected name and value" ast)
  (compiler.destructure (. ast 2) (. ast 3) ast scope parent
                        {:declaration true
                         :isvar true
                         :nomulti true
                         :symtype :var})
  nil)

(doc-special :var [:name :val] "Introduce new mutable local.")

(fn SPECIALS.let [ast scope parent opts]
  (let [bindings (. ast 2)
        pre-syms []]
    (compiler.assert (or (utils.list? bindings) (utils.table? bindings))
                     "expected binding table" ast)
    (compiler.assert (= (% (length bindings) 2) 0)
                     "expected even number of name/value bindings" (. ast 2))
    (compiler.assert (>= (length ast) 3) "expected body expression" (. ast 1))
    ;; we have to gensym the binding for the let body's return value before
    ;; compiling the binding vector, otherwise there's a possibility to conflict
    (for [_ 1 (or opts.nval 0)]
      (table.insert pre-syms (compiler.gensym scope)))
    (let [sub-scope (compiler.make-scope scope)
          sub-chunk []]
      (for [i 1 (length bindings) 2]
        (compiler.destructure (. bindings i) (. bindings (+ i 1)) ast sub-scope
                              sub-chunk
                              {:declaration true :nomulti true :symtype :let}))
      (SPECIALS.do ast scope parent opts 3 sub-chunk sub-scope pre-syms))))

(doc-special :let ["[name1 val1 ... nameN valN]" "..."]
             "Introduces a new scope in which a given set of local bindings are used."
             true)

(fn get-prev-line [parent]
  (if (= :table (type parent))
      (get-prev-line (or parent.leaf (. parent (length parent))))
      (or parent "")))

(fn disambiguate? [rootstr parent]
  (or (rootstr:match "^{")
      (match (get-prev-line parent)
        prev-line (prev-line:match "%)$"))))

(fn SPECIALS.tset [ast scope parent]
  "For setting items in a table."
  (compiler.assert (> (length ast) 3)
                   "expected table, key, and value arguments" ast)
  (let [root (. (compiler.compile1 (. ast 2) scope parent {:nval 1}) 1)
        keys []]
    (for [i 3 (- (length ast) 1)]
      (let [[key] (compiler.compile1 (. ast i) scope parent {:nval 1})]
        (table.insert keys (tostring key))))
    (let [value (. (compiler.compile1 (. ast (length ast)) scope parent
                                      {:nval 1}) 1)
          rootstr (tostring root)
          fmtstr (if (disambiguate? rootstr parent)
                     "do end (%s)[%s] = %s"
                     "%s[%s] = %s")]
      (compiler.emit parent
                     (: fmtstr :format rootstr (table.concat keys "][")
                        (tostring value)) ast))))

(doc-special :tset [:tbl :key1 "..." :keyN :val]
             "Set the value of a table field. Can take additional keys to set
nested values, but all parents must contain an existing table.")

(fn calculate-target [scope opts]
  (if (not (or opts.tail opts.target opts.nval))
      (values :iife true nil)
      (and opts.nval (not= opts.nval 0) (not opts.target))
      (let [accum []
            target-exprs []]
        ;; We need to create a target
        (for [i 1 opts.nval]
          (let [s (compiler.gensym scope)]
            (tset accum i s)
            (tset target-exprs i (utils.expr s :sym))))
        (values :target opts.tail (table.concat accum ", ") target-exprs))
      (values :none opts.tail opts.target)))

;; TODO: refactor; too long!
(fn if* [ast scope parent opts]
  (let [do-scope (compiler.make-scope scope)
        branches []
        (wrapper inner-tail inner-target target-exprs) (calculate-target scope
                                                                         opts)
        body-opts {:nval opts.nval :tail inner-tail :target inner-target}]
    (fn compile-body [i]
      (let [chunk []
            cscope (compiler.make-scope do-scope)]
        (compiler.keep-side-effects (compiler.compile1 (. ast i) cscope chunk
                                                       body-opts)
                                    chunk nil (. ast i))
        {: chunk :scope cscope}))

    (for [i 2 (- (length ast) 1) 2]
      (let [condchunk []
            res (compiler.compile1 (. ast i) do-scope condchunk {:nval 1})
            cond (. res 1)
            branch (compile-body (+ i 1))]
        (set branch.cond cond)
        (set branch.condchunk condchunk)
        (set branch.nested (and (not= i 2) (= (next condchunk nil) nil)))
        (table.insert branches branch)))
    ;; Emit code
    (let [has-else? (and (> (length ast) 3) (= (% (length ast) 2) 0))
          else-branch (and has-else? (compile-body (length ast)))
          s (compiler.gensym scope)
          buffer []]
      (var last-buffer buffer)
      (for [i 1 (length branches)]
        (let [branch (. branches i)
              fstr (if (not branch.nested) "if %s then" "elseif %s then")
              cond (tostring branch.cond)
              cond-line (if (and (= cond :true) branch.nested
                                 (= i (length branches)) (not has-else?))
                            :else (: fstr :format cond))]
          (if branch.nested
              (compiler.emit last-buffer branch.condchunk ast)
              (each [_ v (ipairs branch.condchunk)]
                (compiler.emit last-buffer v ast)))
          (compiler.emit last-buffer cond-line ast)
          (compiler.emit last-buffer branch.chunk ast)
          (if (= i (length branches))
              (do
                (if has-else?
                    (do
                      (compiler.emit last-buffer :else ast)
                      (compiler.emit last-buffer else-branch.chunk ast))
                    ;; TODO: Consolidate use of cond-line ~= "else" with has-else
                    (and inner-target (not= cond-line :else))
                    (do
                      (compiler.emit last-buffer :else ast)
                      (compiler.emit last-buffer
                                     (: "%s = nil" :format inner-target) ast)))
                (compiler.emit last-buffer :end ast))
              (not (. (. branches (+ i 1)) :nested))
              (let [next-buffer []]
                (compiler.emit last-buffer :else ast)
                (compiler.emit last-buffer next-buffer ast)
                (compiler.emit last-buffer :end ast)
                (set last-buffer next-buffer)))))
      ;; Emit if
      (if (= wrapper :iife)
          (let [iifeargs (or (and scope.vararg "...") "")]
            (compiler.emit parent
                           (: "local function %s(%s)" :format (tostring s)
                              iifeargs) ast)
            (compiler.emit parent buffer ast)
            (compiler.emit parent :end ast)
            (utils.expr (: "%s(%s)" :format (tostring s) iifeargs) :statement))
          (= wrapper :none) ; Splice result right into code
          (do
            (for [i 1 (length buffer)]
              (compiler.emit parent (. buffer i) ast))
            {:returned true})
          ;; wrapper is target
          (do
            (compiler.emit parent (: "local %s" :format inner-target) ast)
            (for [i 1 (length buffer)]
              (compiler.emit parent (. buffer i) ast))
            target-exprs)))))

(tset SPECIALS :if if*)

(doc-special :if [:cond1 :body1 "..." :condN :bodyN]
             "Conditional form.
Takes any number of condition/body pairs and evaluates the first body where
the condition evaluates to truthy. Similar to cond in other lisps.")

(fn remove-until-condition [bindings]
  (when (= :until (. bindings (- (length bindings) 1)))
    (table.remove bindings (- (length bindings) 1))
    (table.remove bindings)))

(fn compile-until [condition scope chunk]
  (when condition
    (let [[condition-lua] (compiler.compile1 condition scope chunk {:nval 1})]
      (compiler.emit chunk (: "if %s then break end" :format
                              (tostring condition-lua))
                     (utils.expr condition :expression)))))

(fn SPECIALS.each [ast scope parent]
  (compiler.assert (>= (length ast) 3) "expected body expression" (. ast 1))
  (let [binding (compiler.assert (utils.table? (. ast 2))
                                 "expected binding table" ast)
        _ (compiler.assert (<= 2 (length binding))
                           "expected binding and iterator" binding)
        until-condition (remove-until-condition binding)
        iter (table.remove binding (length binding))
        ; last item is iterator call
        destructures []
        new-manglings []
        sub-scope (compiler.make-scope scope)]
    (fn destructure-binding [v]
      (if (utils.sym? v)
          (compiler.declare-local v [] sub-scope ast new-manglings)
          (let [raw (utils.sym (compiler.gensym sub-scope))]
            (tset destructures raw v)
            (compiler.declare-local raw [] sub-scope ast))))

    (let [bind-vars (utils.map binding destructure-binding)
          vals (compiler.compile1 iter sub-scope parent)
          val-names (utils.map vals tostring)
          chunk []]
      (compiler.emit parent
                     (: "for %s in %s do" :format (table.concat bind-vars ", ")
                        (table.concat val-names ", ")) ast)
      (each [raw args (utils.stablepairs destructures)]
        (compiler.destructure args raw ast sub-scope chunk
                              {:declaration true :nomulti true :symtype :each}))
      (compiler.apply-manglings sub-scope new-manglings ast)
      (compile-until until-condition sub-scope chunk)
      (compile-do ast sub-scope chunk 3)
      (compiler.emit parent chunk ast)
      (compiler.emit parent :end ast))))

(doc-special :each ["[key value (iterator)]" "..."]
             "Runs the body once for each set of values provided by the given iterator.
Most commonly used with ipairs for sequential tables or pairs for  undefined
order, but can be used with any iterator." true)

(fn while* [ast scope parent]
  (let [len1 (length parent)
        condition (. (compiler.compile1 (. ast 2) scope parent {:nval 1}) 1)
        len2 (length parent)
        sub-chunk []]
    (if (not= len1 len2)
        ;; compound condition; move new compilation to subchunk
        (do
          (for [i (+ len1 1) len2]
            (table.insert sub-chunk (. parent i))
            (tset parent i nil))
          (compiler.emit parent "while true do" ast)
          (compiler.emit sub-chunk
                         (: "if not %s then break end" :format (. condition 1))
                         ast))
        ;; simple condition
        (compiler.emit parent (.. "while " (tostring condition) " do") ast))
    (compile-do ast (compiler.make-scope scope) sub-chunk 3)
    (compiler.emit parent sub-chunk ast)
    (compiler.emit parent :end ast)))

(tset SPECIALS :while while*)

(doc-special :while [:condition "..."]
             "The classic while loop. Evaluates body until a condition is non-truthy."
             true)

(fn for* [ast scope parent]
  (let [ranges (compiler.assert (utils.table? (. ast 2))
                                "expected binding table" ast)
        until-condition (remove-until-condition (. ast 2))
        binding-sym (table.remove (. ast 2) 1)
        sub-scope (compiler.make-scope scope)
        range-args []
        chunk []]
    (compiler.assert (utils.sym? binding-sym)
                     (: "unable to bind %s %s" :format (type binding-sym)
                        (tostring binding-sym)) (. ast 2))
    (compiler.assert (>= (length ast) 3) "expected body expression" (. ast 1))
    (for [i 1 (math.min (length ranges) 3)]
      (tset range-args i (tostring (. (compiler.compile1 (. ranges i) sub-scope
                                                         parent {:nval 1})
                                      1))))
    (compiler.emit parent
                   (: "for %s = %s do" :format
                      (compiler.declare-local binding-sym [] sub-scope ast)
                      (table.concat range-args ", ")) ast)
    (compile-until until-condition sub-scope chunk)
    (compile-do ast sub-scope chunk 3)
    (compiler.emit parent chunk ast)
    (compiler.emit parent :end ast)))

(tset SPECIALS :for for*)

(doc-special :for ["[index start stop step?]" "..."]
             "Numeric loop construct.
Evaluates body once for each value between start and stop (inclusive)." true)

(fn native-method-call [ast _scope _parent target args]
  "Prefer native Lua method calls when method name is a valid Lua identifier."
  (let [[_ _ method-string] ast
        call-string (if (or (= target.type :literal)
                            (= target.type :expression))
                        "(%s):%s(%s)" "%s:%s(%s)")]
    (utils.expr (string.format call-string (tostring target) method-string
                               (table.concat args ", "))
                :statement)))

(fn nonnative-method-call [ast scope parent target args]
  "When we don't have to protect against double-evaluation, it's not so bad."
  (let [method-string (tostring (. (compiler.compile1 (. ast 3) scope parent
                                                      {:nval 1})
                                   1))
        args [(tostring target) (unpack args)]]
    (utils.expr (string.format "%s[%s](%s)" (tostring target) method-string
                               (table.concat args ", "))
                :statement)))

(fn double-eval-protected-method-call [ast scope parent target args]
  "When double-evaluation is a concern, we have to wrap an IIFE."
  (let [method-string (tostring (. (compiler.compile1 (. ast 3) scope parent
                                                      {:nval 1})
                                   1))
        call "(function(tgt, m, ...) return tgt[m](tgt, ...) end)(%s, %s)"]
    (table.insert args 1 method-string)
    (utils.expr (string.format call (tostring target) (table.concat args ", "))
                :statement)))

(fn method-call [ast scope parent]
  (compiler.assert (< 2 (length ast)) "expected at least 2 arguments" ast)
  (let [[target] (compiler.compile1 (. ast 2) scope parent {:nval 1})
        args []]
    (for [i 4 (length ast)]
      (let [subexprs (compiler.compile1 (. ast i) scope parent
                                        {:nval (if (not= i (length ast)) 1)})]
        (utils.map subexprs tostring args)))
    (if (and (= (type (. ast 3)) :string)
             (utils.valid-lua-identifier? (. ast 3)))
        (native-method-call ast scope parent target args)
        (= target.type :sym)
        (nonnative-method-call ast scope parent target args)
        ;; When the target is an expression, we can't use the naive
        ;; nonnative-method-call approach, because it will cause the target
        ;; to be evaluated twice. This is fine if it's a symbol but if it's
        ;; the result of a function call, that function could have side-effects.
        ;; See test-short-circuit in test/misc.fnl for an example of the problem.
        (double-eval-protected-method-call ast scope parent target args))))

(tset SPECIALS ":" method-call)

(doc-special ":" [:tbl :method-name "..."] "Call the named method on tbl with the provided args.
Method name doesn't have to be known at compile-time; if it is, use
(tbl:method-name ...) instead.")

(fn SPECIALS.comment [ast _ parent]
  (let [els []]
    (for [i 2 (length ast)]
      (table.insert els (pick-values 1 (: (tostring (. ast i)) :gsub "\n" " "))))
    (compiler.emit parent (.. "-- " (table.concat els " ")) ast)))

(doc-special :comment ["..."] "Comment which will be emitted in Lua output." true)

(fn hashfn-max-used [f-scope i max]
  (let [max (if (. f-scope.symmeta (.. "$" i) :used) i max)]
    (if (< i 9)
        (hashfn-max-used f-scope (+ i 1) max)
        max)))

(fn SPECIALS.hashfn [ast scope parent]
  (compiler.assert (= (length ast) 2) "expected one argument" ast)
  (let [f-scope (doto (compiler.make-scope scope)
                  (tset :vararg false)
                  (tset :hashfn true))
        f-chunk []
        name (compiler.gensym scope)
        symbol (utils.sym name)
        args []]
    (compiler.declare-local symbol [] scope ast)
    (for [i 1 9]
      (tset args i (compiler.declare-local (utils.sym (.. "$" i)) [] f-scope
                                           ast)))
    ;; recursively walk the AST, transforming $... into ...

    (fn walker [idx node parent-node]
      (if (and (utils.sym? node) (= (utils.deref node) "$..."))
          (do
            (tset parent-node idx (utils.varg))
            (set f-scope.vararg true))
          (or (utils.list? node) (utils.table? node))))

    (utils.walk-tree (. ast 2) walker)
    ;; compile body
    (compiler.compile1 (. ast 2) f-scope f-chunk {:tail true})
    (let [max-used (hashfn-max-used f-scope 1 0)]
      (when f-scope.vararg
        (compiler.assert (= max-used 0)
                         "$ and $... in hashfn are mutually exclusive" ast))
      (let [arg-str (if f-scope.vararg
                        (utils.deref (utils.varg))
                        (table.concat args ", " 1 max-used))]
        (compiler.emit parent
                       (string.format "local function %s(%s)" name arg-str) ast)
        (compiler.emit parent f-chunk ast)
        (compiler.emit parent :end ast)
        (utils.expr name :sym)))))

(doc-special :hashfn ["..."]
             "Function literal shorthand; args are either $... OR $1, $2, etc.")

(fn arithmetic-special [name zero-arity unary-prefix nval ast scope parent]
  (match (length ast)
    1 (do
        (compiler.assert zero-arity "Expected more than 0 arguments" ast)
        (utils.expr zero-arity :literal))
    len (let [operands []
              padded-op (.. " " name " ")]
          (for [i 2 len]
            (let [subexprs (compiler.compile1 (. ast i) scope parent {: nval})]
              (utils.map subexprs tostring operands)))
          (if (= (length operands) 1)
              (if unary-prefix
                  (.. "(" unary-prefix padded-op (. operands 1) ")")
                  (. operands 1))
              (.. "(" (table.concat operands padded-op) ")")))))

(fn define-arithmetic-special [name zero-arity unary-prefix lua-name]
  (tset SPECIALS name (partial arithmetic-special (or lua-name name) zero-arity
                               unary-prefix 1))
  (doc-special name [:a :b "..."]
               "Arithmetic operator; works the same as Lua but accepts more arguments."))

(define-arithmetic-special "+" :0)
(define-arithmetic-special ".." "''")
(define-arithmetic-special "^")
(define-arithmetic-special "-" nil "")
(define-arithmetic-special "*" :1)
(define-arithmetic-special "%")
(define-arithmetic-special "/" nil :1)
(define-arithmetic-special "//" nil :1)

(fn SPECIALS.or [ast scope parent]
  ;; and/or have nval=nil in order to trigger IIFE so they can short-circuit
  (arithmetic-special :or :false nil nil ast scope parent))

(fn SPECIALS.and [ast scope parent]
  (arithmetic-special :and :true nil nil ast scope parent))

(doc-special :and [:a :b "..."]
             "Boolean operator; works the same as Lua but accepts more arguments.")

(doc-special :or [:a :b "..."]
             "Boolean operator; works the same as Lua but accepts more arguments.")

(fn bitop-special [native-name lib-name zero-arity unary-prefix ast scope parent]
  (if (= (length ast) 1)
      (compiler.assert zero-arity "Expected more than 0 arguments." ast)
      (let [len (length ast)
            operands []
            padded-native-name (.. " " native-name " ")
            prefixed-lib-name (.. "bit." lib-name)]
        (for [i 2 len]
          (let [subexprs (compiler.compile1 (. ast i) scope parent
                                            {:nval (if (not= i len) 1)})]
            (utils.map subexprs tostring operands)))
        (if (= (length operands) 1)
            (if utils.root.options.useBitLib
                (.. prefixed-lib-name "(" unary-prefix ", " (. operands 1) ")")
                (.. "(" unary-prefix padded-native-name (. operands 1) ")"))
            (if utils.root.options.useBitLib
                (.. prefixed-lib-name "(" (table.concat operands ", ") ")")
                (.. "(" (table.concat operands padded-native-name) ")"))))))

(fn define-bitop-special [name zero-arity unary-prefix native]
  (tset SPECIALS name (partial bitop-special native name zero-arity unary-prefix)))

(define-bitop-special :lshift nil :1 "<<")
(define-bitop-special :rshift nil :1 ">>")
(define-bitop-special :band :0 :0 "&")
(define-bitop-special :bor :0 :0 "|")
(define-bitop-special :bxor :0 :0 "~")

(doc-special :lshift [:x :n]
             "Bitwise logical left shift of x by n bits.
Only works in Lua 5.3+ or LuaJIT with the --use-bit-lib flag.")

(doc-special :rshift [:x :n]
             "Bitwise logical right shift of x by n bits.
Only works in Lua 5.3+ or LuaJIT with the --use-bit-lib flag.")

(doc-special :band [:x1 :x2 "..."] "Bitwise AND of any number of arguments.
Only works in Lua 5.3+ or LuaJIT with the --use-bit-lib flag.")

(doc-special :bor [:x1 :x2 "..."] "Bitwise OR of any number of arguments.
Only works in Lua 5.3+ or LuaJIT with the --use-bit-lib flag.")

(doc-special :bxor [:x1 :x2 "..."] "Bitwise XOR of any number of arguments.
Only works in Lua 5.3+ or LuaJIT with the --use-bit-lib flag.")

(doc-special ".." [:a :b "..."]
             "String concatenation operator; works the same as Lua but accepts more arguments.")

(fn native-comparator [op [_ lhs-ast rhs-ast] scope parent]
  "Naively compile a binary comparison to Lua."
  (let [[lhs] (compiler.compile1 lhs-ast scope parent {:nval 1})
        [rhs] (compiler.compile1 rhs-ast scope parent {:nval 1})]
    (string.format "(%s %s %s)" (tostring lhs) op (tostring rhs))))

(fn double-eval-protected-comparator [op chain-op ast scope parent]
  "Compile a multi-arity comparison to a binary Lua comparison."
  (let [arglist []
        comparisons []
        vals []
        chain (string.format " %s " (or chain-op :and))]
    (for [i 2 (length ast)]
      (table.insert arglist (tostring (compiler.gensym scope)))
      (table.insert vals (tostring (. (compiler.compile1 (. ast i) scope parent
                                                         {:nval 1})
                                      1))))
    (for [i 1 (- (length arglist) 1)]
      (table.insert comparisons
                    (string.format "(%s %s %s)" (. arglist i) op
                                   (. arglist (+ i 1)))))
    ;; The function call here introduces some overhead, but it is the only way
    ;; to compile this safely while preventing both double-evaluation of
    ;; side-effecting values and early evaluation of values which should never
    ;; happen in the case of a short-circuited call. See test-short-circuit in
    ;; test/misc.fnl for an example of the problem.
    (string.format "(function(%s) return %s end)(%s)"
                   (table.concat arglist ",") (table.concat comparisons chain)
                   (table.concat vals ","))))

(fn define-comparator-special [name lua-op chain-op]
  (let [op (or lua-op name)]
    (fn opfn [ast scope parent]
      (compiler.assert (< 2 (length ast)) "expected at least two arguments" ast)
      (if (= 3 (length ast))
          (native-comparator op ast scope parent)
          (double-eval-protected-comparator op chain-op ast scope parent)))

    (tset SPECIALS name opfn))
  (doc-special name [:a :b "..."]
               "Comparison operator; works the same as Lua but accepts more arguments."))

(define-comparator-special ">")
(define-comparator-special "<")
(define-comparator-special ">=")
(define-comparator-special "<=")
(define-comparator-special "=" "==")
(define-comparator-special :not= "~=" :or)

(fn define-unary-special [op realop]
  (fn opfn [ast scope parent]
    (compiler.assert (= (length ast) 2) "expected one argument" ast)
    (let [tail (compiler.compile1 (. ast 2) scope parent {:nval 1})]
      (.. (or realop op) (tostring (. tail 1)))))

  (tset SPECIALS op opfn))

(define-unary-special :not "not ")
(doc-special :not [:x] "Logical operator; works the same as Lua.")
(define-unary-special :bnot "~")
(doc-special :bnot [:x] "Bitwise negation; only works in Lua 5.3+ or LuaJIT with the --use-bit-lib flag.")
(define-unary-special :length "#")
(doc-special :length [:x] "Returns the length of a table or string.")

;; backwards-compatibility aliases
(tset SPECIALS "~=" (. SPECIALS :not=))
(tset SPECIALS "#" (. SPECIALS :length))

(fn SPECIALS.quote [ast scope parent]
  (compiler.assert (= (length ast) 2) "expected one argument")
  (var (runtime this-scope) (values true scope))
  (while this-scope
    (set this-scope this-scope.parent)
    (when (= this-scope compiler.scopes.compiler)
      (set runtime false)))
  (compiler.do-quote (. ast 2) scope parent runtime))

(doc-special :quote [:x]
             "Quasiquote the following form. Only works in macro/compiler scope.")

;; This is the compile-env equivalent of package.loaded. It's used by
;; require-macros and import-macros, but also by require when used from within
;; default compiler scope.
(local macro-loaded {})

(local already-warned? {:_G true})

(local compile-env-warning (-> ["WARNING: Attempting to %s %s in compile scope."
                                "In future versions of Fennel this will not be allowed without the"
                                "--no-compiler-sandbox flag or passing a :compilerEnv globals table"
                                "in the options.\n"]
                               (table.concat "\n")))

(fn compiler-env-warn [_ key]
  "Warn once when allowing a global that the sandbox would normally block."
  (let [v (. _G key)]
    (when (and v io io.stderr (not (. already-warned? key)))
      (tset already-warned? key true)
      ;; Make this an error in a future release!
      (io.stderr:write (compile-env-warning:format "use global" key)))
    v))

(fn safe-getmetatable [tbl]
  (let [mt (getmetatable tbl)]
    ;; we can't let the string metatable leak
    (assert (not= mt (getmetatable "")) "Illegal metatable access!")
    mt))

;; Circularity
(var safe-require nil)

;; Note that this is not yet the safe compiler env! Enforcing a compiler sandbox
;; is a breaking change, so we need to do it in a way that warns for several
;; releases before enforcing the sandbox.
(fn safe-compiler-env [strict?]
  (setmetatable {:table (utils.copy table)
                 :math (utils.copy math)
                 :string (utils.copy string)
                 : pairs
                 : ipairs
                 : select
                 : tostring
                 : tonumber
                 : pcall
                 : xpcall
                 : next
                 : print
                 : type
                 :bit (rawget _G :bit)
                 : assert
                 : error
                 : setmetatable
                 :getmetatable safe-getmetatable
                 :require safe-require
                 : rawget
                 : rawset
                 : rawequal
                 :rawlen (rawget _G :rawlen)}
                {:__index (if strict? nil compiler-env-warn)}))

(fn combined-mt-pairs [env]
  (let [combined {}
        {: __index} (getmetatable env)]
    (when (= :table (type __index))
      (each [k v (pairs __index)]
        (tset combined k v)))
    (each [k v (values next env nil)]
      (tset combined k v))
    (values next combined nil)))

(fn make-compiler-env [ast scope parent strict?]
  (let [provided (match utils.root.options
                   {:compiler-env :strict} (safe-compiler-env true)
                   {: compilerEnv} compilerEnv
                   {: compiler-env} compiler-env
                   _ (safe-compiler-env strict?))
        env {:_AST ast
             :_CHUNK parent
             :_IS_COMPILER true
             :_SCOPE scope
             :_SPECIALS compiler.scopes.global.specials
             :_VARARG (utils.varg)
             : macro-loaded
             : unpack
             :assert-compile compiler.assert
             ;; AST functions
             :list utils.list
             :list? utils.list?
             :multi-sym? utils.multi-sym?
             :sequence utils.sequence
             :sequence? utils.sequence?
             :sym utils.sym
             :sym? utils.sym?
             :table? utils.table?
             :varg? utils.varg?
             : view
             ;; scoping functions
             :gensym (fn [base]
                       (utils.sym (compiler.gensym (or compiler.scopes.macro
                                                       scope)
                                                   base)))
             :get-scope (fn []
                          compiler.scopes.macro)
             :in-scope? (fn [symbol]
                          (compiler.assert compiler.scopes.macro
                                           "must call from macro" ast)
                          (. compiler.scopes.macro.manglings
                             (tostring symbol)))
             :macroexpand (fn [form]
                            (compiler.assert compiler.scopes.macro
                                             "must call from macro" ast)
                            (compiler.macroexpand form
                                                  compiler.scopes.macro))}]
    (set env._G env)
    (setmetatable env
                  {:__index provided
                   :__newindex provided
                   :__pairs combined-mt-pairs})))

;; have search-module use package.config to process package.path (windows compat)
(local cfg (string.gmatch package.config "([^\n]+)"))
(local (dirsep pathsep pathmark)
       (values (or (cfg) "/") (or (cfg) ";") (or (cfg) "?")))

(local pkg-config {: dirsep : pathmark : pathsep})

(fn escapepat [str]
  "Escape a string for safe use in a Lua pattern."
  (string.gsub str "[^%w]" "%%%1"))

(fn search-module [modulename pathstring]
  (let [pathsepesc (escapepat pkg-config.pathsep)
        pattern (: "([^%s]*)%s" :format pathsepesc pathsepesc)
        no-dot-module (: modulename :gsub "%." pkg-config.dirsep)
        fullpath (.. (or pathstring utils.fennel-module.path)
                     pkg-config.pathsep)]
    (fn try-path [path]
      (let [filename (: path :gsub (escapepat pkg-config.pathmark)
                        no-dot-module)
            filename2 (: path :gsub (escapepat pkg-config.pathmark) modulename)]
        (match (or (io.open filename) (io.open filename2))
          file (do
                 (file:close)
                 filename))))

    (fn find-in-path [start]
      (match (fullpath:match pattern start)
        path (or (try-path path) (find-in-path (+ start (length path) 1)))))

    (find-in-path 1)))

(fn make-searcher [options]
  "This will allow regular `require` to work with Fennel:
table.insert(package.loaders, fennel.searcher)"
  (fn [module-name]
    (let [opts (utils.copy utils.root.options)]
      (each [k v (pairs (or options {}))]
        (tset opts k v))
      (set opts.module-name module-name)
      (match (search-module module-name)
        filename (values (partial utils.fennel-module.dofile filename opts)
                         filename)))))

(fn macro-globals [env globals]
  (let [allowed (current-global-names env)]
    (each [_ k (pairs (or globals []))]
      (table.insert allowed k))
    allowed))

(fn fennel-macro-searcher [module-name]
  (match (search-module module-name utils.fennel-module.macro-path)
    filename (values (partial utils.fennel-module.dofile filename
                              {:env :_COMPILER}) filename)))

(fn lua-macro-searcher [module-name]
  (match (search-module module-name package.path)
    filename (let [code (with-open [f (io.open filename)] (assert (f:read :*a)))
                   chunk (load-code code (make-compiler-env) filename)]
               (values chunk filename))))

(local macro-searchers [lua-macro-searcher fennel-macro-searcher])

(fn search-macro-module [modname n]
  (match (. macro-searchers n)
    f (match (f modname)
        (loader ?filename) (values loader ?filename)
        _ (search-macro-module modname (+ n 1)))))

(fn metadata-only-fennel [modname]
  "Let limited Fennel module thru just for purposes of compiling docstrings."
  (if (or (= modname :fennel.macros)
          (and package package.loaded
               (= :table (type (. package.loaded modname)))
               (= (. package.loaded modname :metadata) compiler.metadata)))
      {:metadata compiler.metadata}))

(set safe-require (fn [modname]
                    "This is a replacement for require for use in macro contexts.
It ensures that compile-scoped modules are loaded differently from regular
modules in the compiler environment."
                    (or (. macro-loaded modname) (metadata-only-fennel modname)
                        (let [(loader filename) (search-macro-module modname 1)]
                          (compiler.assert loader (.. modname " module not found."))
                          (tset macro-loaded modname (loader modname filename))
                          (. macro-loaded modname)))))

(fn add-macros [macros* ast scope]
  (compiler.assert (utils.table? macros*) "expected macros to be table" ast)
  (each [k v (pairs macros*)]
    (compiler.assert (= (type v) :function)
                     "expected each macro to be function" ast)
    (tset scope.macros k v)))

(fn SPECIALS.require-macros [ast scope parent real-ast]
  (compiler.assert (= (length ast) 2) "Expected one module name argument"
                   (or real-ast ast)) ; real-ast comes from import-macros
  ;; don't require modname to be string literal; it just needs to compile to one
  (let [filename (or (. ast 2 :filename) ast.filename)
        modname-chunk (load-code (compiler.compile (. ast 2)) nil filename)
        modname (modname-chunk utils.root.options.module-name filename)]
    (compiler.assert (= (type modname) :string)
                     "module name must compile to string" (or real-ast ast))
    (when (not (. macro-loaded modname))
      (let [env (make-compiler-env ast scope parent)
            (loader filename) (search-macro-module modname 1)]
        (compiler.assert loader (.. modname " module not found.") ast)
        (tset macro-loaded modname (loader modname filename))))
    (add-macros (. macro-loaded modname) ast scope parent)))

(doc-special :require-macros [:macro-module-name]
             "Load given module and use its contents as macro definitions in current scope.
Macro module should return a table of macro functions with string keys.
Consider using import-macros instead as it is more flexible.")

(fn emit-included-fennel [src path opts sub-chunk]
  "Emit Fennel code in src into sub-chunk."
  (let [subscope (compiler.make-scope utils.root.scope.parent)
        forms []]
    (when utils.root.options.requireAsInclude
      (set subscope.specials.require compiler.require-include))
    ;; parse Fennel src into table of exprs to know which expr is the tail
    (each [_ val (parser.parser (parser.string-stream src) path)]
      (table.insert forms val))
    ;; Compile the forms into sub-chunk; compiler.compile1 is necessary
    ;; for all nested includes to be emitted in the same root chunk
    ;; in the top-level module.
    (for [i 1 (length forms)]
      (let [subopts (if (= i (length forms)) {:tail true} {:nval 0})]
        (utils.propagate-options opts subopts)
        (compiler.compile1 (. forms i) subscope sub-chunk subopts)))))

(fn include-path [ast opts path mod fennel?]
  "Helper function for include once we have determined the path to use."
  (tset utils.root.scope.includes mod :fnl/loading)
  (let [src (with-open [f (assert (io.open path))]
              (: (f:read :*all) :gsub "[\r\n]*$" ""))
        ;; splice in source and memoize it in compiler AND package.preload
        ;; so we can include it again without duplication, even in runtime
        ret (utils.expr (.. "require(\"" mod "\")") :statement)
        target (: "package.preload[%q]" :format mod)
        preload-str (.. target " = " target " or function(...)")
        (temp-chunk sub-chunk) (values [] [])]
    (compiler.emit temp-chunk preload-str ast)
    (compiler.emit temp-chunk sub-chunk)
    (compiler.emit temp-chunk :end ast)
    ;; Splice temp-chunk to begining of root chunk
    (each [i v (ipairs temp-chunk)]
      (table.insert utils.root.chunk i v))
    ;; For fennel source, compile sub-chunk AFTER splicing into start of
    ;; root chunk.
    (if fennel?
        (emit-included-fennel src path opts sub-chunk)
        ;; For Lua source, simply emit src into the loaders's body
        (compiler.emit sub-chunk src ast))
    ;; Put in cache and return
    (tset utils.root.scope.includes mod ret)
    ret))

(fn include-circular-fallback [mod modexpr fallback ast]
  "If a circular include is detected, fall back to require if possible."
  (when (= (. utils.root.scope.includes mod) :fnl/loading) ; circular include
    (compiler.assert fallback "circular include detected" ast)
    (fallback modexpr)))

(fn SPECIALS.include [ast scope parent opts]
  (compiler.assert (= (length ast) 2) "expected one argument" ast)
  (let [modexpr (. (compiler.compile1 (. ast 2) scope parent {:nval 1}) 1)]
    (if (or (not= modexpr.type :literal) (not= (: (. modexpr 1) :byte) 34))
        (if opts.fallback
            (opts.fallback modexpr)
            (compiler.assert false "module name must be string literal" ast))
        (let [mod ((load-code (.. "return " (. modexpr 1))))]
          (or (include-circular-fallback mod modexpr opts.fallback ast)
              (. utils.root.scope.includes mod) ; check cache
              ;; Find path to Fennel or Lua source; prefering Fennel
              (match (search-module mod)
                fennel-path (include-path ast opts fennel-path mod true)
                _ (let [lua-path (search-module mod package.path)]
                    (if lua-path (include-path ast opts lua-path mod false)
                        opts.fallback (opts.fallback modexpr)
                        (compiler.assert false (.. "module not found " mod) ast)))))))))

(doc-special :include [:module-name-literal]
             "Like require but load the target module during compilation and embed it in the
Lua output. The module must be a string literal and resolvable at compile time.")

(fn eval-compiler* [ast scope parent]
  (let [env (make-compiler-env ast scope parent)
        opts (utils.copy utils.root.options)]
    (set opts.scope (compiler.make-scope compiler.scopes.compiler))
    (set opts.allowedGlobals (macro-globals env (current-global-names)))
    ((load-code (compiler.compile ast opts) (wrap-env env)) opts.module-name
                                                            ast.filename)))

(fn SPECIALS.macros [ast scope parent]
  (compiler.assert (= (length ast) 2) "Expected one table argument" ast)
  (add-macros (eval-compiler* (. ast 2) scope parent) ast scope parent))

(doc-special :macros
             ["{:macro-name-1 (fn [...] ...) ... :macro-name-N macro-body-N}"]
             "Define all functions in the given table as macros local to the current scope.")

(fn SPECIALS.eval-compiler [ast scope parent]
  (let [old-first (. ast 1)]
    (tset ast 1 (utils.sym :do))
    (let [val (eval-compiler* ast scope parent)]
      (tset ast 1 old-first)
      val)))

(doc-special :eval-compiler ["..."]
             "Evaluate the body at compile-time. Use the macro system instead if possible."
             true)

{:doc doc*
 : current-global-names
 : load-code
 : macro-loaded
 : macro-searchers
 : make-compiler-env
 : search-module
 : make-searcher
 : wrap-env}