-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate-docs.lua
More file actions
1986 lines (1814 loc) · 56.7 KB
/
Copy pathgenerate-docs.lua
File metadata and controls
1986 lines (1814 loc) · 56.7 KB
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
local insert = table.insert
local sort = table.sort
local concat = table.concat
local fmt = string.format
local script_path = debug.getinfo(1, "S").source:gsub("^@", "")
local script_dir = script_path:match("^(.*)/[^/]*$") or "."
local lls = dofile(script_dir .. "/luals-type-parser.lua")
local config = dofile(script_dir .. "/config.lua")
local ignored_stems = {}
for _, stem in ipairs(config.ignored_stems or {}) do
ignored_stems[stem] = true
end
local FIELD_OVERVIEW_MIN = config.FIELD_OVERVIEW_MIN
local github_org = config.github_org or "BlueLua"
local github_types_dir = config.github_types_dir or "types"
local github_types_url_template = "https://github.com/"
.. github_org
.. "/%s/blob/main/"
.. github_types_dir
.. "/%s#L%d-L%d"
local domain = config.domain or "bluelua.github.io"
local escaped_domain = domain:gsub("%.", "%%.")
local internal_link_pattern = "https?://" .. escaped_domain .. "/([^%s%)%\"%'%>]+)"
local api_dir_name = config.api_dir_name or "api"
local types_file_name = config.types_file_name or "types"
local function page_stem(filename)
return filename:gsub("%.d%.lua$", ""):gsub("%.lua$", ""):lower()
end
local link_refs = {}
local types_dir, output_dir
local has_ffi, ffi = pcall(require, "ffi")
if has_ffi then
ffi.cdef [[
int access(const char *pathname, int mode);
int mkdir(const char *pathname, unsigned int mode);
]]
end
local function shell_quote(s)
return "'" .. tostring(s):gsub("'", [['"'"']]) .. "'"
end
local function exists_dir(path)
if has_ffi then
return ffi.C.access(path .. "/.", 0) == 0
else
local f = io.open(path .. "/.", "r")
if f then
f:close()
return true
end
return false
end
end
local function is_valid_module(module)
if not module then
return false
end
local std_types = {
string = true,
number = true,
boolean = true,
table = true,
["function"] = true,
thread = true,
userdata = true,
["nil"] = true,
any = true,
void = true,
integer = true,
unknown = true,
}
if std_types[module] then
return false
end
local path = script_dir .. "/../docs/src/" .. module
return exists_dir(path)
end
local function is_api_page(module, stem)
-- 1. Check if the generated markdown file exists in the central docs repo
local central_path = string.format("%s/../docs/src/%s/api/%s.md", script_dir, module, stem)
local f = io.open(central_path, "r")
if f then
f:close()
return true
end
-- 2. Check if the source type file exists in the current types directory
if types_dir then
local t1 = io.open(string.format("%s/%s.lua", types_dir, stem), "r")
if t1 then
t1:close()
return true
end
local t2 = io.open(string.format("%s/%s.d.lua", types_dir, stem), "r")
if t2 then
t2:close()
return true
end
end
-- 3. Check if it exists in the output directory
if output_dir then
local out_path = io.open(string.format("%s/%s.md", output_dir, stem), "r")
if out_path then
out_path:close()
return true
end
end
return false
end
-- =========================================================================
-- Common Helper Functions
-- =========================================================================
local function trim(s)
return s and s:match("^%s*(.-)%s*$") or ""
end
local function split_name_rest(s)
if type(s) ~= "string" then
return
end
s = s:gsub("^%s+", "")
if s == "" then
return
end
local depth = 0
local quote = nil
local escape = false
for i = 1, #s do
local ch = s:sub(i, i)
if quote then
if escape then
escape = false
elseif ch == "\\" then
escape = true
elseif ch == quote then
quote = nil
end
else
if ch == '"' or ch == "'" then
quote = ch
elseif ch == "(" or ch == "[" or ch == "{" or ch == "<" then
depth = depth + 1
elseif ch == ")" or ch == "]" or ch == "}" or ch == ">" then
if depth > 0 then
depth = depth - 1
end
elseif ch:match("%s") and depth == 0 then
local name = s:sub(1, i - 1)
local rest = s:sub(i + 1)
return name, rest:gsub("^%s+", "")
end
end
end
return s, ""
end
local function split_type_desc_from_view(view)
view = trim(view)
if view:match("^fun%(") then
local depth = 0
local params_end = nil
for i = 1, #view do
local ch = view:sub(i, i)
if ch == "(" then
depth = depth + 1
elseif ch == ")" then
depth = depth - 1
if depth == 0 then
params_end = i
break
end
end
end
if params_end then
local after = view:sub(params_end + 1)
local start_idx, end_idx = after:find("^%s*:%s*")
if start_idx then
local ret_part = after:sub(end_idx + 1)
local ret_part_trimmed = trim(ret_part)
if ret_part_trimmed:sub(1, 1) == "(" then
local r_depth = 0
local r_end = nil
for i = 1, #ret_part do
local ch = ret_part:sub(i, i)
if ch == "(" then
r_depth = r_depth + 1
elseif ch == ")" then
r_depth = r_depth - 1
if r_depth == 0 then
r_end = i
break
end
end
end
if r_end then
local tp = view:sub(1, params_end + end_idx + r_end)
local desc = trim(ret_part:sub(r_end + 1))
return tp, desc
end
else
local ret_type, desc = ret_part_trimmed:match("^(%S+)%s*(.*)$")
if ret_type then
local tp = view:sub(1, params_end) .. after:sub(1, end_idx) .. ret_type
return tp, trim(desc)
end
end
else
local desc = trim(after)
return view:sub(1, params_end), desc
end
end
end
return split_name_rest(view)
end
local function esc_table_cell(s)
return (s or ""):gsub("\n", " "):gsub("|", "\\|")
end
local function resolve_internal_links(s)
if type(s) ~= "string" then
return s
end
return s:gsub(internal_link_pattern, function(path)
local base, hash = path:match("^([^#]+)(#.+)$")
base = base or path
hash = hash or ""
base = base:gsub("%.html$", ""):gsub("%.md$", "")
return "/" .. base .. hash
end)
end
local function is_function_doc_item(item)
if not item or item.kind ~= "alias" then
return false
end
if type(item.name) ~= "string" or not item.name:match("^M%.[%a_][%w_]*$") then
return false
end
if type(item.alias_of) == "string" and item.alias_of:match("^M%.[%a_][%w_]*$") then
if item.name:lower() == item.alias_of:lower() then
return false
end
end
return true
end
local function clean_main_content(s)
local split_idx = s:find("<!-- prettier-ignore-start -->", 1, true)
local main_content
if split_idx then
main_content = s:sub(1, split_idx - 1)
else
main_content = s
end
-- Strip all trailing newlines and whitespace
main_content = main_content:gsub("%s*$", "")
return main_content
end
local function convert_inline_links_to_references(s)
if type(s) ~= "string" then
return s
end
local main_content = clean_main_content(s)
-- Extract existing references from s (if any)
local existing_refs = {}
local split_idx = s:find("<!-- prettier-ignore-start -->", 1, true)
if split_idx then
local ref_block = s:sub(split_idx)
for line in ref_block:gmatch("[^\r\n]+") do
local key, url = line:match("^%s*%[([^%]]+)%]%:%s*(%S+)%s*$")
if key and url then
existing_refs[key] = url
end
end
end
local new_refs = {}
-- Match [link text](url) (skipping lines that start with a markdown header prefix '#')
local lines = {}
for line in (main_content .. "\n"):gmatch("([^\n]*)\n") do
if line:match("^%s*#") then
insert(lines, line)
else
local modified_line = line:gsub("([%!]?)%[([^%]]+)%]%(([^%)]+)%)", function(is_image, text, url)
if is_image == "!" then
return "!" .. "[" .. text .. "](" .. url .. ")"
end
local clean_text = text:gsub("^%s*(.-)%s*$", "%1")
local key = clean_text
local target_key = nil
if (existing_refs[key] and existing_refs[key] == url) or (new_refs[key] and new_refs[key] == url) then
target_key = key
elseif not existing_refs[key] and not new_refs[key] then
new_refs[key] = url
target_key = key
else
local base_key = key
local is_code = base_key:match("^`([^`]+)`$")
local i = 1
while true do
local candidate
if is_code then
candidate = "`" .. is_code .. "-" .. i .. "`"
else
candidate = base_key .. "-" .. i
end
if
(existing_refs[candidate] and existing_refs[candidate] == url)
or (new_refs[candidate] and new_refs[candidate] == url)
then
target_key = candidate
break
elseif not existing_refs[candidate] and not new_refs[candidate] then
new_refs[candidate] = url
target_key = candidate
break
end
i = i + 1
end
end
if clean_text == target_key then
return "[" .. clean_text .. "]"
else
return "[" .. clean_text .. "][" .. target_key .. "]"
end
end)
insert(lines, modified_line)
end
end
local modified_content = concat(lines, "\n")
for k, v in pairs(new_refs) do
existing_refs[k] = v
end
local sorted_keys = {}
for k in pairs(existing_refs) do
local escaped = k:gsub("[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%1")
local pattern = "%[%s*" .. escaped .. "%s*%]"
if modified_content:find(pattern) then
insert(sorted_keys, k)
end
end
sort(sorted_keys)
if #sorted_keys == 0 then
return modified_content .. "\n"
end
local new_ref_lines = {}
for _, k in ipairs(sorted_keys) do
insert(new_ref_lines, string.format("[%s]: %s", k, existing_refs[k]))
end
local new_ref_block_content = concat(new_ref_lines, "\n")
return modified_content
.. "\n\n<!-- prettier-ignore-start -->\n"
.. new_ref_block_content
.. "\n<!-- prettier-ignore-end -->\n"
end
local function resolve_code_spans_and_add_links(s)
if type(s) ~= "string" then
return s
end
local main_content = clean_main_content(s)
-- Extract existing references from s (if any)
local existing_refs = {}
local split_idx = s:find("<!-- prettier-ignore-start -->", 1, true)
if split_idx then
local ref_block = s:sub(split_idx)
for name, url in ref_block:gmatch("%[?`([^`]+)`%]?:%s*(%S+)") do
existing_refs[name] = url
end
end
-- Extract code blocks to prevent backtick parity shifting
local code_blocks = {}
local block_count = 0
local cursor = 1
local parts = {}
while true do
local start_idx, end_idx = main_content:find("```", cursor)
if not start_idx then
table.insert(parts, main_content:sub(cursor))
break
end
local close_start, close_end = main_content:find("```", end_idx + 1)
if not close_start then
table.insert(parts, main_content:sub(cursor))
break
end
local block = main_content:sub(start_idx, close_end)
block_count = block_count + 1
code_blocks[block_count] = block
table.insert(parts, main_content:sub(cursor, start_idx - 1))
table.insert(parts, string.format("\001CODEBLOCK%d\002", block_count))
cursor = close_end + 1
end
main_content = table.concat(parts)
local new_refs = {}
local modified_content = main_content:gsub("([%[%w_]?)`([^`]+)`([%]%w_]?)", function(before, content, after)
if before == "[" or after == "]" then
return before .. "`" .. content .. "`" .. after
end
local module, rest = content:match("^([%w_]+)%.(.+)$")
if module and is_valid_module(module) then
local name_path, paren_part = rest:match("^([%w_%.:]+)(.*)$")
if name_path then
local clean_p = module .. "." .. name_path
local first_seg = name_path:match("^([^%.%:]+)") or name_path
local stem = first_seg:lower()
local url
if is_api_page(module, stem) then
url = string.format("/%s/api/%s", module, stem)
local remaining = name_path:sub(#first_seg + 2)
if remaining ~= "" then
local anchor = remaining:lower():gsub("[^%w%-]+", "-"):gsub("%-+", "-"):gsub("^%-+", ""):gsub("%-+$", "")
url = url .. "#" .. anchor
end
else
local slug = clean_p:lower():gsub("[^%w%-]+", "-"):gsub("%-+", "-"):gsub("^%-+", ""):gsub("%-+$", "")
url = string.format("/%s/types#%s", module, slug)
end
local display_text = module .. "." .. name_path .. paren_part
new_refs[display_text] = url
return before .. "[`" .. display_text .. "`]" .. after
end
end
return before .. "`" .. content .. "`" .. after
end)
-- Restore code blocks
for i = 1, block_count do
modified_content = modified_content:gsub("\001CODEBLOCK" .. i .. "\002", function()
return code_blocks[i]
end)
end
for name, url in pairs(new_refs) do
existing_refs[name] = url
end
local sorted_names = {}
for name in pairs(existing_refs) do
table.insert(sorted_names, name)
end
table.sort(sorted_names)
if #sorted_names == 0 then
return modified_content .. "\n"
end
local new_ref_lines = {}
for _, name in ipairs(sorted_names) do
table.insert(new_ref_lines, string.format("[`%s`]: %s", name, existing_refs[name]))
end
local new_ref_block_content = table.concat(new_ref_lines, "\n")
return modified_content
.. "\n\n<!-- prettier-ignore-start -->\n"
.. new_ref_block_content
.. "\n<!-- prettier-ignore-end -->\n"
end
local function sanitize_alias_part(part)
local p = trim(part)
local dq, dq_rest = p:match('^("[^"]*")%s*(.*)$')
if dq then
return dq, trim(dq_rest or "")
end
local sq, sq_rest = p:match([[^('[^']*')%s*(.*)$]])
if sq then
return '"' .. sq:sub(2, -2) .. '"', trim(sq_rest or "")
end
local val, desc = p:match("^([%w_%.:]+)%s+(.+)$")
if val then
return val, trim(desc or "")
end
return p, ""
end
local function alias_view_to_string(view)
if type(view) == "table" then
local out = {}
local alias_desc = nil
for _, part in ipairs(view) do
local p, extra = sanitize_alias_part(tostring(part))
if p ~= "" then
insert(out, p)
end
if extra ~= "" and not alias_desc then
alias_desc = extra
end
end
return table.concat(out, " | "), alias_desc
end
return trim(tostring(view or "")), nil
end
local function is_literal(val)
local s = tostring(val)
if s:match("^['\"]") then
return true
end
if tonumber(s) then
return true
end
if s == "true" or s == "false" then
return true
end
return false
end
local function compare_union_values(a, b)
local val_a = a.value
local val_b = b.value
local lit_a = is_literal(val_a)
local lit_b = is_literal(val_b)
if lit_a ~= lit_b then
return lit_a
end
local num_a = tonumber(val_a)
local num_b = tonumber(val_b)
if num_a and num_b then
return num_a < num_b
end
local str_a = tostring(val_a):gsub("^['\"]", ""):gsub("['\"]$", ""):lower()
local str_b = tostring(val_b):gsub("^['\"]", ""):gsub("['\"]$", ""):lower()
return str_a < str_b
end
local function get_union_parts(view)
if type(view) == "table" then
local parts = {}
for _, part in ipairs(view) do
local p, extra = sanitize_alias_part(tostring(part))
if p ~= "" then
insert(parts, { value = p, desc = extra ~= "" and extra or nil })
end
end
return parts
end
return nil
end
local function get_table_fields(val_str)
local s = trim(val_str)
if s:sub(1, 1) == "{" and s:sub(-1, -1) == "}" then
local fields_str = s:sub(2, -2)
local fields = {}
for part in fields_str:gmatch("[^,]+") do
local k, t = part:match("^%s*([%w_%?]+)%s*:%s*(.*)$")
if k and t then
insert(fields, { key = trim(k), type = trim(t) })
end
end
if #fields > 0 then
return fields
end
end
return nil
end
-- =========================================================================
-- File System / CLI Helpers
-- =========================================================================
local function mkdir_p(path)
if has_ffi then
local current = ""
if path:sub(1, 1) == "/" then
current = "/"
end
for part in path:gmatch("[^/]+") do
if current == "/" or current == "" then
current = current .. part
else
current = current .. "/" .. part
end
ffi.C.mkdir(current, 493) -- 0755 permissions
end
else
os.execute("mkdir -p " .. shell_quote(path))
end
end
local function read_file(path)
local f = assert(io.open(path, "rb"))
local data = f:read("*a")
f:close()
return data
end
local function write_file(path, data)
local f = assert(io.open(path, "wb"))
f:write(data)
f:close()
end
local function list_type_files(path, include_all)
local p = assert(io.popen("ls -1 " .. shell_quote(path), "r"))
local out = {}
for line in p:lines() do
if line:match("%.lua$") then
if include_all or line:sub(1, 1) ~= "_" then
insert(out, line)
end
end
end
p:close()
sort(out)
return out
end
-- =========================================================================
-- API Markdown Renderer
-- =========================================================================
local function first_match(items, pred)
for _, item in ipairs(items or {}) do
if pred(item) then
return item
end
end
end
local function pick_module_name(items, stem)
local item = first_match(items, function(it)
return it.kind == "meta" and it.shortname
end)
local name = item and item.shortname or "module"
if name == "_" and stem then
return stem
end
return name
end
local function pick_module_desc(items, module_name)
local meta_item = first_match(items, function(it)
return it.kind == "meta" and it.desc
end)
if meta_item then
return meta_item.desc
end
local m_class = first_match(items, function(it)
if it.kind ~= "class" or not it.desc then
return false
end
if it.var_name == "M" then
return true
end
local view_name = it.view:match("^([^:]+)") or it.view
view_name = trim(view_name):gsub("<[^>]+>", "")
return view_name == "M"
end)
if m_class then
return m_class.desc
end
local class_item = first_match(items, function(it)
return it.kind == "class" and it.desc
end)
if class_item then
return class_item.desc
end
local item_with_desc = first_match(items, function(it)
return it.desc
end)
return item_with_desc and item_with_desc.desc
end
local function has_function_items(items)
return first_match(items, function(it)
return it.kind == "function" or is_function_doc_item(it)
end) ~= nil
end
local function collect_include_paths(items)
local out = {}
local seen = {}
for _, item in ipairs(items or {}) do
local tags = item and item.tags
local includes = tags and tags.includes
if type(includes) == "table" then
for _, path in ipairs(includes) do
if type(path) == "string" and path ~= "" and not seen[path] then
seen[path] = true
insert(out, path)
end
end
end
end
return out
end
local function collect_include_blocks(items)
local out = {}
for _, item in ipairs(items or {}) do
local tags = item and item.tags
local blocks = tags and tags.include_blocks
if type(blocks) == "table" then
for _, block in ipairs(blocks) do
if type(block) == "string" and block ~= "" then
insert(out, block)
end
end
end
end
return out
end
local function count_function_items(items)
local n = 0
for _, item in ipairs(items or {}) do
if item and (item.kind == "function" or is_function_doc_item(item)) then
n = n + 1
end
end
return n
end
local function collect_class_fields(items)
local out = {}
local seen = {}
for _, item in ipairs(items or {}) do
if item and item.kind == "class" then
local tags = item.tags
local fields = tags and tags.fields
if type(fields) == "table" then
for _, field in ipairs(fields) do
local name = field and field.name
local desc = (field and field.desc or ""):gsub("%s+", " "):gsub("^%s+", ""):gsub("%s+$", "")
if name and name ~= "__index" and (desc ~= "" or field.value ~= nil) and not seen[name] then
seen[name] = true
insert(out, field)
end
end
end
end
end
sort(out, function(a, b)
return (a.name or "") < (b.name or "")
end)
return out
end
local function value_to_markdown(value)
local t = type(value)
if t == "string" then
return fmt("`%q`", value)
elseif t == "number" or t == "boolean" then
return fmt("`%s`", tostring(value))
end
end
local function first_sentence(s)
if not s then
return nil
end
local flattened = s:gsub("%s+", " "):gsub("^%s+", ""):gsub("%s+$", "")
if flattened == "" then
return nil
end
local period = flattened:find("%.")
if period then
return flattened:sub(1, period)
end
return flattened
end
local function render_frontmatter(module_name, desc)
local lines = { "---" }
insert(lines, fmt('title: "%s"', module_name:gsub('"', '\\"')))
local short_desc = first_sentence(desc)
if short_desc then
local clean_desc = short_desc:gsub("<[^>]+>", "")
insert(lines, fmt('description: "%s"', clean_desc:gsub('"', '\\"')))
end
insert(lines, "---")
return concat(lines, "\n")
end
local function first_paragraph(s)
if not s then
return ""
end
local para = s:match("^(.-)\n%s*\n") or s
return para:gsub("%s+", " "):gsub("^%s+", ""):gsub("%s+$", "")
end
local function heading_anchor(s)
return (s or ""):lower():gsub("_+", "-"):gsub("[^%w-]+", ""):gsub("^%-+", ""):gsub("%-+$", "")
end
local function function_signature(item)
local base = item.shortname or item.name or ""
if item.kind == "alias" then
return base
end
local params = {}
local tag_params = item.tags and item.tags.params
if type(tag_params) == "table" then
for _, param in ipairs(tag_params) do
local name = param and param.name
if name and name ~= "" and name ~= "self" then
insert(params, name)
end
end
end
if #params == 0 then
return base .. "()"
end
return base .. "(" .. concat(params, ", ") .. ")"
end
local function function_ref_id(item)
return heading_anchor(item.shortname or item.name or "")
end
local function format_type_value_ref(val)
local s = tostring(val):gsub("self:%s*[^,)]+", "self")
s = s:gsub("([%w_]+)%s*:%s*([^,%)]-)%?", "%1?: %2")
local parts = {}
for part in s:gmatch("[^|]+") do
local p = part:match("^%s*(.-)%s*$") -- trim
local formatted = p:gsub("([%w_]+)%.([%w_%.]+)", function(module, name)
if module and is_valid_module(module) then
local first_seg = name:match("^([^%.]+)") or name
local stem = first_seg:lower()
local url
if is_api_page(module, name:lower()) then
url = string.format("/%s/api/%s", module, name:lower())
else
local clean_p = module .. "." .. name
local slug = clean_p:lower():gsub("[^%w%-]+", "-"):gsub("%-+", "-"):gsub("^%-+", ""):gsub("%-+$", "")
url = string.format("/%s/types#%s", module, slug)
end
local clean_p = module .. "." .. name
link_refs[clean_p] = url
return "`[`" .. clean_p .. "`]`"
end
return nil
end)
local final_part = ("`" .. formatted .. "`"):gsub("``", "")
insert(parts, final_part)
end
return table.concat(parts, " | ")
end
local function collect_alias_views(items)
local out = {}
for _, item in ipairs(items or {}) do
if item and item.kind == "alias" and item.view ~= nil then
local expanded, alias_desc = alias_view_to_string(item.view)
if expanded ~= "" then
local data = { view = expanded, desc = alias_desc or item.desc }
if type(item.name) == "string" and item.name ~= "" then
out[item.name] = data
end
if type(item.shortname) == "string" and item.shortname ~= "" then
out[item.shortname] = data
end
end
end
end
return out
end
local function expand_type_view(view, alias_views, seen)
local v = trim(tostring(view or ""))
if v == "" then
return "any", nil
end
local mapped = alias_views and alias_views[v]
if not mapped then
return v, nil
end
seen = seen or {}
if seen[v] then
return v, mapped.desc
end
seen[v] = true
local out, nested_desc = expand_type_view(mapped.view, alias_views, seen)
seen[v] = nil
return out, mapped.desc or nested_desc
end
local function normalize_api_desc(desc)
local d = trim(desc or "")
d = d:gsub("^#%s*", "")
return d
end
local function adjust_optional_name_type(name, view)
local clean_name = name or ""
local clean_view = view or "any"
if clean_view:sub(-1) == "?" and not clean_view:match("^%s*fun%(") then
clean_view = clean_view:sub(1, -2)
if clean_name ~= "" and clean_name:sub(-1) ~= "?" then
clean_name = clean_name .. "?"
end
end
return clean_name, clean_view
end
local function append_function_api_contract(doc, item, alias_views)
local tags = item.tags or {}
local params = tags.params or {}
local returns = tags.returns or {}
local has_params = false
for _, param in ipairs(params) do
local pname = param and param.name or ""
if pname ~= "" and pname ~= "self" then
has_params = true
break
end
end
local has_returns = #returns > 0
if not has_params and not has_returns then
return
end
if has_params then
insert(doc, "**Parameters**:")
for _, param in ipairs(params) do
local pname = param and param.name or ""
local pview = param and param.view or "any"
local _, alias_desc = expand_type_view(pview, alias_views)
local pdesc = normalize_api_desc(param and param.desc or "")
if pdesc == "" and alias_desc and alias_desc ~= "" then
pdesc = normalize_api_desc(alias_desc)
end
if pname ~= "" and pname ~= "self" then
local clean_pname, clean_pview = adjust_optional_name_type(pname, pview)
if pdesc ~= "" then
insert(doc, fmt("- `%s` (%s): %s", clean_pname, format_type_value_ref(clean_pview), pdesc))
else
insert(doc, fmt("- `%s` (%s)", clean_pname, format_type_value_ref(clean_pview)))
end
end
end
end
if has_returns then
insert(doc, "")
insert(doc, "**Returns**:")
for _, ret in ipairs(returns) do
local rname = ret and ret.name or ""
local rview = ret and ret.view or "any"
local _, alias_desc = expand_type_view(rview, alias_views)
local rdesc = normalize_api_desc(ret and ret.desc or "")
if rdesc == "" and alias_desc and alias_desc ~= "" then
rdesc = normalize_api_desc(alias_desc)
end
local clean_rname, clean_rview = adjust_optional_name_type(rname, rview)
local label