]> git.draconx.ca Git - dxcommon.git/blob - scripts/gen-tree.awk
gen-options.awk: Work around busybox regex bug.
[dxcommon.git] / scripts / gen-tree.awk
1 #!/bin/awk -f
2 #
3 # Copyright © 2021-2022 Nick Bowler
4 #
5 # Generate one or more C array initializers to encode simple tree structures
6 # in a compact format.
7 #
8 # Each nonempty line of the input file is either a comment, an option
9 # specification or a tree specification.  Each line is distinguished by
10 # its first character.  A # character introduces a comment, an @ character
11 # introduces an option specification (described later), and all other
12 # nonempty lines are tree nodes.
13 #
14 # The first field of a tree specification must be a valid C identifier,
15 # optionally followed by a comma.  The identifiers used on non-leaf nodes
16 # must be unique with respect to other non-leaf nodes, but leaf nodes may
17 # share the same identifier as other nodes.
18 #
19 # The tree structure is expressed through indentation.  Lines with no leading
20 # whitespace designate root nodes.  When the number of white-space characters
21 # at the beginning of a line is greater than that of the previous line, this
22 # introduces a new subtree rooted at the previous node.  When the number of
23 # leading white-space characters is less than the previous line, this concludes
24 # the definition of the current subtree.
25 #
26 # For example, the input on the left describes the tree on the right.
27 #
28 #    INPUT: root           TREE: root -- a -- b -- c
29 #              a                    |    |
30 #                 b                 |    + -- d
31 #                    c              |
32 #                 d                 + -- e -- f
33 #              e                         |
34 #                 f                      + -- g
35 #                 g
36 #
37 # For each root node X, the object-like macro X_INITIALIZER is defined.  This
38 # can be used to initialize an array with static storage duration.  Each line
39 # of the input is defines the initializer for one array element.  These are
40 # then ordered topologically beginning with the root, but the root itself is
41 # not included.  Each subtree is terminated by an "empty" element (with an
42 # initializer of {0}).
43 #
44 # If there is a comma after the identifier which begins a tree element, or
45 # if the identifier is the only text on the line, then the element initializer
46 # is constructed by surrounding the entire line by braces.  Otherwise, the
47 # identifier is removed and the remainder of the line is surrounded by braces
48 # to construct the initializer.  This allows the exact form of the initializer
49 # to be customized.
50 #
51 # For example, the above input will produce this (or an equivalent topological
52 # ordering) initializer:
53 #
54 #    OUTPUT: #define root_INITIALIZER \
55 #                 {a}, {e}, {0}, {b}, {d}, {0}, {f}, {g}, {0}, {c}, {0}
56 #
57 # Constants representing the array offset for each subtree are additionally
58 # defined.  For a non-leaf node X, the enumeration constant X_OFFSET gives the
59 # index of the first node rooted at X.  With the above example, the results
60 # are:
61 #
62 #    OUTPUT: enum { a_OFFSET = 3, b_OFFSET = 9, e_OFFSET = 6 };
63 #
64 # By using an array of structures to represent the tree and including these
65 # constants in initializers, it is possible for the flattened tree to describe
66 # its own structure.
67 #
68 # Finally, each node identifier is defined as an enumeration constant
69 # representing the nonzero offset into a string table tree_strtab.  These
70 # constants will normally be in scope when using the root_INITIALIZER macro,
71 # which means the resulting array initializers will use them.
72 #
73 # Options may be used to alter the normal behaviour.  They may be placed
74 # anywhere in the input file.  The following options are defined:
75 #
76 #   @nostrtab
77 #     Do not output a definition for tree_strtab or its associated
78 #     enumeration constants.
79 #
80 # License WTFPL2: Do What The Fuck You Want To Public License, version 2.
81 # This is free software: you are free to do what the fuck you want to.
82 # There is NO WARRANTY, to the extent permitted by law.
83
84 END {
85   print "/*"
86   if (FILENAME) {
87     print " * Automatically generated by gen-tree.awk from " FILENAME
88   } else {
89     print " * Automatically generated by gen-tree.awk"
90   }
91   print " * Do not edit."
92   print " */"
93 }
94
95 BEGIN {
96   opts["strtab"] = 1;
97
98   depth = max_depth = 0;
99   num_entries = 0;
100
101   tree_name = "";
102   entry_name = "";
103
104   indent_stack[0] = 0;
105 }
106
107 # Comments
108 NF == 0 { next }
109 $0 ~ /^#/ { next }
110
111 # Options
112 sub(/^@/, "", $0) {
113   if (NF == 1) {
114     orig=$1
115     gsub(/-/, "_", $1);
116     val = !sub(/^no_?/, "", $1);
117     if ($1 in opts) {
118       opts[$1] = val;
119     } else {
120       print "error: unrecognized option: @" orig | "cat 1>&2"
121       exit 1
122     }
123   }
124   next
125 }
126
127 { indent = index($0, $1) - 1 }
128
129 indent > 0 {
130   if (indent > indent_stack[depth]) {
131     indent_stack[++depth] = indent;
132     if (depth > 1) {
133       subtree_offsets[entry_name] = level_count[depth];
134       subtree_depth[entry_name] = depth;
135     }
136   } else {
137     while (indent < indent_stack[depth]) {
138       tree_items[depth] = tree_items[depth] ", \\\n\t{ 0 }";
139       level_count[depth]++;
140       depth--;
141     }
142   }
143
144   entry_name = $1; sub(/,$/, "", entry_name);
145   all_items[num_entries++] = entry_name;
146
147   # Construct the element initializer for this tree node.
148   $1 = " " $1;
149   if (NF > 1) {
150     # Check if entry name is followed by a comma.  If it is not, the entry
151     # name is excluded from the initializer.
152     check_str = $1$2;
153     gsub(/[ \t]/, "", check_str);
154     if (index(check_str, entry_name ",") == 0) {
155       $1 = "";
156     }
157   }
158   $1 = ", \\\n\t{" $1; $NF = $NF " }";
159
160   tree_items[depth] = tree_items[depth] $0;
161   level_count[depth]++;
162 }
163
164 indent == 0 && tree_identifier {
165   trees[tree_identifier] = format_items();
166   tree_identifier = "";
167 }
168 END {
169   if (tree_identifier)
170     trees[tree_identifier] = format_items()
171 }
172 indent == 0 { tree_identifier = $1 }
173
174 END {
175   prefix = "\nenum {\n";
176
177   if (opts["strtab"]) {
178     entry_strtab = "\1";
179     bucketsort(sorted_items, all_items);
180     for (i = 0; i < num_entries; i++) {
181       s = sorted_items[i];
182       if ((n = index(entry_strtab, s "\1")) > 0) {
183         entry_offsets[s] = n-1;
184       } else {
185         entry_offsets[s] = length(entry_strtab);
186         entry_strtab = entry_strtab s "\1";
187       }
188     }
189
190     gsub(/\1/, "\"\n\t\"\\0\" \"", entry_strtab);
191     sub(/^"/, "", entry_strtab);
192     sub(/\n[^\n]*$/, ";", entry_strtab);
193     print "\nstatic const char tree_strtab[] =" entry_strtab
194
195     for (item in entry_offsets) {
196       printf "%s\t%s = %d", prefix, item, entry_offsets[item];
197       prefix = ",\n";
198     }
199   }
200
201   for (i in subtree_offsets) {
202     printf "%s\t%s_OFFSET = %d", prefix, i, subtree_offsets[i];
203     prefix = ",\n";
204   }
205   if (!index(prefix, "enum")) {
206     print "\n};";
207   }
208 }
209
210 END {
211   for (tree in trees) {
212     print "\n" trees[tree];
213   }
214 }
215
216 function format_items(s, i)
217 {
218   while (depth > 0) {
219     tree_items[depth] = tree_items[depth] ", \\\n\t{ 0 }";
220     level_count[depth]++;
221     depth--;
222   }
223
224   for (i = 2; tree_items[i]; i++) {
225     level_count[i] += level_count[i-1];
226   }
227
228   for (i in subtree_depth) {
229     subtree_offsets[i] += level_count[subtree_depth[i]-1];
230     delete subtree_depth[i];
231   }
232
233   for (i = 1; tree_items[i]; i++) {
234     s = s tree_items[i];
235     delete tree_items[i];
236     delete level_count[i];
237   }
238
239   sub(/^,/, "", s);
240   return "#define " tree_identifier "_INITIALIZER" s;
241 }
242
243 # bucketsort(dst, src)
244 #
245 # Sort the elements of src by descending string length,
246 # placing them into dst[0] ... dst[n].
247 #
248 # Returns the number of elements.
249 function bucketsort(dst, src, buckets, max, count, i, t)
250 {
251   for (t in src) {
252     i = length(src[t])
253     if (i > max) { max = i }
254     buckets[i]++
255   }
256
257   for (i = max; i > 0; i--) {
258     if (i in buckets) {
259       t = buckets[i]
260       buckets[i] = count
261       count += t
262     }
263   }
264
265   for (t in src) {
266     i = length(t = src[t])
267     dst[buckets[i]++] = t
268   }
269
270   return count
271 }