Debian Codegraph @

cmd/haredoc/main.ha

raw
1 // SPDX-License-Identifier: GPL-3.0-only
2 // (c) Hare authors <https://harelang.org>
3
4 use bufio;
5 use cmd::haredoc::doc;
6 use fmt;
7 use fs;
8 use getopt;
9 use hare::ast;
10 use hare::lex;
11 use hare::module;
12 use hare::parse;
13 use hare::unparse;
14 use io;
15 use memio;
16 use os;
17 use os::exec;
18 use path;
19 use strconv;
20 use strings;
21
22 const help: []getopt::help = [
23 "reads and formats Hare documentation",
24 ('a', "show undocumented members (only applies to -Ftty)"),
25 ('F', "format", "specify output format (tty or html)"),
26 ('n', "include file paths and line numbers"),
27 ('N', "print symbol path and line number and exit"),
28 ('t', "disable HTML template (requires postprocessing)"),
29 ('T', "tagset", "set/unset build tags"),
30 "[identifier|path]",
31 ];
32
33 export fn main() void = {
34 const cmd = getopt::parse(os::args, help...);
35 defer getopt::finish(&cmd);
36 match (doc(os::args[0], &cmd)) {
37 case void => void;
38 case let e: doc::error =>
39 fmt::fatal(doc::strerror(e));
40 case let e: exec::error =>
41 fmt::fatal(exec::strerror(e));
42 case let e: fs::error =>
43 fmt::fatal(fs::strerror(e));
44 case let e: io::error =>
45 fmt::fatal(io::strerror(e));
46 case let e: module::error =>
47 fmt::fatal(module::strerror(e));
48 case let e: path::error =>
49 fmt::fatal(path::strerror(e));
50 case let e: parse::error =>
51 fmt::fatal(parse::strerror(e));
52 case let e: strconv::error =>
53 fmt::fatal(strconv::strerror(e));
54 };
55 };
56
57 fn doc(name: str, cmd: *getopt::command) (void | error) = {
58 let html = false;
59 let template = true;
60 let show_undocumented = false;
61 let show_lineno = false;
62 let only_lineno = false;
63 let tags: []str = default_tags();
64 defer free(tags);
65
66 for (let (k, v) .. cmd.opts) {
67 switch (k) {
68 case 'F' =>
69 switch (v) {
70 case "tty" =>
71 html = false;
72 case "html" =>
73 html = true;
74 case =>
75 fmt::fatal("Invalid format", v);
76 };
77 case 'T' =>
78 merge_tags(&tags, v)?;
79 case 't' =>
80 template = false;
81 case 'n' =>
82 show_lineno = true;
83 case 'N' =>
84 only_lineno = true;
85 case 'a' =>
86 show_undocumented = true;
87 case => abort();
88 };
89 };
90
91 if (show_undocumented && html) {
92 fmt::fatal("Option -a must be used only with -Ftty");
93 };
94
95 if (len(cmd.args) > 1) {
96 getopt::printusage(os::stderr, os::args[0], help)!;
97 os::exit(os::status::FAILURE);
98 };
99
100 let ctx = module::context {
101 harepath = harepath(),
102 harecache = harecache(),
103 tags = tags,
104 };
105
106 let declpath = "";
107 defer free(declpath);
108 let declsrcs = module::srcset { ... };
109 defer module::finish_srcset(&declsrcs);
110 let modpath = "";
111 defer free(modpath);
112 let modsrcs = module::srcset { ... };
113 defer module::finish_srcset(&modsrcs);
114 let id: ast::ident = [];
115 defer free(id);
116
117 if (len(cmd.args) == 0) {
118 let (p, s) = module::find(&ctx, []: ast::ident)?;
119 modpath = strings::dup(p)!;
120 modsrcs = s;
121 } else {
122 const buf = memio::fixed(strings::toutf8(cmd.args[0]));
123 const scan = bufio::newscanner(&buf);
124 defer bufio::finish(&scan);
125 const lex = lex::init(&scan, "<argv>");
126 defer lex::finish(&lex);
127 match (parse::ident_trailing(&lex)) {
128 case let ident: (ast::ident, bool) =>
129 id = ident.0;
130 const trailing = ident.1;
131 if (!trailing) {
132 // check if it's an ident inside a module
133 match (module::find(&ctx, id[..len(id)-1])) {
134 case let s: (str, module::srcset) =>
135 declpath = strings::dup(s.0)!;
136 declsrcs = s.1;
137 case let e: module::error =>
138 module::finish_error(e);
139 };
140 };
141 // check if it's a module
142 match (module::find(&ctx, id)) {
143 case let s: (str, module::srcset) =>
144 modpath = strings::dup(s.0)!;
145 modsrcs = s.1;
146 case let e: module::error =>
147 module::finish_error(e);
148 if (declpath == "") {
149 const id = unparse::identstr(id);
150 fmt::fatalf("Could not find {}{}", id,
151 if (trailing) "::" else "");
152 };
153 };
154 case lex::error =>
155 let buf = path::init(cmd.args[0])?;
156 let (p, s) = module::find(&ctx, &buf)?;
157 modpath = strings::dup(p)!;
158 modsrcs = s;
159 };
160 };
161
162 let decls: []ast::decl = [];
163 defer {
164 for (let decl .. decls) {
165 ast::decl_finish(decl);
166 };
167 free(decls);
168 };
169
170 let parse_errs: []lex::syntax = [];
171 defer {
172 for (const err .. parse_errs) {
173 free(err.1);
174 };
175 free(parse_errs);
176 };
177
178 if (declpath != "") {
179 for (let ha .. declsrcs.ha) {
180 let d = match (doc::scan(ha)) {
181 case let d: []ast::decl =>
182 yield d;
183 case let err: parse::error =>
184 if (html) {
185 return err;
186 };
187 match (err) {
188 case let err: lex::syntax =>
189 const msg = strings::dup(err.1)!;
190 append(parse_errs, (err.0, msg))!;
191 continue;
192 case =>
193 return err;
194 };
195 };
196 defer free(d);
197 append(decls, d...)!;
198 };
199
200 let matching: []ast::decl = [];
201 let notmatching: []ast::decl = [];
202
203 for (let decl .. decls) {
204 if (has_decl(decl, id[len(id) - 1])) {
205 append(matching, decl)!;
206 } else {
207 append(notmatching, decl)!;
208 };
209 };
210 include_related(&matching, &notmatching);
211
212 for (let decl .. notmatching) {
213 ast::decl_finish(decl);
214 };
215 free(notmatching);
216 free(decls);
217 decls = matching;
218
219 if (len(matching) == 0) {
220 if (modpath == "") {
221 const id = unparse::identstr(id);
222 fmt::fatalf("Could not find {}", id);
223 };
224 } else {
225 show_undocumented = true;
226 };
227 };
228
229 let readme: (io::file | void) = void;
230 defer match (readme) {
231 case void => void;
232 case let f: io::file =>
233 io::close(f)!;
234 };
235
236 const ambiguous = modpath != "" && len(decls) > 0;
237
238 if (len(decls) == 0) :nodecls {
239 for (let ha .. modsrcs.ha) {
240 let d = match (doc::scan(ha)) {
241 case let d: []ast::decl =>
242 yield d;
243 case let err: parse::error =>
244 if (html) {
245 return err;
246 };
247 match (err) {
248 case let err: lex::syntax =>
249 const msg = strings::dup(err.1)!;
250 append(parse_errs, (err.0, msg))!;
251 continue;
252 case =>
253 return err;
254 };
255 };
256 defer free(d);
257 append(decls, d...)!;
258 };
259
260 const rpath = match (path::init(modpath, "README")) {
261 case let buf: path::buffer =>
262 yield buf;
263 case let err: path::error =>
264 assert(err is path::too_long);
265 yield :nodecls;
266 };
267 match (os::open(path::string(&rpath))) {
268 case let f: io::file =>
269 readme = f;
270 case fs::error => void;
271 };
272 };
273
274 const submods: []doc::submodule =
275 if (!ambiguous && modpath != "") {
276 yield match (doc::submodules(modpath, show_undocumented)) {
277 case let s: []doc::submodule =>
278 yield s;
279 case doc::error =>
280 yield [];
281 };
282 } else [];
283
284 if (only_lineno) {
285 if (len(decls) == 0) {
286 const id = unparse::identstr(id);
287 fmt::fatalf("Error: {}: symbol not found", id);
288 } else if (len(decls) != 1) {
289 const id = unparse::identstr(id);
290 fmt::fatalf("Error: {} matches more than one symbol", id);
291 };
292 const decl = decls[0];
293 fmt::printfln("{}:{}",
294 doc::cwdpath(decl.loc.start.path),
295 decl.loc.start.line)?;
296 return;
297 };
298
299 const srcs = if (!ambiguous && modpath != "") modsrcs else declsrcs;
300 const summary = doc::sort_decls(decls);
301 defer doc::finish_summary(summary);
302 const ctx = doc::context {
303 mctx = &ctx,
304 ident = id,
305 tags = tags,
306 ambiguous = ambiguous,
307 parse_errs = parse_errs,
308 srcs = srcs,
309 submods = submods,
310 summary = summary,
311 template = template,
312 readme = readme,
313 show_lineno = show_lineno,
314 show_undocumented = show_undocumented,
315 out = os::stdout,
316 pager = void,
317 };
318
319 const ret = if (html) {
320 yield doc::emit_html(&ctx);
321 } else {
322 ctx.out = init_tty(&ctx);
323 yield doc::emit_tty(&ctx);
324 };
325
326 io::close(ctx.out)!;
327 match (ctx.pager) {
328 case void => void;
329 case let proc: exec::process =>
330 exec::wait(&proc)!;
331 };
332
333 // TODO: remove ? (harec bug workaround)
334 return ret?;
335 };
336
337 fn init_tty(ctx: *doc::context) io::handle = {
338 const pager = match (os::getenv("PAGER")) {
339 case let name: str =>
340 yield match (exec::cmd(name)) {
341 case let cmd: exec::command =>
342 yield cmd;
343 case exec::error =>
344 return os::stdout;
345 };
346 case void =>
347 yield match (exec::cmd("less", "-R")) {
348 case let cmd: exec::command =>
349 yield cmd;
350 case exec::error =>
351 yield match (exec::cmd("more", "-R")) {
352 case let cmd: exec::command =>
353 yield cmd;
354 case exec::error =>
355 return os::stdout;
356 };
357 };
358 };
359
360 const pipe = exec::pipe();
361 defer io::close(pipe.0)!;
362 exec::addfile(&pager, os::stdin_file, pipe.0)!;
363 // Get raw flag in if possible
364 exec::setenv(&pager, "LESS", os::tryenv("LESS", "FRX"))!;
365 exec::setenv(&pager, "MORE", os::tryenv("MORE", "R"))!;
366 ctx.pager = exec::start(&pager)!;
367 return pipe.1;
368 };
369
370 fn has_decl(decl: ast::decl, name: str) bool = {
371 if (!decl.exported) {
372 return false;
373 };
374
375 match (decl.decl) {
376 case let d: ast::decl_const =>
377 if (len(d.ident) == 1 && d.ident[0] == name) {
378 return true;
379 };
380 case let d: ast::decl_func =>
381 if (len(d.ident) == 1 && d.ident[0] == name) {
382 return true;
383 };
384 case let d: ast::decl_global =>
385 if (len(d.ident) == 1 && d.ident[0] == name) {
386 return true;
387 };
388 case let d: ast::decl_type =>
389 if (len(d.ident) == 1 && d.ident[0] == name) {
390 return true;
391 };
392 case ast::assert_expr => void;
393 };
394 return false;
395 };
396
397 fn include_related(matching: *[]ast::decl, notmatching: *[]ast::decl) void = {
398 if (len(matching) != 1) {
399 return;
400 };
401 let decl = match (matching[0].decl) {
402 case let d: ast::decl_type =>
403 if (len(d.ident) != 1) {
404 return;
405 };
406 if (d._type.repr is ast::error_type) {
407 return;
408 };
409 match (d._type.repr) {
410 case let repr: ast::builtin_type =>
411 if (repr == ast::builtin_type::VOID) {
412 return;
413 };
414 case => void;
415 };
416 yield d;
417 case =>
418 return;
419 };
420
421 for (let i = 0z; i < len(notmatching); i += 1) {
422 let _type = match (notmatching[i].decl) {
423 case let d: ast::decl_const =>
424 yield match (d._type) {
425 case let t: *ast::_type =>
426 yield t;
427 case null =>
428 continue;
429 };
430 case let d: ast::decl_global =>
431 yield match (d._type) {
432 case let t: *ast::_type =>
433 yield t;
434 case null =>
435 continue;
436 };
437 case let d: ast::decl_func =>
438 let _type = d.prototype.repr as ast::func_type;
439 if (signature_matches(decl._type, d.prototype)) {
440 append(matching, notmatching[i])!;
441 delete(notmatching[i]);
442 i -= 1;
443 continue;
444 };
445 yield _type.result;
446 case =>
447 continue;
448 };
449
450 if (is_init_type(decl.ident, _type)) {
451 append(matching, notmatching[i])!;
452 delete(notmatching[i]);
453 i -= 1;
454 };
455 };
456 };
457
458 fn signature_matches(want: *ast::_type, prototype: *ast::_type) bool = {
459 for (true) {
460 match (want.repr) {
461 case let repr: ast::pointer_type =>
462 want = repr.referent;
463 case =>
464 break;
465 };
466 };
467 return want.repr is ast::func_type && type_eq(want, prototype);
468 };
469
470 // This isn't perfect, but it's correct 99% of the time
471 fn type_eq(a: *ast::_type, b: *ast::_type) bool = {
472 match (a.repr) {
473 case let arepr: ast::alias_type =>
474 match (b.repr) {
475 case let brepr: ast::alias_type =>
476 return ast::ident_eq(arepr, brepr);
477 case =>
478 return false;
479 };
480 case let arepr: ast::builtin_type =>
481 match (b.repr) {
482 case let brepr: ast::builtin_type =>
483 return arepr == brepr;
484 case =>
485 return false;
486 };
487 case ast::enum_type =>
488 return false; // code is invalid
489 case let e: ast::error_type =>
490 match (b.repr) {
491 case let brepr: ast::error_type =>
492 return type_eq(e: *ast::_type, brepr: *ast::_type);
493 case =>
494 return false;
495 };
496 case let arepr: ast::func_type =>
497 const brepr = match (b.repr) {
498 case let brepr: ast::func_type =>
499 yield brepr;
500 case =>
501 return false;
502 };
503
504 if (len(arepr.params) != len(brepr.params)
505 || arepr.variadism != brepr.variadism) {
506 return false;
507 };
508 for (let i = 0z; i < len(arepr.params); i += 1) {
509 if (!type_eq(arepr.params[i]._type,
510 brepr.params[i]._type)) {
511 return false;
512 };
513 };
514 return type_eq(arepr.result, brepr.result);
515 case let arepr: ast::list_type =>
516 const brepr = match (b.repr) {
517 case let brepr: ast::list_type =>
518 yield brepr;
519 case =>
520 return false;
521 };
522
523 if (!type_eq(arepr.members, brepr.members)) {
524 return false;
525 };
526 match (arepr.length) {
527 case *ast::expr =>
528 // It's not really worth it to check that the lengths
529 // are equal, since that would require checking
530 // expressions for equality, which isn't possible to do
531 // 100% correctly anyway (without an actual type
532 // checker). I can't imagine false positives will be
533 // very common here.
534 return brepr.length is *ast::expr;
535 case ast::len_slice =>
536 return brepr.length is ast::len_slice;
537 case ast::len_unbounded =>
538 return brepr.length is ast::len_unbounded;
539 case ast::len_contextual =>
540 return brepr.length is ast::len_contextual;
541 };
542 case let arepr: ast::pointer_type =>
543 match (b.repr) {
544 case let brepr: ast::pointer_type =>
545 return arepr.flags == brepr.flags
546 && type_eq(arepr.referent, brepr.referent);
547 case =>
548 return false;
549 };
550 case (ast::struct_type | ast::union_type) =>
551 // This pretty much won't ever happen in real-world code, and
552 // checking for equality is more effort than it's worth
553 return false;
554 case let arepr: ast::tagged_type =>
555 let brepr = match (b.repr) {
556 case let brepr: ast::tagged_type =>
557 yield brepr;
558 case =>
559 return false;
560 };
561 if (len(arepr) != len(brepr)) {
562 return false;
563 };
564 for (let i = 0z; i < len(arepr); i += 1) {
565 if (arepr[i].1 != brepr[i].1) {
566 return false;
567 };
568 if (!type_eq(arepr[i].0, brepr[i].0)) {
569 return false;
570 };
571 };
572 return true;
573 case let arepr: ast::tuple_type =>
574 match (b.repr) {
575 case let brepr: ast::tuple_type =>
576 return types_eq(arepr, brepr);
577 case =>
578 return false;
579 };
580 };
581 };
582
583 fn types_eq(a: []*ast::_type, b: []*ast::_type) bool = {
584 if (len(a) != len(b)) {
585 return false;
586 };
587
588 for (let i = 0z; i < len(a); i += 1) {
589 if (!type_eq(a[i], b[i])) {
590 return false;
591 };
592 };
593 return true;
594 };
595
596 fn is_init_type(ident: ast::ident, _type: *ast::_type) bool = {
597 let type_ident = match (_type.repr) {
598 case let repr: ast::alias_type =>
599 yield repr;
600 case let repr: ast::list_type =>
601 if (!(repr.length is ast::len_slice)) {
602 return false;
603 };
604 yield match (repr.members.repr) {
605 case let repr: ast::alias_type =>
606 yield repr;
607 case =>
608 return false;
609 };
610 case let repr: ast::pointer_type =>
611 yield match (repr.referent.repr) {
612 case let repr: ast::alias_type =>
613 yield repr;
614 case =>
615 return false;
616 };
617 case let repr: ast::tagged_type =>
618 for (let t .. repr) {
619 if (is_init_type(ident, t.0)) {
620 return true;
621 };
622 };
623 return false;
624 case =>
625 return false;
626 };
627
628 return ast::ident_eq(ident, type_ident);
629 };