-
Notifications
You must be signed in to change notification settings - Fork 0
/
fennel.lua
executable file
·4243 lines (4204 loc) · 161 KB
/
fennel.lua
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
package.preload["fennel.repl"] = package.preload["fennel.repl"] or function(...)
local utils = require("fennel.utils")
local parser = require("fennel.parser")
local compiler = require("fennel.compiler")
local specials = require("fennel.specials")
local function default_read_chunk(parser_state)
local function _0_()
if (0 < parser_state["stack-size"]) then
return ".."
else
return ">> "
end
end
io.write(_0_())
io.flush()
local input = io.read()
return (input and (input .. "\n"))
end
local function default_on_values(xs)
io.write(table.concat(xs, "\9"))
return io.write("\n")
end
local function default_on_error(errtype, err, lua_source)
local function _1_()
local _0_0 = errtype
if (_0_0 == "Lua Compile") then
return ("Bad code generated - likely a bug with the compiler:\n" .. "--- Generated Lua Start ---\n" .. lua_source .. "--- Generated Lua End ---\n")
elseif (_0_0 == "Runtime") then
return (compiler.traceback(tostring(err), 4) .. "\n")
else
local _ = _0_0
return ("%s error: %s\n"):format(errtype, tostring(err))
end
end
return io.write(_1_())
end
local save_source = table.concat({"local ___i___ = 1", "while true do", " local name, value = debug.getlocal(1, ___i___)", " if(name and name ~= \"___i___\") then", " ___replLocals___[name] = value", " ___i___ = ___i___ + 1", " else break end end"}, "\n")
local function splice_save_locals(env, lua_source)
env.___replLocals___ = (env.___replLocals___ or {})
local spliced_source = {}
local bind = "local %s = ___replLocals___['%s']"
for line in lua_source:gmatch("([^\n]+)\n?") do
table.insert(spliced_source, line)
end
for name in pairs(env.___replLocals___) do
table.insert(spliced_source, 1, bind:format(name, name))
end
if ((1 < #spliced_source) and (spliced_source[#spliced_source]):match("^ *return .*$")) then
table.insert(spliced_source, #spliced_source, save_source)
end
return table.concat(spliced_source, "\n")
end
local commands = {}
local function command_3f(input)
return input:match("^%s*,")
end
local function command_docs()
local _0_
do
local tbl_0_ = {}
for name, f in pairs(commands) do
tbl_0_[(#tbl_0_ + 1)] = (" ,%s - %s"):format(name, ((compiler.metadata):get(f, "fnl/docstring") or "undocumented"))
end
_0_ = tbl_0_
end
return table.concat(_0_, "\n")
end
commands.help = function(_, _0, on_values)
return on_values({("Welcome to Fennel.\nThis is the REPL where you can enter code to be evaluated.\nYou can also run these repl commands:\n\n" .. command_docs() .. "\n ,exit - Leave the repl.\n\nUse (doc something) to see descriptions for individual macros and special forms.\n\nFor more information about the language, see https://fennel-lang.org/reference")})
end
do end (compiler.metadata):set(commands.help, "fnl/docstring", "Show this message.")
local function reload(module_name, env, on_values, on_error)
local _0_0, _1_0 = pcall(specials["load-code"]("return require(...)", env), module_name)
if ((_0_0 == true) and (nil ~= _1_0)) then
local old = _1_0
local _ = nil
package.loaded[module_name] = nil
_ = nil
local ok, new = pcall(require, module_name)
local new0 = nil
if not ok then
on_values({new})
new0 = old
else
new0 = new
end
if ((type(old) == "table") and (type(new0) == "table")) then
for k, v in pairs(new0) do
old[k] = v
end
for k in pairs(old) do
if (nil == new0[k]) then
old[k] = nil
end
end
package.loaded[module_name] = old
end
return on_values({"ok"})
elseif ((_0_0 == false) and (nil ~= _1_0)) then
local msg = _1_0
local function _3_()
local _2_0 = msg:gsub("\n.*", "")
return _2_0
end
return on_error("Runtime", _3_())
end
end
commands.reload = function(env, read, on_values, on_error)
local _0_0, _1_0, _2_0 = pcall(read)
if ((_0_0 == true) and (_1_0 == true) and (nil ~= _2_0)) then
local module_sym = _2_0
return reload(tostring(module_sym), env, on_values, on_error)
elseif ((_0_0 == false) and true and true) then
local _3fparse_ok = _1_0
local _3fmsg = _2_0
return on_error("Parse", (_3fmsg or _3fparse_ok))
end
end
do end (compiler.metadata):set(commands.reload, "fnl/docstring", "Reload the specified module.")
commands.reset = function(env, _, on_values)
env.___replLocals___ = {}
return on_values({"ok"})
end
do end (compiler.metadata):set(commands.reset, "fnl/docstring", "Erase all repl-local scope.")
local function load_plugin_commands()
if (utils.root and utils.root.options and utils.root.options.plugins) then
for _, plugin in ipairs(utils.root.options.plugins) do
for name, f in pairs(plugin) do
local _0_0 = name:match("^repl%-command%-(.*)")
if (nil ~= _0_0) then
local cmd_name = _0_0
commands[cmd_name] = (commands[cmd_name] or f)
end
end
end
return nil
end
end
local function run_command(input, read, loop, env, on_values, on_error)
load_plugin_commands()
local command_name = input:match(",([^%s/]+)")
do
local _0_0 = commands[command_name]
if (nil ~= _0_0) then
local command = _0_0
command(env, read, on_values, on_error)
else
local _ = _0_0
if ("exit" ~= command_name) then
on_values({"Unknown command", command_name})
end
end
end
if ("exit" ~= command_name) then
return loop()
end
end
local function completer(env, scope, text)
local matches = {}
local input_fragment = text:gsub(".*[%s)(]+", "")
local function add_partials(input, tbl, prefix)
for k in utils.allpairs(tbl) do
local k0 = nil
if ((tbl == env) or (tbl == env.___replLocals___)) then
k0 = scope.unmanglings[k]
else
k0 = k
end
if ((#matches < 2000) and (type(k0) == "string") and (input == k0:sub(0, #input))) then
table.insert(matches, (prefix .. k0))
end
end
return nil
end
local function add_matches(input, tbl, prefix)
local prefix0 = nil
if prefix then
prefix0 = (prefix .. ".")
else
prefix0 = ""
end
if not input:find("%.") then
return add_partials(input, tbl, prefix0)
else
local head, tail = input:match("^([^.]+)%.(.*)")
local raw_head = nil
if ((tbl == env) or (tbl == env.___replLocals___)) then
raw_head = scope.manglings[head]
else
raw_head = head
end
if (type(tbl[raw_head]) == "table") then
return add_matches(tail, tbl[raw_head], (prefix0 .. head))
end
end
end
add_matches(input_fragment, (scope.specials or {}))
add_matches(input_fragment, (scope.macros or {}))
add_matches(input_fragment, (env.___replLocals___ or {}))
add_matches(input_fragment, env)
add_matches(input_fragment, (env._ENV or env._G or {}))
return matches
end
local function repl(options)
local old_root_options = utils.root.options
local env = nil
if options.env then
env = specials["wrap-env"](options.env)
else
env = setmetatable({}, {__index = (rawget(_G, "_ENV") or _G)})
end
local save_locals_3f = ((options.saveLocals ~= false) and env.debug and env.debug.getlocal)
local opts = {}
local _ = nil
for k, v in pairs(options) do
opts[k] = v
end
_ = nil
local read_chunk = (opts.readChunk or default_read_chunk)
local on_values = (opts.onValues or default_on_values)
local on_error = (opts.onError or default_on_error)
local pp = (opts.pp or tostring)
local byte_stream, clear_stream = parser.granulate(read_chunk)
local chars = {}
local read, reset = nil, nil
local function _1_(parser_state)
local c = byte_stream(parser_state)
table.insert(chars, c)
return c
end
read, reset = parser.parser(_1_)
local scope = compiler["make-scope"]()
opts.useMetadata = (options.useMetadata ~= false)
if (opts.allowedGlobals == nil) then
opts.allowedGlobals = specials["current-global-names"](opts.env)
end
if opts.registerCompleter then
local function _3_(...)
return completer(env, scope, ...)
end
opts.registerCompleter(_3_)
end
local function print_values(...)
local vals = {...}
local out = {}
env._, env.__ = vals[1], vals
for i = 1, select("#", ...) do
table.insert(out, pp(vals[i]))
end
return on_values(out)
end
local function loop()
for k in pairs(chars) do
chars[k] = nil
end
local ok, parse_ok_3f, x = pcall(read)
local src_string = string.char((table.unpack or _G.unpack)(chars))
utils.root.options = opts
if not ok then
on_error("Parse", parse_ok_3f)
clear_stream()
reset()
return loop()
elseif command_3f(src_string) then
return run_command(src_string, read, loop, env, on_values, on_error)
else
if parse_ok_3f then
do
local _4_0, _5_0 = pcall(compiler.compile, x, {["assert-compile"] = opts["assert-compile"], ["parse-error"] = opts["parse-error"], correlate = opts.correlate, moduleName = opts.moduleName, scope = scope, source = src_string, useBitLib = opts.useBitLib, useMetadata = opts.useMetadata})
if ((_4_0 == false) and (nil ~= _5_0)) then
local msg = _5_0
clear_stream()
on_error("Compile", msg)
elseif ((_4_0 == true) and (nil ~= _5_0)) then
local src = _5_0
local src0 = nil
if save_locals_3f then
src0 = splice_save_locals(env, src)
else
src0 = src
end
local _7_0, _8_0 = pcall(specials["load-code"], src0, env)
if ((_7_0 == false) and (nil ~= _8_0)) then
local msg = _8_0
clear_stream()
on_error("Lua Compile", msg, src0)
elseif (true and (nil ~= _8_0)) then
local _0 = _7_0
local chunk = _8_0
local function _9_()
return print_values(chunk())
end
local function _10_(...)
return on_error("Runtime", ...)
end
xpcall(_9_, _10_)
end
end
end
utils.root.options = old_root_options
return loop()
end
end
end
return loop()
end
return repl
end
package.preload["fennel.view"] = package.preload["fennel.view"] or function(...)
local type_order = {["function"] = 5, boolean = 2, number = 1, string = 3, table = 4, thread = 7, userdata = 6}
local function sort_keys(_0_0, _1_0)
local _1_ = _0_0
local a = _1_[1]
local _2_ = _1_0
local b = _2_[1]
local ta = type(a)
local tb = type(b)
if ((ta == tb) and ((ta == "string") or (ta == "number"))) then
return (a < b)
else
local dta = type_order[ta]
local dtb = type_order[tb]
if (dta and dtb) then
return (dta < dtb)
elseif dta then
return true
elseif dtb then
return false
else
return (ta < tb)
end
end
end
local function table_kv_pairs(t)
local assoc_3f = false
local i = 1
local kv = {}
local insert = table.insert
for k, v in pairs(t) do
if ((type(k) ~= "number") or (k ~= i)) then
assoc_3f = true
end
i = (i + 1)
insert(kv, {k, v})
end
table.sort(kv, sort_keys)
if (#kv == 0) then
return kv, "empty"
else
local function _2_()
if assoc_3f then
return "table"
else
return "seq"
end
end
return kv, _2_()
end
end
local function count_table_appearances(t, appearances)
if (type(t) == "table") then
if not appearances[t] then
appearances[t] = 1
for k, v in pairs(t) do
count_table_appearances(k, appearances)
count_table_appearances(v, appearances)
end
else
appearances[t] = ((appearances[t] or 0) + 1)
end
end
return appearances
end
local function save_table(t, seen)
local seen0 = (seen or {len = 0})
local id = (seen0.len + 1)
if not seen0[t] then
seen0[t] = id
seen0.len = id
end
return seen0
end
local function detect_cycle(t, seen, _3fk)
if ("table" == type(t)) then
seen[t] = true
local _2_0, _3_0 = next(t, _3fk)
if ((nil ~= _2_0) and (nil ~= _3_0)) then
local k = _2_0
local v = _3_0
return (seen[k] or detect_cycle(k, seen) or seen[v] or detect_cycle(v, seen) or detect_cycle(t, seen, k))
end
end
end
local function visible_cycle_3f(t, options)
return (options["detect-cycles?"] and detect_cycle(t, {}) and save_table(t, options.seen) and (1 < (options.appearances[t] or 0)))
end
local function table_indent(t, indent, id)
local opener_length = nil
if id then
opener_length = (#tostring(id) + 2)
else
opener_length = 1
end
return (indent + opener_length)
end
local pp = nil
local function concat_table_lines(elements, options, multiline_3f, indent, table_type, prefix)
local indent_str = ("\n" .. string.rep(" ", indent))
local open = nil
local function _2_()
if ("seq" == table_type) then
return "["
else
return "{"
end
end
open = ((prefix or "") .. _2_())
local close = nil
if ("seq" == table_type) then
close = "]"
else
close = "}"
end
local oneline = (open .. table.concat(elements, " ") .. close)
if (not options["one-line?"] and (multiline_3f or ((indent + #oneline) > options["line-length"]))) then
return (open .. table.concat(elements, indent_str) .. close)
else
return oneline
end
end
local function pp_associative(t, kv, options, indent, key_3f)
local multiline_3f = false
local id = options.seen[t]
if (options.level >= options.depth) then
return "{...}"
elseif (id and options["detect-cycles?"]) then
return ("@" .. id .. "{...}")
else
local visible_cycle_3f0 = visible_cycle_3f(t, options)
local id0 = (visible_cycle_3f0 and options.seen[t])
local indent0 = table_indent(t, indent, id0)
local slength = nil
local function _3_()
local _2_0 = rawget(_G, "utf8")
if _2_0 then
return _2_0.len
else
return _2_0
end
end
local function _4_(_241)
return #_241
end
slength = ((options["utf8?"] and _3_()) or _4_)
local prefix = nil
if visible_cycle_3f0 then
prefix = ("@" .. id0)
else
prefix = ""
end
local items = nil
do
local tbl_0_ = {}
for _, _6_0 in pairs(kv) do
local _7_ = _6_0
local k = _7_[1]
local v = _7_[2]
local _8_
do
local k0 = pp(k, options, (indent0 + 1), true)
local v0 = pp(v, options, (indent0 + slength(k0) + 1))
multiline_3f = (multiline_3f or k0:find("\n") or v0:find("\n"))
_8_ = (k0 .. " " .. v0)
end
tbl_0_[(#tbl_0_ + 1)] = _8_
end
items = tbl_0_
end
return concat_table_lines(items, options, multiline_3f, indent0, "table", prefix)
end
end
local function pp_sequence(t, kv, options, indent)
local multiline_3f = false
local id = options.seen[t]
if (options.level >= options.depth) then
return "[...]"
elseif (id and options["detect-cycles?"]) then
return ("@" .. id .. "[...]")
else
local visible_cycle_3f0 = visible_cycle_3f(t, options)
local id0 = (visible_cycle_3f0 and options.seen[t])
local indent0 = table_indent(t, indent, id0)
local prefix = nil
if visible_cycle_3f0 then
prefix = ("@" .. id0)
else
prefix = ""
end
local items = nil
do
local tbl_0_ = {}
for _, _3_0 in pairs(kv) do
local _4_ = _3_0
local _0 = _4_[1]
local v = _4_[2]
local _5_
do
local v0 = pp(v, options, indent0)
multiline_3f = (multiline_3f or v0:find("\n"))
_5_ = v0
end
tbl_0_[(#tbl_0_ + 1)] = _5_
end
items = tbl_0_
end
return concat_table_lines(items, options, multiline_3f, indent0, "seq", prefix)
end
end
local function concat_lines(lines, options, indent, force_multi_line_3f)
if (#lines == 0) then
if options["empty-as-sequence?"] then
return "[]"
else
return "{}"
end
else
local oneline = nil
local _2_
do
local tbl_0_ = {}
for _, line in ipairs(lines) do
tbl_0_[(#tbl_0_ + 1)] = line:gsub("^%s+", "")
end
_2_ = tbl_0_
end
oneline = table.concat(_2_, " ")
if (not options["one-line?"] and (force_multi_line_3f or oneline:find("\n") or ((indent + #oneline) > options["line-length"]))) then
return table.concat(lines, ("\n" .. string.rep(" ", indent)))
else
return oneline
end
end
end
local function pp_metamethod(t, metamethod, options, indent)
if (options.level >= options.depth) then
if options["empty-as-sequence?"] then
return "[...]"
else
return "{...}"
end
else
local _ = nil
local function _2_(_241)
return visible_cycle_3f(_241, options)
end
options["visible-cycle?"] = _2_
_ = nil
local lines, force_multi_line_3f = metamethod(t, pp, options, indent)
options["visible-cycle?"] = nil
local _3_0 = type(lines)
if (_3_0 == "string") then
return lines
elseif (_3_0 == "table") then
return concat_lines(lines, options, indent, force_multi_line_3f)
else
local _0 = _3_0
return error("__fennelview metamethod must return a table of lines")
end
end
end
local function pp_table(x, options, indent)
options.level = (options.level + 1)
local x0 = nil
do
local _2_0 = nil
if options["metamethod?"] then
local _3_0 = x
if _3_0 then
local _4_0 = getmetatable(_3_0)
if _4_0 then
_2_0 = _4_0.__fennelview
else
_2_0 = _4_0
end
else
_2_0 = _3_0
end
else
_2_0 = nil
end
if (nil ~= _2_0) then
local metamethod = _2_0
x0 = pp_metamethod(x, metamethod, options, indent)
else
local _ = _2_0
local _4_0, _5_0 = table_kv_pairs(x)
if (true and (_5_0 == "empty")) then
local _0 = _4_0
if options["empty-as-sequence?"] then
x0 = "[]"
else
x0 = "{}"
end
elseif ((nil ~= _4_0) and (_5_0 == "table")) then
local kv = _4_0
x0 = pp_associative(x, kv, options, indent)
elseif ((nil ~= _4_0) and (_5_0 == "seq")) then
local kv = _4_0
x0 = pp_sequence(x, kv, options, indent)
else
x0 = nil
end
end
end
options.level = (options.level - 1)
return x0
end
local function number__3estring(n)
local _2_0 = string.gsub(tostring(n), ",", ".")
return _2_0
end
local function colon_string_3f(s)
return s:find("^[-%w?^_!$%&*+./@|<=>]+$")
end
local function pp_string(str, options, indent)
local escs = nil
local _2_
if (options["escape-newlines?"] and (#str < (options["line-length"] - indent))) then
_2_ = "\\n"
else
_2_ = "\n"
end
local function _4_(_241, _242)
return ("\\%03d"):format(_242:byte())
end
escs = setmetatable({["\""] = "\\\"", ["\11"] = "\\v", ["\12"] = "\\f", ["\13"] = "\\r", ["\7"] = "\\a", ["\8"] = "\\b", ["\9"] = "\\t", ["\\"] = "\\\\", ["\n"] = _2_}, {__index = _4_})
return ("\"" .. str:gsub("[%c\\\"]", escs) .. "\"")
end
local function make_options(t, options)
local defaults = {["detect-cycles?"] = true, ["empty-as-sequence?"] = false, ["escape-newlines?"] = false, ["line-length"] = 80, ["metamethod?"] = true, ["one-line?"] = false, ["prefer-colon?"] = false, ["utf8?"] = true, depth = 128}
local overrides = {appearances = count_table_appearances(t, {}), level = 0, seen = {len = 0}}
for k, v in pairs((options or {})) do
defaults[k] = v
end
for k, v in pairs(overrides) do
defaults[k] = v
end
return defaults
end
local function _2_(x, options, indent, colon_3f)
local indent0 = (indent or 0)
local options0 = (options or make_options(x))
local tv = type(x)
local function _4_()
local _3_0 = getmetatable(x)
if _3_0 then
return _3_0.__fennelview
else
return _3_0
end
end
if ((tv == "table") or ((tv == "userdata") and _4_())) then
return pp_table(x, options0, indent0)
elseif (tv == "number") then
return number__3estring(x)
else
local function _5_()
if (colon_3f ~= nil) then
return colon_3f
elseif ("function" == type(options0["prefer-colon?"])) then
return options0["prefer-colon?"](x)
else
return options0["prefer-colon?"]
end
end
if ((tv == "string") and colon_string_3f(x) and _5_()) then
return (":" .. x)
elseif (tv == "string") then
return pp_string(x, options0, indent0)
elseif ((tv == "boolean") or (tv == "nil")) then
return tostring(x)
else
return ("#<" .. tostring(x) .. ">")
end
end
end
pp = _2_
local function view(x, options)
return pp(x, make_options(x, options), 0)
end
return view
end
package.preload["fennel.specials"] = package.preload["fennel.specials"] or function(...)
local utils = require("fennel.utils")
local view = require("fennel.view")
local parser = require("fennel.parser")
local compiler = require("fennel.compiler")
local unpack = (table.unpack or _G.unpack)
local SPECIALS = compiler.scopes.global.specials
local function wrap_env(env)
local function _0_(_, key)
if (type(key) == "string") then
return env[compiler["global-unmangling"](key)]
else
return env[key]
end
end
local function _1_(_, key, value)
if (type(key) == "string") then
env[compiler["global-unmangling"](key)] = value
return nil
else
env[key] = value
return nil
end
end
local function _2_()
local function putenv(k, v)
local _3_
if (type(k) == "string") then
_3_ = compiler["global-unmangling"](k)
else
_3_ = k
end
return _3_, v
end
return next, utils.kvmap(env, putenv), nil
end
return setmetatable({}, {__index = _0_, __newindex = _1_, __pairs = _2_})
end
local function current_global_names(env)
return utils.kvmap((env or _G), compiler["global-unmangling"])
end
local function load_code(code, environment, filename)
local environment0 = (environment or rawget(_G, "_ENV") or _G)
if (rawget(_G, "setfenv") and rawget(_G, "loadstring")) then
local f = assert(_G.loadstring(code, filename))
_G.setfenv(f, environment0)
return f
else
return assert(load(code, filename, "t", environment0))
end
end
local function doc_2a(tgt, name)
if not tgt then
return (name .. " not found")
else
local docstring = (((compiler.metadata):get(tgt, "fnl/docstring") or "#<undocumented>")):gsub("\n$", ""):gsub("\n", "\n ")
local mt = getmetatable(tgt)
if ((type(tgt) == "function") or ((type(mt) == "table") and (type(mt.__call) == "function"))) then
local arglist = table.concat(((compiler.metadata):get(tgt, "fnl/arglist") or {"#<unknown-arguments>"}), " ")
local _0_
if (#arglist > 0) then
_0_ = " "
else
_0_ = ""
end
return string.format("(%s%s%s)\n %s", name, _0_, arglist, docstring)
else
return string.format("%s\n %s", name, docstring)
end
end
end
local function doc_special(name, arglist, docstring, body_form_3f)
compiler.metadata[SPECIALS[name]] = {["fnl/arglist"] = arglist, ["fnl/body-form?"] = body_form_3f, ["fnl/docstring"] = docstring}
return nil
end
local function compile_do(ast, scope, parent, start)
local start0 = (start or 2)
local len = #ast
local sub_scope = compiler["make-scope"](scope)
for i = start0, len do
compiler.compile1(ast[i], sub_scope, parent, {nval = 0})
end
return nil
end
SPECIALS["do"] = function(ast, scope, parent, opts, start, chunk, sub_scope, pre_syms)
local start0 = (start or 2)
local sub_scope0 = (sub_scope or compiler["make-scope"](scope))
local chunk0 = (chunk or {})
local len = #ast
local retexprs = {returned = true}
local function compile_body(outer_target, outer_tail, outer_retexprs)
if (len < start0) then
compiler.compile1(nil, sub_scope0, chunk0, {tail = outer_tail, target = outer_target})
else
for i = start0, len do
local subopts = {nval = (((i ~= len) and 0) or opts.nval), tail = (((i == len) and outer_tail) or nil), target = (((i == len) and outer_target) or nil)}
local _ = utils["propagate-options"](opts, subopts)
local subexprs = compiler.compile1(ast[i], sub_scope0, chunk0, subopts)
if (i ~= len) then
compiler["keep-side-effects"](subexprs, parent, nil, ast[i])
end
end
end
compiler.emit(parent, chunk0, ast)
compiler.emit(parent, "end", ast)
return (outer_retexprs or retexprs)
end
if (opts.target or (opts.nval == 0) or opts.tail) then
compiler.emit(parent, "do", ast)
return compile_body(opts.target, opts.tail)
elseif opts.nval then
local syms = {}
for i = 1, opts.nval do
local s = ((pre_syms and pre_syms[i]) or compiler.gensym(scope))
syms[i] = s
retexprs[i] = utils.expr(s, "sym")
end
local outer_target = table.concat(syms, ", ")
compiler.emit(parent, string.format("local %s", outer_target), ast)
compiler.emit(parent, "do", ast)
return compile_body(outer_target, opts.tail)
else
local fname = compiler.gensym(scope)
local fargs = nil
if scope.vararg then
fargs = "..."
else
fargs = ""
end
compiler.emit(parent, string.format("local function %s(%s)", fname, fargs), ast)
utils.hook("do", ast, sub_scope0)
return compile_body(nil, true, utils.expr((fname .. "(" .. fargs .. ")"), "statement"))
end
end
doc_special("do", {"..."}, "Evaluate multiple forms; return last value.", true)
SPECIALS.values = function(ast, scope, parent)
local len = #ast
local exprs = {}
for i = 2, len do
local subexprs = compiler.compile1(ast[i], scope, parent, {nval = ((i ~= len) and 1)})
table.insert(exprs, subexprs[1])
if (i == len) then
for j = 2, #subexprs do
table.insert(exprs, subexprs[j])
end
end
end
return exprs
end
doc_special("values", {"..."}, "Return multiple values from a function. Must be in tail position.")
local function deep_tostring(x, key_3f)
local elems = {}
if utils["sequence?"](x) then
local _0_
do
local tbl_0_ = {}
for _, v in ipairs(x) do
tbl_0_[(#tbl_0_ + 1)] = deep_tostring(v)
end
_0_ = tbl_0_
end
return ("[" .. table.concat(_0_, " ") .. "]")
elseif utils["table?"](x) then
local _0_
do
local tbl_0_ = {}
for k, v in pairs(x) do
tbl_0_[(#tbl_0_ + 1)] = (deep_tostring(k, true) .. " " .. deep_tostring(v))
end
_0_ = tbl_0_
end
return ("{" .. table.concat(_0_, " ") .. "}")
elseif (key_3f and (type(x) == "string") and x:find("^[-%w?\\^_!$%&*+./@:|<=>]+$")) then
return (":" .. x)
elseif (type(x) == "string") then
return string.format("%q", x):gsub("\\\"", "\\\\\""):gsub("\"", "\\\"")
else
return tostring(x)
end
end
local function set_fn_metadata(arg_list, docstring, parent, fn_name)
if utils.root.options.useMetadata then
local args = nil
local function _0_(_241)
return ("\"%s\""):format(deep_tostring(_241))
end
args = utils.map(arg_list, _0_)
local meta_fields = {"\"fnl/arglist\"", ("{" .. table.concat(args, ", ") .. "}")}
if docstring then
table.insert(meta_fields, "\"fnl/docstring\"")
table.insert(meta_fields, ("\"" .. docstring:gsub("%s+$", ""):gsub("\\", "\\\\"):gsub("\n", "\\n"):gsub("\"", "\\\"") .. "\""))
end
local meta_str = ("require(\"%s\").metadata"):format((utils.root.options.moduleName or "fennel"))
return compiler.emit(parent, ("pcall(function() %s:setall(%s, %s) end)"):format(meta_str, fn_name, table.concat(meta_fields, ", ")))
end
end
local function get_fn_name(ast, scope, fn_name, multi)
if (fn_name and (fn_name[1] ~= "nil")) then
local _0_
if not multi then
_0_ = compiler["declare-local"](fn_name, {}, scope, ast)
else
_0_ = compiler["symbol-to-expression"](fn_name, scope)[1]
end
return _0_, not multi, 3
else
return nil, true, 2
end
end
local function compile_named_fn(ast, f_scope, f_chunk, parent, index, fn_name, local_3f, arg_name_list, arg_list, docstring)
for i = (index + 1), #ast do
compiler.compile1(ast[i], f_scope, f_chunk, {nval = (((i ~= #ast) and 0) or nil), tail = (i == #ast)})
end
local _0_
if local_3f then
_0_ = "local function %s(%s)"
else
_0_ = "%s = function(%s)"
end
compiler.emit(parent, string.format(_0_, 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)
return utils.expr(fn_name, "sym")
end
local function compile_anonymous_fn(ast, f_scope, f_chunk, parent, index, arg_name_list, arg_list, docstring, scope)
local fn_name = compiler.gensym(scope)
return compile_named_fn(ast, f_scope, f_chunk, parent, index, fn_name, true, arg_name_list, arg_list, docstring)
end
SPECIALS.fn = function(ast, scope, parent)
local f_scope = nil
do
local _0_0 = compiler["make-scope"](scope)
_0_0["vararg"] = false
f_scope = _0_0
end
local f_chunk = {}
local fn_sym = utils["sym?"](ast[2])
local multi = (fn_sym and utils["multi-sym?"](fn_sym[1]))
local fn_name, local_3f, index = get_fn_name(ast, scope, fn_sym, multi)
local arg_list = compiler.assert(utils["table?"](ast[index]), "expected parameters table", ast)
compiler.assert((not multi or not multi["multi-sym-method-call"]), ("unexpected multi symbol " .. tostring(fn_name)), fn_sym)
local function get_arg_name(arg)
if utils["varg?"](arg) then
compiler.assert((arg == arg_list[#arg_list]), "expected vararg as last parameter", ast)
f_scope.vararg = true
return "..."
elseif (utils["sym?"](arg) and (utils.deref(arg) ~= "nil") and not utils["multi-sym?"](utils.deref(arg))) then
return compiler["declare-local"](arg, {}, f_scope, ast)
elseif utils["table?"](arg) then
local raw = utils.sym(compiler.gensym(scope))
local declared = compiler["declare-local"](raw, {}, f_scope, ast)
compiler.destructure(arg, raw, ast, f_scope, f_chunk, {declaration = true, nomulti = true, symtype = "arg"})
return declared
else
return compiler.assert(false, ("expected symbol for function parameter: %s"):format(tostring(arg)), ast[2])
end
end
local arg_name_list = utils.map(arg_list, get_arg_name)
local index0, docstring = nil, nil
if ((type(ast[(index + 1)]) == "string") and ((index + 1) < #ast)) then
index0, docstring = (index + 1), ast[(index + 1)]
else
index0, docstring = index, nil
end
if fn_name then
return compile_named_fn(ast, f_scope, f_chunk, parent, index0, fn_name, local_3f, arg_name_list, arg_list, docstring)
else
return compile_anonymous_fn(ast, f_scope, f_chunk, parent, index0, arg_name_list, arg_list, docstring, scope)
end
end
doc_special("fn", {"name?", "args", "docstring?", "..."}, "Function syntax. May optionally include a name and docstring.\nIf a name is provided, the function will be bound in the current scope.\nWhen called with the wrong number of args, excess args will be discarded\nand lacking args will be nil, use lambda for arity-checked functions.", true)
SPECIALS.lua = function(ast, _, parent)
compiler.assert(((#ast == 2) or (#ast == 3)), "expected 1 or 2 arguments", ast)
if (ast[2] ~= nil) then
table.insert(parent, {ast = ast, leaf = tostring(ast[2])})
end
if (ast[3] ~= nil) then
return tostring(ast[3])
end
end
SPECIALS.doc = function(ast, scope, parent)
assert(utils.root.options.useMetadata, "can't look up doc with metadata disabled.")
compiler.assert((#ast == 2), "expected one argument", ast)
local target = utils.deref(ast[2])
local special_or_macro = (scope.specials[target] or scope.macros[target])
if special_or_macro then
return ("print(%q)"):format(doc_2a(special_or_macro, target))
else
local _0_ = compiler.compile1(ast[2], scope, parent, {nval = 1})
local value = _0_[1]
return ("print(require('%s').doc(%s, '%s'))"):format((utils.root.options.moduleName or "fennel"), tostring(value), tostring(ast[2]))
end
end
doc_special("doc", {"x"}, "Print the docstring and arglist for a function, macro, or special form.")
local function dot(ast, scope, parent)
compiler.assert((1 < #ast), "expected table argument", ast)
local len = #ast
local _0_ = compiler.compile1(ast[2], scope, parent, {nval = 1})
local lhs = _0_[1]
if (len == 2) then
return tostring(lhs)
else
local indices = {}
for i = 3, len do
local index = ast[i]
if ((type(index) == "string") and utils["valid-lua-identifier?"](index)) then