/
tl
executable file
·1415 lines (1219 loc) · 43.5 KB
/
tl
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
-- Little trick for running development versions:
-- when tl.lua and tl are in the same folder, prefer that tl.lua
local tl
do
local script_path = debug.getinfo(1, "S").source:match("^@?(.*[/\\])") or "."
local save_package_path = package.path
package.path = script_path .. "/?.lua;" .. package.path
tl = require("tl")
-- but otherwise don't pollute package.path inadvertedly
package.path = save_package_path
end
local argparse = require("argparse")
--------------------------------------------------------------------------------
-- Utilities
--------------------------------------------------------------------------------
local PATH_SEPARATOR = package.config:sub(1, 1)
local turbo
local is_turbo_on
do
local tl_lex = tl.lex
local turbo_is_on = false
turbo = function(on)
if on then
if jit then
jit.off()
tl.lex = function(input, filename)
jit.on()
local r1, r2 = tl_lex(input, filename)
jit.off()
return r1, r2
end
end
collectgarbage("stop")
else
if jit then
jit.on()
tl.lex = tl_lex
end
collectgarbage("restart")
end
turbo_is_on = on
end
is_turbo_on = function()
return turbo_is_on
end
end
local function check_collect(i)
if i % 50 == 0 then
collectgarbage()
end
end
local function printerr(s)
io.stderr:write(s .. "\n")
end
local function die(msg)
printerr(msg)
os.exit(1)
end
local function find_in_sequence(seq, value)
for _, v in ipairs(seq) do
if v == value then
return true
end
end
return false
end
local function keys(t)
local ks = {}
local n = 0
for k, _ in pairs(t) do
n = n + 1
ks[n] = k
end
table.sort(ks)
return ks, n
end
local function prepend_to_lua_paths(directory)
local path_str = directory
local shared_library_ext = package.cpath:match("%.(%w+)%s*$") or "so"
if string.sub(path_str, -1) == PATH_SEPARATOR then
path_str = path_str:sub(1, -2)
end
path_str = path_str .. PATH_SEPARATOR
local lib_path_str = path_str .. "?." .. shared_library_ext .. ";"
local lua_path_str = path_str .. "?.lua;" .. path_str .. "?/init.lua;"
package.path = lua_path_str .. package.path
package.cpath = lib_path_str .. package.cpath
end
local function find_file_in_parent_dirs(fname)
for _ = 1, 20 do
local fd = io.open(fname, "rb")
if fd then
fd:close()
return fname
end
fname = ".." .. PATH_SEPARATOR .. fname
end
end
--------------------------------------------------------------------------------
-- Common driver backend
--------------------------------------------------------------------------------
local function setup_env(tlconfig, filename)
local _, extension = filename:match("(.*)%.([a-z]+)$")
extension = extension and extension:lower()
local lax_mode
if extension == "tl" then
lax_mode = false
elseif extension == "lua" then
lax_mode = true
else
-- if we can't decide based on the file extension, default to strict mode
lax_mode = false
end
local gen_compat = tlconfig["gen_compat"]
local gen_target = tlconfig["gen_target"]
tlconfig._init_env_modules = tlconfig._init_env_modules or {}
if tlconfig.global_env_def then
table.insert(tlconfig._init_env_modules, 1, tlconfig.global_env_def)
end
local env, err = tl.init_env(lax_mode, gen_compat, gen_target, tlconfig._init_env_modules)
if not env then
die(err)
end
return env
end
local function filter_warnings(tlconfig, result)
if not result.warnings then
return
end
for i = #result.warnings, 1, -1 do
local w = result.warnings[i]
if tlconfig._disabled_warnings_set[w.tag] then
table.remove(result.warnings, i)
elseif tlconfig._warning_errors_set[w.tag] then
local err = table.remove(result.warnings, i)
table.insert(result.type_errors, err)
end
end
end
local report_all_errors
do
local function report_errors(category, errors)
if not errors then
return false
end
if #errors > 0 then
local n = #errors
printerr("========================================")
printerr(n .. " " .. category .. (n ~= 1 and "s" or "") .. ":")
for _, err in ipairs(errors) do
printerr(err.filename .. ":" .. err.y .. ":" .. err.x .. ": " .. (err.msg or ""))
end
return true
end
return false
end
report_all_errors = function(tlconfig, env, syntax_only)
local any_syntax_err, any_type_err, any_warning
for _, name in ipairs(env.loaded_order) do
local result = env.loaded[name]
local syntax_err = report_errors("syntax error", result.syntax_errors)
if syntax_err then
any_syntax_err = true
elseif not syntax_only then
filter_warnings(tlconfig, result)
any_warning = report_errors("warning", result.warnings) or any_warning
any_type_err = report_errors("error", result.type_errors) or any_type_err
end
end
local ok = not (any_syntax_err or any_type_err)
return ok, any_syntax_err, any_type_err, any_warning
end
end
local function type_check_and_load(tlconfig, filename)
local env = setup_env(tlconfig, filename)
local result, err = tl.process(filename, env)
if err then
die(err)
end
local is_tl = filename:match("%.tl$")
local _, syntax_err, type_err = report_all_errors(tlconfig, env, not is_tl)
if syntax_err then
os.exit(1)
end
if is_tl and type_err then
os.exit(1)
end
local chunk; chunk, err = (loadstring or load)(tl.pretty_print_ast(result.ast, tlconfig.gen_target), "@" .. filename)
if err then
die("Internal Compiler Error: Teal generator produced invalid Lua. " ..
"Please report a bug at https://github.com/teal-language/tl\n\n" .. tostring(err))
end
return chunk
end
local function write_out(tlconfig, result, output_file, pp_opts)
if tlconfig["pretend"] then
print("Would Write: " .. output_file)
return
end
local ofd, err = io.open(output_file, "wb")
if not ofd then
die("cannot write " .. output_file .. ": " .. err)
end
local _
_, err = ofd:write(tl.pretty_print_ast(result.ast, tlconfig.gen_target, pp_opts) .. "\n")
if err then
die("error writing " .. output_file .. ": " .. err)
end
ofd:close()
if not tlconfig["quiet"] then
print("Wrote: " .. output_file)
end
end
--------------------------------------------------------------------------------
-- Build system (deprecated, use Cyan)
--------------------------------------------------------------------------------
local build = {}
do
local lfs = require("lfs")
local function str_split(str, delimiter)
local idx = 0
return function()
if not idx then return end
idx = idx + 1
local prev_idx = idx
local s_idx
s_idx, idx = str:find(delimiter, idx, true)
return str:sub(prev_idx, (s_idx or 0) - 1)
end
end
--remove trailing and extra path separators, substitute './' for 'current_dir/'
local function cleanup_file_name(name)
return (name
:gsub("^(%.)(.?)", function(a, b)
assert(a == ".")
if b == "." then
die("Config error: .." .. PATH_SEPARATOR .. " not allowed, please use direct paths")
elseif b == PATH_SEPARATOR then
return ""
else
return b
end
end)
:gsub(PATH_SEPARATOR .. "+", PATH_SEPARATOR))
:gsub(PATH_SEPARATOR .. "+$", "")
end
local function path_concat(...)
local path = {}
for i = 1, select("#", ...) do
local fname = cleanup_file_name((select(i, ...)))
if #fname > 0 then
table.insert(path, fname)
end
end
return table.concat(path, PATH_SEPARATOR)
end
function build.arg_parser(parser)
parser:flag("--run-build-script", "Run the build script if needed, even when not running the build comamnd.")
local build_command = parser:command("build",
"Build your project according to tlconfig.lua by type checking and compiling each specified file.")
build_command:option("-b --build-dir", "Put all generated files in <directory>.")
:argname("<directory>")
build_command:option("-s --source-dir", "Compile all *.tl files in <directory> (and all subdirectories).")
:argname("<directory>")
end
function build.tlconfig_not_found(cmd)
if cmd == "build" then
die("Build error: tlconfig.lua not found")
end
end
function build.config_dir(cmd, config_path, config)
local config_dir = config_path:match("^(.+)" .. PATH_SEPARATOR .. "tlconfig.lua$")
if cmd == "build" and config_dir then
assert(lfs.chdir(config_dir))
end
if not config.build_file then
if lfs.attributes("./build.tl", "mode") == "file" then
config.build_file = "./build.tl"
end
else
if lfs.attributes(config.build_file, "mode") ~= "file" then
die("The configured build script is not a file")
end
end
end
function build.merge_config(tlconfig, args)
local cmd = args["command"]
if cmd == "build" then
tlconfig["source_dir"] = args["source_dir"] or tlconfig["source_dir"]
tlconfig["build_dir"] = args["build_dir"] or tlconfig["build_dir"]
end
tlconfig["run_build_script"] = tlconfig["run_build_script"] or args["run_build_script"] or cmd == "build"
if tlconfig["run_build_script"] then
if tlconfig["build_file"] and not tlconfig["build_file_output_dir"] then
print("A build file is detected, but build_file_output_dir is not set. Defaulting to ./generated_code")
tlconfig["build_file_output_dir"] = "generated_code"
end
if tlconfig["build_file"] and not tlconfig["internal_compiler_output"] then
print("A build file is detected, but there is no place configured " ..
"to store temporary compiler output. Defaulting to ./internal_compiler_output")
tlconfig["internal_compiler_output"] = "internal_compiler_output"
end
end
end
local internal_output
local build_path
function build.run_build_script(tlconfig)
if not tlconfig["run_build_script"] then
return
end
if tlconfig["internal_compiler_output"] then
internal_output = path_concat(lfs.currentdir(), tlconfig["internal_compiler_output"])
local mode = lfs.attributes(internal_output, "mode")
if not mode then
local parts = ""
local prefix = PATH_SEPARATOR == "\\" and "" or "/"
for v in string.gmatch(internal_output, "[^/]+") do
parts = parts .. prefix .. v
mode = lfs.attributes(parts, "mode")
if mode == nil then
local res, message = lfs.mkdir(parts)
if not res then
die("Could not create directory to store internal output. Error: " .. message)
end
elseif mode ~= "directory" then
die("Could not create directory to store the internal output. " ..
"Path: " .. parts .. " is not a directory")
end
end
end
end
if tlconfig["build_file"] then
build_path = path_concat(internal_output, "build_script_output")
lfs.mkdir(build_path)
prepend_to_lua_paths(build_path)
local script = {}
local chunk = type_check_and_load(tlconfig, tlconfig.build_file)
local success, res = pcall(chunk)
if success then
script = res
else
die("The build file could not be executed.")
end
local time_keeper_path = path_concat(internal_output, "last_build_script_time")
-- No need to read the file if we can just look up when it was last modified.
-- Should have about the same effect and is easier.
local last_run_time = lfs.attributes(time_keeper_path, "modification")
local last_edit_time = lfs.attributes(tlconfig.build_file, "modification")
local should_rerun = last_run_time == nil or last_run_time < last_edit_time
local gen_code = script["gen_code"]
if should_rerun and gen_code then
if type(gen_code) == "function" then
local full_path = path_concat(build_path, tlconfig["build_file_output_dir"] )
lfs.rmdir(full_path)
lfs.mkdir(full_path)
local pok, message = pcall(gen_code, full_path)
if not pok then
die("Something has gone wrong while executing the " ..
"\"gen_code\" part of the build file. Error : ".. tostring(message))
end
local file = io.open(time_keeper_path, "wb")
file:write(last_edit_time)
file:flush()
file:close()
else
die("the key \"gen_code\" exists in the build file, " ..
"but it is not a function. Value: ".. tostring(gen_code))
end
end
end
end
function build.run(tlconfig)
local function remove_leading_path(leading_part, path)
local s, e = path:find("^" .. leading_part .. PATH_SEPARATOR .. "?")
if s then
return path:sub(e+1, -1)
end
return path
end
local function traverse(dirname, emptyref, is_generated, generated_ref)
local files = {}
local paths = {} --lookup table for string paths to help
-- with pattern matching while iterating over a project
-- paths[files.foo.bar] -> "foo/bar"
emptyref = emptyref or {}
generated_ref = generated_ref or {}
for file in lfs.dir(dirname) do
if file ~= "." and file ~= ".." then
if lfs.attributes(path_concat(dirname, file), "mode") == "directory" then
local p
files[file], p = traverse(path_concat(dirname, file), emptyref, is_generated, generated_ref)
paths[files[file]] = file
for k, v in pairs(p) do
paths[k] = path_concat(file, v)
end
else
-- storing a special entry in this table to it mark as empty could
-- interfere with convoluted or maliciously constructed directory
-- names so we use a table with specific metatable to mark
-- something as the end of a traversal to have a property attached
-- to the table, without creating an entry in the table
local meta_table = {empty = emptyref}
if is_generated then
meta_table["generated"] = generated_ref
end
files[file] = setmetatable({}, meta_table)
paths[files[file]] = file
end
end
end
return files, paths, emptyref
end
local function match(patt_arr, str)
for i, v in ipairs(patt_arr) do
if v(str) then
return i
end
end
return nil
end
local inc_patterns = {}
local exc_patterns = {}
local function patt_match(patt, str)
local matches = true
local idx = 1
local s_idx
for _, v in ipairs(patt) do
s_idx, idx = str:find(v, idx)
if not s_idx then
matches = false
break
end
end
return matches
end
local function matcher(str)
local chunks = {}
for piece in str_split(str, "**" .. PATH_SEPARATOR) do
table.insert(chunks, (piece:gsub("%*", "[^" .. PATH_SEPARATOR .. "]-")))
end
chunks[1] = "^" .. chunks[1]
chunks[#chunks] = chunks[#chunks] .. "$"
return function(s)
return patt_match(chunks, s)
end
end
if internal_output then
table.insert(exc_patterns, matcher(path_concat(tlconfig["internal_compiler_output"], "**" .. PATH_SEPARATOR .. "*.*")))
end
-- prepare build and source dirs
local project = {}
-- This will probably get exposed in the api if that happens
function project:file_with_is_build(inc_patt_arr, exc_patt_arr, dirname)
local iter_dir
if dirname then
iter_dir = project:find(dirname)
else
iter_dir = self.dir
end
if not iter_dir then
return function() end
end
inc_patt_arr = inc_patt_arr or {}
exc_patt_arr = exc_patt_arr or {}
local function iter(dirs)
for fname, file in pairs(dirs) do
local path = self.paths[file]
if dirname then
path = remove_leading_path(dirname, path)
end
local meta_table = getmetatable(file)
if meta_table and meta_table.empty == self.emptyref then
local include = true
if tlconfig["files"] then
include = false
end
if build_path and meta_table.generated and meta_table.generated == self.generatedref then
coroutine.yield(build_path .. PATH_SEPARATOR .. path, true)
else
-- TODO: print out patterns that include/exclude paths to help
-- users debug tlconfig.lua (this is why match returns the array index)
if #inc_patt_arr > 0 then
local idx = match(inc_patt_arr, path)
if not idx then
include = false
end
end
if #exc_patt_arr > 0 then
local idx = match(exc_patt_arr, path)
if include and idx then
include = false
end
end
if include then
coroutine.yield(self.paths[file], false)
end
end
else
iter(file, fname)
end
end
end
return coroutine.wrap(iter), iter_dir
end
function project:find(path) -- allow for indexing with paths project:find("foo/bar") -> project.dir.foo.bar
if not path then return nil end
if path == "" then return self.dir end -- empty string is the current dir
local current_dir = self.dir
for dirname in str_split(path, PATH_SEPARATOR) do
current_dir = current_dir[dirname]
if not current_dir then
return nil
end
end
return current_dir
end
project.dir, project.paths, project.emptyref = traverse(lfs.currentdir())
local build_ref = {}
project.generatedref = build_ref
if build_path then
local build_dir, build_paths = traverse(build_path, project.emptyref, true, build_ref)
for k, v in pairs(build_dir) do
project.dir[k] = v
end
for k, v in pairs(build_paths) do
project.paths[k] = v
end
end
project.source_file_map = {}
if tlconfig["source_dir"] then
tlconfig["source_dir"] = cleanup_file_name(tlconfig["source_dir"])
local project_source = project:find(tlconfig["source_dir"])
local meta_table = getmetatable(project_source)
if not project_source then
die("Build error: source_dir '" .. tlconfig["source_dir"] .. "' doesn't exist")
elseif meta_table and meta_table.empty == project.emptyref then
die("Build error: source_dir '" .. tlconfig["source_dir"] .. "' is not a directory")
end
end
if tlconfig["build_dir"] then
tlconfig["build_dir"] = cleanup_file_name(tlconfig["build_dir"])
end
-- include/exclude pattern matching
-- create matchers for each pattern
if tlconfig["include"] then
for _, patt in ipairs(tlconfig["include"]) do
patt = cleanup_file_name(patt)
table.insert(inc_patterns, matcher(patt))
end
end
if tlconfig["exclude"] then
for _, patt in ipairs(tlconfig["exclude"]) do
patt = cleanup_file_name(patt)
table.insert(exc_patterns, matcher(patt))
end
end
local dirs_to_be_mked = {}
local function check_parent_dirs(path)
local parent_dirs = {}
for dir in str_split(path, PATH_SEPARATOR) do
parent_dirs[#parent_dirs + 1] = #parent_dirs > 0 and path_concat(parent_dirs[#parent_dirs], dir) or dir
end
for i, v in ipairs(parent_dirs) do
if i < #parent_dirs then
local mode = lfs.attributes(v, "mode")
if not mode and not dirs_to_be_mked[v] then
table.insert(dirs_to_be_mked, v)
dirs_to_be_mked[v] = true
elseif mode and mode ~= "directory" then
die("Build error: expected " .. v .. " to be a directory")
end
end
end
end
if tlconfig["files"] then
-- TODO: check if files are not relative
for _, fname in ipairs(tlconfig["files"]) do
if not project:find(fname) then
die("Build error: file \"" .. fname .. "\" not found")
end
project.source_file_map[fname] = fname:gsub("%.tl$", ".lua")
if tlconfig["build_dir"] then
project.source_file_map[fname] = path_concat(tlconfig["build_dir"], project.source_file_map[fname])
end
check_parent_dirs(project.source_file_map[fname])
end
end
local source_dir = tlconfig["source_dir"]
for path, is_build in project:file_with_is_build(inc_patterns, exc_patterns, source_dir) do
--TODO: make this better
local valid = true
if not (path:match("%.tl$") and not path:match("%.d%.tl$")) then
valid = false
end
if valid then
local work_on = path:gsub("%.tl$", ".lua")
if is_build then
work_on = remove_leading_path(build_path, work_on)
end
project.source_file_map[path] = work_on
if tlconfig["build_dir"] then
if source_dir then
project.source_file_map[path] = remove_leading_path(source_dir, project.source_file_map[path])
end
project.source_file_map[path] = path_concat(tlconfig["build_dir"], project.source_file_map[path])
end
check_parent_dirs(project.source_file_map[path])
end
end
for _, v in ipairs(dirs_to_be_mked) do
if not lfs.mkdir(v) then
die("Build error: unable to mkdir \"" .. v .. "\"")
end
end
-- sort source map so that order is deterministic (helps for testing output)
local sorted_source_file_arr = {}
for input_file, output_file in pairs(project.source_file_map) do
table.insert(sorted_source_file_arr, {input_file, output_file})
end
table.sort(sorted_source_file_arr, function(a, b) return a[1] < b[1] end)
if #sorted_source_file_arr == 0 then
os.exit(0)
end
turbo(true)
local env
for i, files in ipairs(sorted_source_file_arr) do
local input_file, output_file = files[1], files[2]
if not env then
env = setup_env(tlconfig, input_file)
end
local result, err = tl.process(input_file, env)
if err then
die(err)
end
filter_warnings(tlconfig, result)
if #result.syntax_errors == 0 and #result.type_errors == 0 then
write_out(tlconfig, result, output_file)
end
check_collect(i)
end
local ok = report_all_errors(tlconfig, env)
os.exit(ok and 0 or 1)
end
end
--------------------------------------------------------------------------------
-- Driver utilities
--------------------------------------------------------------------------------
local function validate_config(config)
local errs, warnings = {}, {}
local function warning(k, fmt, ...)
table.insert(warnings, string.format("* in key \"" .. k .. "\": " .. fmt, ...))
end
local function fail(k, fmt, ...)
table.insert(errs, string.format("* in key \"" .. k .. "\": " .. fmt, ...))
end
local function check_warnings(key)
if config[key] then
local unknown = {}
for _, warning in ipairs(config[key]) do
if not tl.warning_kinds[warning] then
table.insert(unknown, string.format("%q", warning))
end
end
if #unknown > 0 then
warning(key, "Unknown warning%s in config: %s", #unknown > 1 and "s" or "", table.concat(unknown, ", "))
end
end
end
local valid_keys = {
include_dir = "{string}",
global_env_def = "string",
quiet = "boolean",
skip_compat53 = "boolean",
gen_compat = { ["off"] = true, ["optional"] = true, ["required"] = true },
gen_target = { ["5.1"] = true, ["5.3"] = true, ["5.4"] = true },
disable_warnings = "{string}",
warning_error = "{string}",
-- build related keys
exclude = "{string}",
files = "{string}",
include = "{string}",
source_dir = "string",
build_dir = "string",
build_file = "string",
build_file_output_dir = "string",
internal_compiler_output = "string",
run_build_script = "boolean"
}
for k, v in pairs(config) do
if k == "preload_modules" then
fail(k, "this key is no longer supported. To load a definition globally into the environment, use global_env_def.")
elseif not valid_keys[k] then
warning(k, "unknown config key '" .. k .. "'")
elseif type(valid_keys[k]) == "table" then
if not valid_keys[k][v] then
fail(k, "expected one of: %s", table.concat(keys(valid_keys[k][v]), ", "))
end
else
-- TODO: could we type-check the config file using tl?
local arr_type = valid_keys[k]:match("{(.*)}")
if arr_type and type(v) == "table" then
for i, val in ipairs(v) do
if type(val) ~= arr_type then
fail(k, "expected a %s, got %s in position %d", valid_keys[k], type(val), i)
end
end
elseif type(v) ~= valid_keys[k] then
fail(k, "expected a %s, got %s", valid_keys[k], type(v))
end
end
end
if config.skip_compat53 then
config.gen_compat = "off"
end
check_warnings("disable_warnings")
check_warnings("warning_error")
return errs, warnings
end
local function get_args_parser()
local parser = argparse("tl", "A minimalistic typed dialect of Lua.")
parser:option("--global-env-def", "Predefined types from a custom global environment.")
:argname("<dtlfilename>")
:count("*") -- count("1") does not work? we verify by hand below then
parser:option("-I --include-dir", "Prepend this directory to the module search path.")
:argname("<directory>")
:count("*")
parser:option("--wdisable", "Disable the given kind of warning.")
:argname("<warning>")
:count("*")
parser:option("--werror", "Promote the given kind of warning to an error. " ..
"Use '--werror all' to promote all warnings to errors")
:argname("<warning>")
:count("*")
parser:option("--gen-compat", "Generate compatibility code for targeting different Lua VM versions.")
:choices({ "off", "optional", "required" })
:default("optional")
:defmode("a")
parser:option("--gen-target", "Minimum targeted Lua version for generated code.")
:choices({ "5.1", "5.3", "5.4" })
parser:flag("--skip-compat53", "Skip compat53 insertions.")
:hidden(true)
:action(function(args) args.gen_compat = "off" end)
parser:flag("--version", "Print version and exit")
parser:flag("-q --quiet", "Do not print information messages to stdout. Errors may still be printed to stderr.")
parser:flag("-p --pretend", "Do not write to any files, type check and output what files would be generated.")
parser:require_command(false)
parser:command_target("command")
local check_command = parser:command("check", "Type-check one or more Teal files.")
check_command:argument("file", "The Teal source file."):args("+")
local gen_command = parser:command("gen", "Generate a Lua file for one or more Teal files.")
gen_command:argument("file", "The Teal source file."):args("+")
gen_command:flag("-c --check", "Type check and fail on type errors.")
gen_command:flag("--keep-hashbang", "Preserve hashbang line (#!) at the top of file if present.")
gen_command:option("-o --output", "Write to <filename> instead.")
:argname("<filename>")
local run_command = parser:command("run", "Run a Teal script.")
run_command:argument("script", "The Teal script."):args("+")
run_command:option("-l --require", "Require module for execution.")
:argname("<modulename>")
:count("*")
build.arg_parser(parser)
parser:command("warnings", "List each kind of warning the compiler can produce.")
local types_command = parser:command("types", "Report all types found in one or more Teal files")
types_command:argument("file", "The Teal source file."):args("+")
types_command:option("-p --position", "Report values in scope in position line[:column]")
:argname("<position>")
return parser
end
local function get_config(cmd)
local config = {
include_dir = {},
disable_warnings = {},
warning_error = {},
quiet = false
}
local config_path = find_file_in_parent_dirs("tlconfig.lua") or "tlconfig.lua"
local conf, err = loadfile(config_path)
if not conf then
if err:match("No such file or directory$") then
build.tlconfig_not_found(cmd)
else
die("Error loading tlconfig.lua:\n" .. err)
end
end
if conf then
local ok, user_config = pcall(conf)
if not ok then
err = user_config
die("Error loading tlconfig.lua:\n" .. err)
end
-- Merge tlconfig with the default config
if user_config then
for k, v in pairs(user_config) do
config[k] = v
end
end
end
build.config_dir(cmd, config_path, config)
local errs, warnings = validate_config(config)
if #errs > 0 then
die("Error loading tlconfig.lua:\n" .. table.concat(errs, "\n"))
end
return config, warnings
end
local function merge_config_and_args(tlconfig, args)
do
local default_true_mt = { __index = function() return true end }
local function enable(tab, warning)
if warning == "all" then
setmetatable(tab, default_true_mt)
else
tab[warning] = true
end
end
tlconfig._disabled_warnings_set = {}
tlconfig._warning_errors_set = {}
for _, list in ipairs({ tlconfig["disable_warnings"] or {}, args["wdisable"] or {} }) do
for _, warning in ipairs(list) do
enable(tlconfig._disabled_warnings_set, warning)
end
end
for _, list in ipairs({ tlconfig["warning_error"] or {}, args["werror"] or {} }) do
for _, warning in ipairs(list) do
enable(tlconfig._warning_errors_set, warning)
end
end
end
if args["global_env_def"] then
if #args["global_env_def"] > 1 then
die("Error: --global-env-def can be used only once.")
elseif args["global_env_def"][1] then
tlconfig["global_env_def"] = args["global_env_def"][1]
end
end
for _, include_dir_cli in ipairs(args["include_dir"]) do
if not find_in_sequence(tlconfig.include_dir, include_dir_cli) then
table.insert(tlconfig.include_dir, include_dir_cli)
end
end
if args["quiet"] then
tlconfig["quiet"] = true
end
if args["pretend"] then
tlconfig["pretend"] = true
end
tlconfig["gen_target"] = args["gen_target"] or tlconfig["gen_target"]
tlconfig["gen_compat"] = args["gen_compat"] or tlconfig["gen_compat"]
or (tlconfig["skip_compat53"] and "off")
for _, include in ipairs(tlconfig["include_dir"]) do
prepend_to_lua_paths(include)
end
build.merge_config(tlconfig, args)
end
local function get_output_filename(file_name)
local tail = file_name:match("[^%" .. PATH_SEPARATOR .. "]+$")
if not tail then
return
end
local name, ext = tail:match("(.+)%.([a-zA-Z]+)$")
if not name then name = tail end
if ext ~= "lua" then
return name .. ".lua"
else
return name .. ".out.lua"