-
Notifications
You must be signed in to change notification settings - Fork 0
/
fennel
executable file
·6536 lines (6465 loc) · 252 KB
/
fennel
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
#!/usr/bin/env lua
package.preload["fennel.binary"] = package.preload["fennel.binary"] or function(...)
local fennel = require("fennel")
local _763_ = require("fennel.utils")
local copy = _763_["copy"]
local warn = _763_["warn"]
local function shellout(command)
local f = io.popen(command)
local stdout = f:read("*all")
return (f:close() and stdout)
end
local function execute(cmd)
local _764_0 = os.execute(cmd)
if (_764_0 == 0) then
return true
elseif (_764_0 == true) then
return true
end
end
local function string__3ec_hex_literal(characters)
local hex = {}
for character in characters:gmatch(".") do
table.insert(hex, ("0x%02x"):format(string.byte(character)))
end
return table.concat(hex, ", ")
end
local c_shim = "#ifdef __cplusplus\nextern \"C\" {\n#endif\n#include <lauxlib.h>\n#include <lua.h>\n#include <lualib.h>\n#ifdef __cplusplus\n}\n#endif\n#include <signal.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#if LUA_VERSION_NUM == 501\n #define LUA_OK 0\n#endif\n\n/* Copied from lua.c */\n\nstatic lua_State *globalL = NULL;\n\nstatic void lstop (lua_State *L, lua_Debug *ar) {\n (void)ar; /* unused arg. */\n lua_sethook(L, NULL, 0, 0); /* reset hook */\n luaL_error(L, \"interrupted!\");\n}\n\nstatic void laction (int i) {\n signal(i, SIG_DFL); /* if another SIGINT happens, terminate process */\n lua_sethook(globalL, lstop, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1);\n}\n\nstatic void createargtable (lua_State *L, char **argv, int argc, int script) {\n int i, narg;\n if (script == argc) script = 0; /* no script name? */\n narg = argc - (script + 1); /* number of positive indices */\n lua_createtable(L, narg, script + 1);\n for (i = 0; i < argc; i++) {\n lua_pushstring(L, argv[i]);\n lua_rawseti(L, -2, i - script);\n }\n lua_setglobal(L, \"arg\");\n}\n\nstatic int msghandler (lua_State *L) {\n const char *msg = lua_tostring(L, 1);\n if (msg == NULL) { /* is error object not a string? */\n if (luaL_callmeta(L, 1, \"__tostring\") && /* does it have a metamethod */\n lua_type(L, -1) == LUA_TSTRING) /* that produces a string? */\n return 1; /* that is the message */\n else\n msg = lua_pushfstring(L, \"(error object is a %%s value)\",\n luaL_typename(L, 1));\n }\n /* Call debug.traceback() instead of luaL_traceback() for Lua 5.1 compat. */\n lua_getglobal(L, \"debug\");\n lua_getfield(L, -1, \"traceback\");\n /* debug */\n lua_remove(L, -2);\n lua_pushstring(L, msg);\n /* original msg */\n lua_remove(L, -3);\n lua_pushinteger(L, 2); /* skip this function and traceback */\n lua_call(L, 2, 1); /* call debug.traceback */\n return 1; /* return the traceback */\n}\n\nstatic int docall (lua_State *L, int narg, int nres) {\n int status;\n int base = lua_gettop(L) - narg; /* function index */\n lua_pushcfunction(L, msghandler); /* push message handler */\n lua_insert(L, base); /* put it under function and args */\n globalL = L; /* to be available to 'laction' */\n signal(SIGINT, laction); /* set C-signal handler */\n status = lua_pcall(L, narg, nres, base);\n signal(SIGINT, SIG_DFL); /* reset C-signal handler */\n lua_remove(L, base); /* remove message handler from the stack */\n return status;\n}\n\nint main(int argc, char *argv[]) {\n lua_State *L = luaL_newstate();\n luaL_openlibs(L);\n createargtable(L, argv, argc, 0);\n\n static const unsigned char lua_loader_program[] = {\n%s\n};\n if(luaL_loadbuffer(L, (const char*)lua_loader_program,\n sizeof(lua_loader_program), \"%s\") != LUA_OK) {\n fprintf(stderr, \"luaL_loadbuffer: %%s\\n\", lua_tostring(L, -1));\n lua_close(L);\n return 1;\n }\n\n /* lua_bundle */\n lua_newtable(L);\n static const unsigned char lua_require_1[] = {\n %s\n };\n lua_pushlstring(L, (const char*)lua_require_1, sizeof(lua_require_1));\n lua_setfield(L, -2, \"%s\");\n\n%s\n\n if (docall(L, 1, LUA_MULTRET)) {\n const char *errmsg = lua_tostring(L, 1);\n if (errmsg) {\n fprintf(stderr, \"%%s\\n\", errmsg);\n }\n lua_close(L);\n return 1;\n }\n lua_close(L);\n return 0;\n}"
local function compile_fennel(filename, options)
local f = nil
if (filename == "-") then
f = io.stdin
else
f = assert(io.open(filename, "rb"))
end
local lua_code = fennel["compile-string"](f:read("*a"), options)
f:close()
return lua_code
end
local function module_name(open, rename, used_renames)
local require_name = nil
do
local _767_0 = rename[open]
if (nil ~= _767_0) then
local renamed = _767_0
used_renames[open] = true
require_name = renamed
else
local _ = _767_0
require_name = open
end
end
return (require_name:sub(1, 1) .. require_name:sub(2):gsub("_", "."))
end
local function native_loader(native, _3foptions)
local opts = (_3foptions or {["rename-modules"] = {}})
local rename = (opts["rename-modules"] or {})
local used_renames = {}
local nm = (os.getenv("NM") or "nm")
local out = {" /* native libraries */"}
for _, path in ipairs(native) do
local opens = {}
for open in shellout((nm .. " " .. path)):gmatch("[^dDt] _?luaopen_([%a%p%d]+)") do
table.insert(opens, open)
end
if (0 == #opens) then
warn((("Native module %s did not contain any luaopen_* symbols. " .. "Did you mean to use --native-library instead of --native-module?")):format(path))
end
for _0, open in ipairs(opens) do
table.insert(out, (" int luaopen_%s(lua_State *L);"):format(open))
table.insert(out, (" lua_pushcfunction(L, luaopen_%s);"):format(open))
table.insert(out, (" lua_setfield(L, -2, \"%s\");\n"):format(module_name(open, rename, used_renames)))
end
end
for key, val in pairs(rename) do
if not used_renames[key] then
warn((("unused --rename-native-module %s %s argument. " .. "Did you mean to include a native module?")):format(key, val))
end
end
return table.concat(out, "\n")
end
local function fennel__3ec(filename, native, options)
local basename = filename:gsub("(.*[\\/])(.*)", "%2")
local basename_noextension = (basename:match("(.+)%.") or basename)
local dotpath = filename:gsub("^%.%/", ""):gsub("[\\/]", ".")
local dotpath_noextension = (dotpath:match("(.+)%.") or dotpath)
local fennel_loader = nil
local _771_
do
_771_ = "(do (local bundle_2_ ...) (fn loader_3_ [name_4_] (match (or (. bundle_2_ name_4_) (. bundle_2_ (.. name_4_ \".init\"))) (mod_5_ ? (= \"function\" (type mod_5_))) mod_5_ (mod_5_ ? (= \"string\" (type mod_5_))) (assert (if (= _VERSION \"Lua 5.1\") (loadstring mod_5_ name_4_) (load mod_5_ name_4_))) nil (values nil (: \"\n\\tmodule '%%s' not found in fennel bundle\" \"format\" name_4_)))) (table.insert (or package.loaders package.searchers) 2 loader_3_) ((assert (loader_3_ \"%s\")) ((or unpack table.unpack) arg)))"
end
fennel_loader = _771_:format(dotpath_noextension)
local lua_loader = fennel["compile-string"](fennel_loader)
local _772_ = options
local rename_modules = _772_["rename-modules"]
return c_shim:format(string__3ec_hex_literal(lua_loader), basename_noextension, string__3ec_hex_literal(compile_fennel(filename, options)), dotpath_noextension, native_loader(native, {["rename-modules"] = rename_modules}))
end
local function write_c(filename, native, options)
local out_filename = (filename .. "_binary.c")
local f = assert(io.open(out_filename, "w+"))
f:write(fennel__3ec(filename, native, options))
f:close()
return out_filename
end
local function compile_binary(lua_c_path, executable_name, static_lua, lua_include_dir, native)
local cc = (os.getenv("CC") or "cc")
local rdynamic, bin_extension, ldl_3f = nil, nil, nil
local _774_
do
local _773_0 = shellout((cc .. " -dumpmachine"))
if (nil ~= _773_0) then
_774_ = _773_0:match("mingw")
else
_774_ = _773_0
end
end
if _774_ then
rdynamic, bin_extension, ldl_3f = "", ".exe", false
else
rdynamic, bin_extension, ldl_3f = "-rdynamic", "", true
end
local compile_command = nil
local _777_
if ldl_3f then
_777_ = "-ldl"
else
_777_ = ""
end
compile_command = {cc, "-Os", lua_c_path, table.concat(native, " "), static_lua, rdynamic, "-lm", _777_, "-o", (executable_name .. bin_extension), "-I", lua_include_dir, os.getenv("CC_OPTS")}
if os.getenv("FENNEL_DEBUG") then
print("Compiling with", table.concat(compile_command, " "))
end
if not execute(table.concat(compile_command, " ")) then
print("failed:", table.concat(compile_command, " "))
os.exit(1)
end
if not os.getenv("FENNEL_DEBUG") then
os.remove(lua_c_path)
end
return os.exit(0)
end
local function native_path_3f(path)
local extension, version_extension = path:match("%.(%a+)(%.?%d*)$")
if (version_extension and (version_extension ~= "") and not version_extension:match("%.%d+")) then
return false
else
local _782_0 = extension
if (_782_0 == "a") then
return path
elseif (_782_0 == "o") then
return path
elseif (_782_0 == "so") then
return path
elseif (_782_0 == "dylib") then
return path
else
local _ = _782_0
return false
end
end
end
local function extract_native_args(args)
local native = {["rename-modules"] = {}, libraries = {}, modules = {}}
for i = #args, 1, -1 do
if ("--native-module" == args[i]) then
local path = assert(native_path_3f(table.remove(args, (i + 1))))
table.insert(native.modules, 1, path)
table.insert(native.libraries, 1, path)
table.remove(args, i)
end
if ("--native-library" == args[i]) then
table.insert(native.libraries, 1, assert(native_path_3f(table.remove(args, (i + 1)))))
table.remove(args, i)
end
if ("--rename-native-module" == args[i]) then
local original = table.remove(args, (i + 1))
local new = table.remove(args, (i + 1))
native["rename-modules"][original] = new
table.remove(args, i)
end
end
if (0 < #args) then
print(table.concat(args, " "))
error(("Unknown args: " .. table.concat(args, " ")))
end
return native
end
local function compile(filename, executable_name, static_lua, lua_include_dir, options, args)
local _789_ = extract_native_args(args)
local libraries = _789_["libraries"]
local modules = _789_["modules"]
local rename_modules = _789_["rename-modules"]
local opts = {["rename-modules"] = rename_modules}
copy(options, opts)
return compile_binary(write_c(filename, modules, opts), executable_name, static_lua, lua_include_dir, libraries)
end
local help = "\nUsage: %s --compile-binary FILE OUT STATIC_LUA_LIB LUA_INCLUDE_DIR\n\nCompile a binary from your Fennel program.\n\nRequires a C compiler, a copy of liblua, and Lua's dev headers. Implies\nthe --require-as-include option.\n\n FILE: the Fennel source being compiled.\n OUT: the name of the executable to generate\n STATIC_LUA_LIB: the path to the Lua library to use in the executable\n LUA_INCLUDE_DIR: the path to the directory of Lua C header files\n\nFor example, on a Debian system, to compile a file called program.fnl using\nLua 5.3, you would use this:\n\n $ %s --compile-binary program.fnl program \\\n /usr/lib/x86_64-linux-gnu/liblua5.3.a /usr/include/lua5.3\n\nThe program will be compiled to Lua, then compiled to C, then compiled to\nmachine code. You can set the CC environment variable to change the compiler\nused (default: cc) or set CC_OPTS to pass in compiler options. For example\nset CC_OPTS=-static to generate a binary with static linking.\n\nThis method is currently limited to programs do not transitively require Lua\nmodules. Requiring a Lua module directly will work, but requiring a Lua module\nwhich requires another will fail.\n\nTo include C libraries that contain Lua modules, add --native-module path/to.so,\nand to include C libraries without modules, use --native-library path/to.so.\nThese options are unstable, barely tested, and even more likely to break.\n\nIf you need to change the require name that a given native module is referenced\nas, you can use the --rename-native-module ORIGINAL NEW. ORIGINAL should be the\nsuffix of the luaopen_* symbol in the native module. NEW should be the string\nyou wish to pass to require to require the given native module. This can be used\nto handle cases where the name of an object file does not match the name of the\nluaopen_* symbol(s) within it. For example, the Lua readline bindings include a\nreadline.lua file which is usually required as \"readline\", and a C-readline.so\nfile which is required in the Lua half of the bindings like so:\n\n require 'C-readline'\n\nHowever, the symbol within the C-readline.so file is named luaopen_readline, so\nby default --compile-binary will make it so you can require it as \"readline\",\nwhich collides with the name of the readline.lua file and doesn't match the\nrequire call within readline.lua. In order to include the module within your\ncompiled binary and have it get picked up by readline.lua correctly, you can\nspecify the name used to refer to it in a require call by compiling it like\nso (this is assuming that program.fnl requires the Lua bindings):\n\n $ %s --compile-binary program.fnl program \\\n /usr/lib/x86_64-linux-gnu/liblua5.3.a /usr/include/lua5.3 \\\n --native-module C-readline.so \\\n --rename-native-module readline C-readline\n"
return {compile = compile, help = help}
end
local fennel = nil
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 view = require("fennel.view")
local unpack = (table.unpack or _G.unpack)
local function default_read_chunk(parser_state)
local function _601_()
if (0 < parser_state["stack-size"]) then
return ".."
else
return ">> "
end
end
io.write(_601_())
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 _603_()
local _602_0 = errtype
if (_602_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 (_602_0 == "Runtime") then
return (compiler.traceback(tostring(err), 4) .. "\n")
else
local _ = _602_0
return ("%s error: %s\n"):format(errtype, tostring(err))
end
end
return io.write(_603_())
end
local function splice_save_locals(env, lua_source, scope)
local saves = nil
do
local tbl_17_ = {}
local i_18_ = #tbl_17_
for name in pairs(env.___replLocals___) do
local val_19_ = ("local %s = ___replLocals___['%s']"):format(scope.manglings[name], name)
if (nil ~= val_19_) then
i_18_ = (i_18_ + 1)
tbl_17_[i_18_] = val_19_
end
end
saves = tbl_17_
end
local binds = nil
do
local tbl_17_ = {}
local i_18_ = #tbl_17_
for raw, name in pairs(scope.manglings) do
local val_19_ = nil
if not scope.gensyms[name] then
val_19_ = ("___replLocals___['%s'] = %s"):format(raw, name)
else
val_19_ = nil
end
if (nil ~= val_19_) then
i_18_ = (i_18_ + 1)
tbl_17_[i_18_] = val_19_
end
end
binds = tbl_17_
end
local gap = nil
if lua_source:find("\n") then
gap = "\n"
else
gap = " "
end
local function _609_()
if next(saves) then
return (table.concat(saves, " ") .. gap)
else
return ""
end
end
local function _612_()
local _610_0, _611_0 = lua_source:match("^(.*)[\n ](return .*)$")
if ((nil ~= _610_0) and (nil ~= _611_0)) then
local body = _610_0
local _return = _611_0
return (body .. gap .. table.concat(binds, " ") .. gap .. _return)
else
local _ = _610_0
return lua_source
end
end
return (_609_() .. _612_())
end
local function completer(env, scope, text)
local max_items = 2000
local seen = {}
local matches = {}
local input_fragment = text:gsub(".*[%s)(]+", "")
local stop_looking_3f = false
local function add_partials(input, tbl, prefix)
local scope_first_3f = ((tbl == env) or (tbl == env.___replLocals___))
local tbl_17_ = matches
local i_18_ = #tbl_17_
local function _614_()
if scope_first_3f then
return scope.manglings
else
return tbl
end
end
for k, is_mangled in utils.allpairs(_614_()) do
if (max_items <= #matches) then break end
local val_19_ = nil
do
local lookup_k = nil
if scope_first_3f then
lookup_k = is_mangled
else
lookup_k = k
end
if ((type(k) == "string") and (input == k:sub(0, #input)) and not seen[k] and ((":" ~= prefix:sub(-1)) or ("function" == type(tbl[lookup_k])))) then
seen[k] = true
val_19_ = (prefix .. k)
else
val_19_ = nil
end
end
if (nil ~= val_19_) then
i_18_ = (i_18_ + 1)
tbl_17_[i_18_] = val_19_
end
end
return tbl_17_
end
local function descend(input, tbl, prefix, add_matches, method_3f)
local splitter = nil
if method_3f then
splitter = "^([^:]+):(.*)"
else
splitter = "^([^.]+)%.(.*)"
end
local head, tail = input:match(splitter)
local raw_head = (scope.manglings[head] or head)
if (type(tbl[raw_head]) == "table") then
stop_looking_3f = true
if method_3f then
return add_partials(tail, tbl[raw_head], (prefix .. head .. ":"))
else
return add_matches(tail, tbl[raw_head], (prefix .. head))
end
end
end
local function add_matches(input, tbl, prefix)
local prefix0 = nil
if prefix then
prefix0 = (prefix .. ".")
else
prefix0 = ""
end
if (not input:find("%.") and input:find(":")) then
return descend(input, tbl, prefix0, add_matches, true)
elseif not input:find("%.") then
return add_partials(input, tbl, prefix0)
else
return descend(input, tbl, prefix0, add_matches, false)
end
end
for _, source in ipairs({scope.specials, scope.macros, (env.___replLocals___ or {}), env, env._G}) do
if stop_looking_3f then break end
add_matches(input_fragment, source)
end
return matches
end
local commands = {}
local function command_3f(input)
return input:match("^%s*,")
end
local function command_docs()
local _623_
do
local tbl_17_ = {}
local i_18_ = #tbl_17_
for name, f in pairs(commands) do
local val_19_ = (" ,%s - %s"):format(name, ((compiler.metadata):get(f, "fnl/docstring") or "undocumented"))
if (nil ~= val_19_) then
i_18_ = (i_18_ + 1)
tbl_17_[i_18_] = val_19_
end
end
_623_ = tbl_17_
end
return table.concat(_623_, "\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 _625_0, _626_0 = pcall(specials["load-code"]("return require(...)", env), module_name)
if ((_625_0 == true) and (nil ~= _626_0)) then
local old = _626_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
specials["macro-loaded"][module_name] = nil
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 ((_625_0 == false) and (nil ~= _626_0)) then
local msg = _626_0
if msg:match("loop or previous error loading module") then
package.loaded[module_name] = nil
return reload(module_name, env, on_values, on_error)
elseif specials["macro-loaded"][module_name] then
specials["macro-loaded"][module_name] = nil
return nil
else
local function _631_()
local _630_0 = msg:gsub("\n.*", "")
return _630_0
end
return on_error("Runtime", _631_())
end
end
end
local function run_command(read, on_error, f)
local _634_0, _635_0, _636_0 = pcall(read)
if ((_634_0 == true) and (_635_0 == true) and (nil ~= _636_0)) then
local val = _636_0
local _637_0, _638_0 = pcall(f, val)
if ((_637_0 == false) and (nil ~= _638_0)) then
local msg = _638_0
return on_error("Runtime", msg)
end
elseif (_634_0 == false) then
return on_error("Parse", "Couldn't parse input.")
end
end
commands.reload = function(env, read, on_values, on_error)
local function _641_(_241)
return reload(tostring(_241), env, on_values, on_error)
end
return run_command(read, on_error, _641_)
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.")
commands.complete = function(env, read, on_values, on_error, scope, chars)
local function _642_()
return on_values(completer(env, scope, table.concat(chars):gsub(",complete +", ""):sub(1, -2)))
end
return run_command(read, on_error, _642_)
end
do end (compiler.metadata):set(commands.complete, "fnl/docstring", "Print all possible completions for a given input symbol.")
local function apropos_2a(pattern, tbl, prefix, seen, names)
for name, subtbl in pairs(tbl) do
if (("string" == type(name)) and (package ~= subtbl)) then
local _643_0 = type(subtbl)
if (_643_0 == "function") then
if ((prefix .. name)):match(pattern) then
table.insert(names, (prefix .. name))
end
elseif (_643_0 == "table") then
if not seen[subtbl] then
local _645_
do
seen[subtbl] = true
_645_ = seen
end
apropos_2a(pattern, subtbl, (prefix .. name:gsub("%.", "/") .. "."), _645_, names)
end
end
end
end
return names
end
local function apropos(pattern)
local names = apropos_2a(pattern, package.loaded, "", {}, {})
local tbl_17_ = {}
local i_18_ = #tbl_17_
for _, name in ipairs(names) do
local val_19_ = name:gsub("^_G%.", "")
if (nil ~= val_19_) then
i_18_ = (i_18_ + 1)
tbl_17_[i_18_] = val_19_
end
end
return tbl_17_
end
commands.apropos = function(_env, read, on_values, on_error, _scope)
local function _650_(_241)
return on_values(apropos(tostring(_241)))
end
return run_command(read, on_error, _650_)
end
do end (compiler.metadata):set(commands.apropos, "fnl/docstring", "Print all functions matching a pattern in all loaded modules.")
local function apropos_follow_path(path)
local paths = nil
do
local tbl_17_ = {}
local i_18_ = #tbl_17_
for p in path:gmatch("[^%.]+") do
local val_19_ = p
if (nil ~= val_19_) then
i_18_ = (i_18_ + 1)
tbl_17_[i_18_] = val_19_
end
end
paths = tbl_17_
end
local tgt = package.loaded
for _, path0 in ipairs(paths) do
if (nil == tgt) then break end
local _653_
do
local _652_0 = path0:gsub("%/", ".")
_653_ = _652_0
end
tgt = tgt[_653_]
end
return tgt
end
local function apropos_doc(pattern)
local tbl_17_ = {}
local i_18_ = #tbl_17_
for _, path in ipairs(apropos(".*")) do
local val_19_ = nil
do
local tgt = apropos_follow_path(path)
if ("function" == type(tgt)) then
local _654_0 = (compiler.metadata):get(tgt, "fnl/docstring")
if (nil ~= _654_0) then
local docstr = _654_0
val_19_ = (docstr:match(pattern) and path)
else
val_19_ = nil
end
else
val_19_ = nil
end
end
if (nil ~= val_19_) then
i_18_ = (i_18_ + 1)
tbl_17_[i_18_] = val_19_
end
end
return tbl_17_
end
commands["apropos-doc"] = function(_env, read, on_values, on_error, _scope)
local function _658_(_241)
return on_values(apropos_doc(tostring(_241)))
end
return run_command(read, on_error, _658_)
end
do end (compiler.metadata):set(commands["apropos-doc"], "fnl/docstring", "Print all functions that match the pattern in their docs")
local function apropos_show_docs(on_values, pattern)
for _, path in ipairs(apropos(pattern)) do
local tgt = apropos_follow_path(path)
if (("function" == type(tgt)) and (compiler.metadata):get(tgt, "fnl/docstring")) then
on_values(specials.doc(tgt, path))
on_values()
end
end
return nil
end
commands["apropos-show-docs"] = function(_env, read, on_values, on_error)
local function _660_(_241)
return apropos_show_docs(on_values, tostring(_241))
end
return run_command(read, on_error, _660_)
end
do end (compiler.metadata):set(commands["apropos-show-docs"], "fnl/docstring", "Print all documentations matching a pattern in function name")
local function resolve(identifier, _661_0, scope)
local _662_ = _661_0
local env = _662_
local ___replLocals___ = _662_["___replLocals___"]
local e = nil
local function _663_(_241, _242)
return (___replLocals___[scope.unmanglings[_242]] or env[_242])
end
e = setmetatable({}, {__index = _663_})
local function _664_(...)
local _665_0, _666_0 = ...
if ((_665_0 == true) and (nil ~= _666_0)) then
local code = _666_0
local function _667_(...)
local _668_0, _669_0 = ...
if ((_668_0 == true) and (nil ~= _669_0)) then
local val = _669_0
return val
else
local _ = _668_0
return nil
end
end
return _667_(pcall(specials["load-code"](code, e)))
else
local _ = _665_0
return nil
end
end
return _664_(pcall(compiler["compile-string"], tostring(identifier), {scope = scope}))
end
commands.find = function(env, read, on_values, on_error, scope)
local function _672_(_241)
local _673_0 = nil
do
local _674_0 = utils["sym?"](_241)
if (nil ~= _674_0) then
local _675_0 = resolve(_674_0, env, scope)
if (nil ~= _675_0) then
_673_0 = debug.getinfo(_675_0)
else
_673_0 = _675_0
end
else
_673_0 = _674_0
end
end
if ((_G.type(_673_0) == "table") and (nil ~= _673_0.linedefined) and (nil ~= _673_0.short_src) and (nil ~= _673_0.source) and (_673_0.what == "Lua")) then
local line = _673_0.linedefined
local src = _673_0.short_src
local source = _673_0.source
local fnlsrc = nil
do
local _678_0 = compiler.sourcemap
if (nil ~= _678_0) then
_678_0 = _678_0[source]
end
if (nil ~= _678_0) then
_678_0 = _678_0[line]
end
if (nil ~= _678_0) then
_678_0 = _678_0[2]
end
fnlsrc = _678_0
end
return on_values({string.format("%s:%s", src, (fnlsrc or line))})
elseif (_673_0 == nil) then
return on_error("Repl", "Unknown value")
else
local _ = _673_0
return on_error("Repl", "No source info")
end
end
return run_command(read, on_error, _672_)
end
do end (compiler.metadata):set(commands.find, "fnl/docstring", "Print the filename and line number for a given function")
commands.doc = function(env, read, on_values, on_error, scope)
local function _683_(_241)
local name = tostring(_241)
local path = (utils["multi-sym?"](name) or {name})
local ok_3f, target = nil, nil
local function _684_()
return (utils["get-in"](scope.specials, path) or utils["get-in"](scope.macros, path) or resolve(name, env, scope))
end
ok_3f, target = pcall(_684_)
if ok_3f then
return on_values({specials.doc(target, name)})
else
return on_error("Repl", ("Could not find " .. name .. " for docs."))
end
end
return run_command(read, on_error, _683_)
end
do end (compiler.metadata):set(commands.doc, "fnl/docstring", "Print the docstring and arglist for a function, macro, or special form.")
commands.compile = function(env, read, on_values, on_error, scope)
local function _686_(_241)
local allowedGlobals = specials["current-global-names"](env)
local ok_3f, result = pcall(compiler.compile, _241, {allowedGlobals = allowedGlobals, env = env, scope = scope})
if ok_3f then
return on_values({result})
else
return on_error("Repl", ("Error compiling expression: " .. result))
end
end
return run_command(read, on_error, _686_)
end
do end (compiler.metadata):set(commands.compile, "fnl/docstring", "compiles the expression into lua and prints the result.")
local function load_plugin_commands(plugins)
for _, plugin in ipairs((plugins or {})) do
for name, f in pairs(plugin) do
local _688_0 = name:match("^repl%-command%-(.*)")
if (nil ~= _688_0) then
local cmd_name = _688_0
commands[cmd_name] = (commands[cmd_name] or f)
end
end
end
return nil
end
local function run_command_loop(input, read, loop, env, on_values, on_error, scope, chars)
local command_name = input:match(",([^%s/]+)")
do
local _690_0 = commands[command_name]
if (nil ~= _690_0) then
local command = _690_0
command(env, read, on_values, on_error, scope, chars)
else
local _ = _690_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 try_readline_21(opts, ok, readline)
if ok then
if readline.set_readline_name then
readline.set_readline_name("fennel")
end
readline.set_options({histfile = "", keeplines = 1000})
opts.readChunk = function(parser_state)
local prompt = nil
if (0 < parser_state["stack-size"]) then
prompt = ".. "
else
prompt = ">> "
end
local str = readline.readline(prompt)
if str then
return (str .. "\n")
end
end
local completer0 = nil
opts.registerCompleter = function(repl_completer)
completer0 = repl_completer
return nil
end
local function repl_completer(text, from, to)
if completer0 then
readline.set_completion_append_character("")
return completer0(text:sub(from, to))
else
return {}
end
end
readline.set_complete_function(repl_completer)
return readline
end
end
local function should_use_readline_3f(opts)
return (("dumb" ~= os.getenv("TERM")) and not opts.readChunk and not opts.registerCompleter)
end
local function repl(_3foptions)
local old_root_options = utils.root.options
local _699_ = utils.copy(_3foptions)
local opts = _699_
local _3ffennelrc = _699_["fennelrc"]
local _ = nil
opts.fennelrc = nil
_ = nil
local readline = (should_use_readline_3f(opts) and try_readline_21(opts, pcall(require, "readline")))
local _0 = nil
if _3ffennelrc then
_0 = _3ffennelrc()
else
_0 = nil
end
local env = specials["wrap-env"]((opts.env or rawget(_G, "_ENV") or _G))
local callbacks = {env = env, onError = (opts.onError or default_on_error), onValues = (opts.onValues or default_on_values), pp = (opts.pp or view), readChunk = (opts.readChunk or default_read_chunk)}
local save_locals_3f = (opts.saveLocals ~= false)
local byte_stream, clear_stream = nil, nil
local function _701_(_241)
return callbacks.readChunk(_241)
end
byte_stream, clear_stream = parser.granulate(_701_)
local chars = {}
local read, reset = nil, nil
local function _702_(parser_state)
local b = byte_stream(parser_state)
if b then
table.insert(chars, string.char(b))
end
return b
end
read, reset = parser.parser(_702_)
env.___repl___ = callbacks
opts.env, opts.scope = env, compiler["make-scope"]()
opts.useMetadata = (opts.useMetadata ~= false)
if (opts.allowedGlobals == nil) then
opts.allowedGlobals = specials["current-global-names"](env)
end
if opts.registerCompleter then
local function _706_()
local _705_0 = opts.scope
local function _707_(...)
return completer(env, _705_0, ...)
end
return _707_
end
opts.registerCompleter(_706_())
end
load_plugin_commands(opts.plugins)
if save_locals_3f then
local function newindex(t, k, v)
if opts.scope.manglings[k] then
return rawset(t, k, v)
end
end
env.___replLocals___ = setmetatable({}, {__newindex = newindex})
end
local function print_values(...)
local vals = {...}
local out = {}
local pp = callbacks.pp
env._, env.__ = vals[1], vals
for i = 1, select("#", ...) do
table.insert(out, pp(vals[i]))
end
return callbacks.onValues(out)
end
local function loop()
for k in pairs(chars) do
chars[k] = nil
end
reset()
local ok, parser_not_eof_3f, x = pcall(read)
local src_string = table.concat(chars)
local readline_not_eof_3f = (not readline or (src_string ~= "(null)"))
local not_eof_3f = (readline_not_eof_3f and parser_not_eof_3f)
if not ok then
callbacks.onError("Parse", not_eof_3f)
clear_stream()
return loop()
elseif command_3f(src_string) then
return run_command_loop(src_string, read, loop, env, callbacks.onValues, callbacks.onError, opts.scope, chars)
else
if not_eof_3f then
do
local _711_0, _712_0 = nil, nil
local function _713_()
opts["source"] = src_string
return opts
end
_711_0, _712_0 = pcall(compiler.compile, x, _713_())
if ((_711_0 == false) and (nil ~= _712_0)) then
local msg = _712_0
clear_stream()
callbacks.onError("Compile", msg)
elseif ((_711_0 == true) and (nil ~= _712_0)) then
local src = _712_0
local src0 = nil
if save_locals_3f then
src0 = splice_save_locals(env, src, opts.scope)
else
src0 = src
end
local _715_0, _716_0 = pcall(specials["load-code"], src0, env)
if ((_715_0 == false) and (nil ~= _716_0)) then
local msg = _716_0
clear_stream()
callbacks.onError("Lua Compile", msg, src0)
elseif (true and (nil ~= _716_0)) then
local _1 = _715_0
local chunk = _716_0
local function _717_()
return print_values(chunk())
end
local function _718_(...)
return callbacks.onError("Runtime", ...)
end
xpcall(_717_, _718_)
end
end
end
utils.root.options = old_root_options
return loop()
end
end
end
loop()
if readline then
return readline.save_history()
end
end
return repl
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 _415_(_, key)
if utils["string?"](key) then
return env[compiler["global-unmangling"](key)]
else
return env[key]
end
end
local function _417_(_, key, value)
if utils["string?"](key) then
env[compiler["global-unmangling"](key)] = value
return nil
else
env[key] = value
return nil
end
end
local function _419_()
local function putenv(k, v)
local _420_
if utils["string?"](k) then
_420_ = compiler["global-unmangling"](k)
else
_420_ = k
end
return _420_, v
end
return next, utils.kvmap(env, putenv), nil
end
return setmetatable({}, {__index = _415_, __newindex = _417_, __pairs = _419_})
end
local function current_global_names(_3fenv)
local mt = nil
do
local _422_0 = getmetatable(_3fenv)
if ((_G.type(_422_0) == "table") and (nil ~= _422_0.__pairs)) then
local mtpairs = _422_0.__pairs
local tbl_14_ = {}
for k, v in mtpairs(_3fenv) do
local k_15_, v_16_ = k, v
if ((k_15_ ~= nil) and (v_16_ ~= nil)) then
tbl_14_[k_15_] = v_16_
end
end
mt = tbl_14_
elseif (_422_0 == nil) then
mt = (_3fenv or _G)
else
mt = nil
end
end
return (mt and utils.kvmap(mt, compiler["global-unmangling"]))
end
local function load_code(code, _3fenv, _3ffilename)
local env = (_3fenv or rawget(_G, "_ENV") or _G)
local _425_0, _426_0 = rawget(_G, "setfenv"), rawget(_G, "loadstring")
if ((nil ~= _425_0) and (nil ~= _426_0)) then
local setfenv = _425_0
local loadstring = _426_0
local f = assert(loadstring(code, _3ffilename))
setfenv(f, env)
return f
else
local _ = _425_0
return assert(load(code, _3ffilename, "t", env))
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 _428_
if (0 < #arglist) then
_428_ = " "
else
_428_ = ""
end
return string.format("(%s%s%s)\n %s", name, _428_, 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