Debian Codegraph @

cmd/haredoc/doc/sort.ha

raw
1 // SPDX-License-Identifier: GPL-3.0-only
2 // (c) Hare authors <https://harelang.org>
3
4 use hare::ast;
5 use sort;
6 use strings;
7
8 // Sorts declarations by:
9 // - removing unexported declarations,
10 // - setting the "exported" field of all remaining declarations to false, so the
11 // "export" keyword isn't unparsed,
12 // - moving undocumented declarations to the end,
13 // - sorting by identifier,
14 // - removing the initializer from globals and the body from functions,
15 // - ensuring that only one member is present in each declaration:
16 // "let x: int, y: int;" becomes two declarations: "let x: int; let y: int;".
17 export fn sort_decls(decls: []ast::decl) summary = {
18 let sorted = summary { ... };
19
20 for (let decl .. decls) {
21 if (!decl.exported) {
22 continue;
23 };
24
25 match (decl.decl) {
26 case let f: ast::decl_func =>
27 append(sorted.funcs, ast::decl {
28 exported = false,
29 loc = decl.loc,
30 decl = ast::decl_func {
31 symbol = f.symbol,
32 ident = f.ident,
33 prototype = f.prototype,
34 body = null,
35 attrs = f.attrs,
36 },
37 docs = decl.docs,
38 })!;
39 case let t: ast::decl_type =>
40 let bucket = &sorted.types;
41 if (t._type.repr is ast::error_type) {
42 bucket = &sorted.errors;
43 };
44 append(bucket, ast::decl {
45 exported = false,
46 loc = decl.loc,
47 decl = t,
48 docs = decl.docs,
49 })!;
50 case let c: ast::decl_const =>
51 append(sorted.constants, ast::decl {
52 exported = false,
53 loc = decl.loc,
54 decl = c,
55 docs = decl.docs,
56 })!;
57 case let g: ast::decl_global =>
58 append(sorted.globals, ast::decl {
59 exported = false,
60 loc = decl.loc,
61 decl = ast::decl_global {
62 is_const = g.is_const,
63 is_threadlocal = g.is_threadlocal,
64 symbol = g.symbol,
65 ident = g.ident,
66 _type = g._type,
67 init = null,
68 },
69 docs = decl.docs,
70 })!;
71 case ast::assert_expr => void;
72 };
73 };
74
75 sort::sort(sorted.constants, size(ast::decl), &decl_cmp)!;
76 sort::sort(sorted.errors, size(ast::decl), &decl_cmp)!;
77 sort::sort(sorted.types, size(ast::decl), &decl_cmp)!;
78 sort::sort(sorted.globals, size(ast::decl), &decl_cmp)!;
79 sort::sort(sorted.funcs, size(ast::decl), &decl_cmp)!;
80 return sorted;
81 };
82
83 fn decl_cmp(a: const *opaque, b: const *opaque) int = {
84 const a = a: const *ast::decl;
85 const b = b: const *ast::decl;
86 if (a.docs == "" && b.docs != "") {
87 return 1;
88 } else if (a.docs != "" && b.docs == "") {
89 return -1;
90 };
91 const id_a = decl_ident(a), id_b = decl_ident(b);
92 return strings::compare(id_a[len(id_a) - 1], id_b[len(id_b) - 1]);
93 };
94
95 fn decl_ident(decl: *ast::decl) ast::ident = {
96 match (decl.decl) {
97 case let f: ast::decl_func =>
98 return f.ident;
99 case let t: ast::decl_type =>
100 return t.ident;
101 case let c: ast::decl_const =>
102 return c.ident;
103 case let g: ast::decl_global =>
104 return g.ident;
105 case ast::assert_expr => abort();
106 };
107 };