]> git.draconx.ca Git - dxcommon.git/blob - scripts/gen-strtab.awk
fix-gnulib: Restore compatibility with perl 5.8.
[dxcommon.git] / scripts / gen-strtab.awk
1 #!/bin/awk -f
2 #
3 # Copyright © 2021, 2023 Nick Bowler
4 #
5 # Generate a C string table based on an input string specification file.
6 #
7 # A string table is a single large char single array containing all of
8 # the specified (0-terminated) strings, which is then offset to obtain
9 # the desired string.  By storing these offsets instead of string pointers
10 # into read-only data structures, this can reduce the need for relocation
11 # processing at startup when programs are built in PIC mode.
12 #
13 # The string specification file is processed line by line.  Comment
14 # lines may be included by beginning the line with a # character, which
15 # must be the very first character on the line.  If a comment is encountered,
16 # processing immediately moves on to the next line and the result is as if
17 # the comment line were omitted from the input.
18 #
19 # Options may be used to alter the normal behaviour.  An option is placed
20 # on a line by itself beginning with an @ character, and may appear anywhere
21 # in the input file.  The following options are defined:
22 #
23 #   @nozero
24 #     All strings will have a non-zero offset in the strtab.
25 #
26 #   @macro
27 #     Instead of a variable declaration, the generated header will define an
28 #     object-like macro that can be used as the initializer for a char array.
29 #
30 # A string is defined by beginning a line with one or two & characters, which
31 # must be immediately followed by a C identifier.  Two & characters indicates
32 # a string that should not be translated, as described below.  A nonempty
33 # sequence of whitespace (with at most one newline) separates the identifier
34 # from the beginning of the string itself.  This whitespace is never included
35 # in the output.
36 #
37 # The string is then interpreted as follows:
38 #
39 #   - Leading blanks on each line are ignored.
40 #   - The sequences \\, \a, \b, \t, \n, \v, \f and \r can be entered and
41 #     mean the same as they do in C string literals.  The "\\" sequence
42 #     prevents any special interpretation of the second backslash.
43 #   - Newlines in the input are included in the output, except for the
44 #     where the entire string (including its identifier) are on one line.
45 #   - If this is not desired, a newline which is immediately preceded by an
46 #     unescaped backslash will deleted, along with the backslash.
47 #   - All other backslashes are deleted.  This can be used to prevent special
48 #     handling of whitespace, # or & characters at the beginning of a line.
49 #
50 # Unless the @macro option is specified, the output defines a variable,
51 # strtab, which contains all of the strings, and each identifier in the input
52 # is declared as an emumeration constant whose value is the offset of the
53 # associated string within strtab.  Otherwise, if the @macro option is
54 # specified, no variables are defined and STRTAB_INITIALIZER object-like macro
55 # may be used to initialize a char array with static storage duration.
56 #
57 # Normally, the generated source code wraps strings using the identity macro
58 # N_(x), which has no effect on the resulting data structures but enables tools
59 # such as xgettext to extract translatable strings from the source code.  An
60 # identifier preceded by two ampersands (&&) suppresses this output to allow
61 # a single string table to also contain both translateable strings as well as
62 # ones that should not be translated.
63 #
64 # The object-like macro STRTAB_MAX_OFFSET is defined and expands to the
65 # greatest string offset, suitable for use in #if preprocessing directives.
66 #
67 # License WTFPL2: Do What The Fuck You Want To Public License, version 2.
68 # This is free software: you are free to do what the fuck you want to.
69 # There is NO WARRANTY, to the extent permitted by law.
70
71 END {
72   print "/*"
73   if (FILENAME) {
74     print " * Automatically generated by gen-strtab.awk from " FILENAME
75   } else {
76     print " * Automatically generated by gen-strtab.awk"
77   }
78   print " * Do not edit."
79   print " */"
80 }
81
82 BEGIN {
83   opts["zero"] = 1
84   opts["macro"] = 0
85   collected = ident = ""
86   startline = endline = 0
87   num_vars = 0
88 }
89
90 # Comments
91 NF == 0 || $0 ~ /^[#]/ { next }
92
93 # Options
94 sub(/^@/, "", $0) {
95   if (NF == 1) {
96     orig=$1
97     gsub(/-/, "_", $1);
98     val = !sub(/^no_?/, "", $1);
99     if ($1 in opts) {
100       opts[$1] = val;
101     } else {
102       print "error: unrecognized option: @" orig | "cat 1>&2"
103       exit 1
104     }
105   }
106   next
107 }
108
109 sub(/^[&]/, "") {
110   if (ident) {
111     finish_string_input(strings, ident, collected)
112     vars[num_vars++] = ident
113   }
114
115   current_l10n = !sub(/^[&]/, "", $1);
116   startline = NR
117   ident = $1
118
119   $1 = ""
120   collected = ""
121 }
122
123 ident {
124   sub(/^[ \t]*/, "")
125   if (collected) {
126     collected = collected "\n" $0
127   } else {
128     collected = $0
129   }
130
131   endline = NR
132 }
133
134 END {
135   if (ident) {
136     finish_string_input(strings, ident, collected)
137     vars[num_vars++] = ident
138   }
139 }
140
141 END {
142   strtab = cont = ""
143   strtab_len = 0
144   count = bucketsort(sorted_strings, strings)
145   max = 0
146
147   print "\n#define STR_L10N_(x)"
148   print "#ifndef N_"
149   print "#  define N_(x) x"
150   print "#endif"
151   if (opts["macro"]) {
152     cont = " \\";
153     print "\n#define STRTAB_INITIALIZER" cont;
154   } else {
155     print "\nstatic const char strtab[] =";
156   }
157
158   for (i = 0; i < count; i++) {
159     s = sorted_strings[i]
160     gsub(/\\\\/, "\2\2", s)
161     if ((n = index(strtab "\1", s "\1")) > 0) {
162       offsets[sorted_strings[i]] = real_length(substr(strtab, 1, n-1));
163       if (!(sorted_strings[i] in nol10n))
164         print "\tSTR_L10N_(N_(\"" sorted_strings[i] "\"))" cont;
165     } else if (strtab) {
166       strtab = strtab "\1" s
167       offsets[sorted_strings[i]] = strtab_len + 1
168       strtab_len += real_length(s) + 1
169     } else {
170       strtab = s
171       offsets[sorted_strings[i]] = 0
172       strtab_len += real_length(s)
173     }
174   }
175
176   gsub(/\2/, "\\", strtab);
177   n = split(strtab, split_strtab, "\1");
178   for (i = 1; i <= n; i++) {
179     printf("\t%4s ", i > !!opts["zero"] ? "\"\\0\"" : "");
180
181     if (split_strtab[i] in nol10n) {
182       print "\"" split_strtab[i] "\"" cont;
183     } else {
184       print "N_(\"" split_strtab[i] "\")" cont;
185     }
186   }
187   print "\t\"\"" substr(";", 1, !opts["macro"]);
188
189   print "enum {"
190   for (i = 0; i < num_vars; i++) {
191     sep = (i+1) != num_vars ? "," : ""
192     s = vars[i]
193     o = offsets[strings[s]] + (!opts["zero"])
194     print "\t" s " = " o sep
195     if (o > max) {
196       max = o
197     }
198   }
199   print "};"
200   print "\n#define STRTAB_MAX_OFFSET " max
201 }
202
203 # finish_string_input(strings, ident, val)
204 #
205 # Deal with backslash-escapes and special characters in val, then set
206 # strings[ident] = val.
207 function finish_string_input(strings, ident, val, n, tmpval)
208 {
209   gsub(/\\\\/, "\1\1", val)
210   val = val (endline > startline ? "\n" : "")
211   gsub(/\\\n/, "", val)
212
213   tmpval = ""
214   while ((n = match(val, /\\[^abtnvfr]/)) > 0) {
215     tmpval = tmpval substr(val, 1, n-1)
216     val = substr(val, n+1)
217   }
218   tmpval = tmpval val
219
220   # Escape special characters
221   gsub(/"/, "\\\"", tmpval)
222   gsub(/\t/, "\\t", tmpval)
223   gsub(/\n/, "\\n", tmpval)
224   gsub(/\1/, "\\", tmpval)
225
226   strings[ident] = tmpval
227   if (!current_l10n) {
228     nol10n[tmpval] = 1;
229   }
230 }
231
232 function real_length(s, t)
233 {
234   t = length(s)
235   return t - gsub(/\\.|\2\2/, "&", s)
236 }
237
238 # bucketsort(dst, src)
239 #
240 # Sort the elements of src by descending string length,
241 # placing them into dst[0] ... dst[n].
242 #
243 # Returns the number of elements.
244 function bucketsort(dst, src, buckets, max, count, i, t)
245 {
246   for (t in src) {
247     i = length(src[t])
248     if (i > max) { max = i }
249     buckets[i]++
250   }
251
252   for (i = max; i > 0; i--) {
253     if (i in buckets) {
254       t = buckets[i]
255       buckets[i] = count
256       count += t
257     }
258   }
259
260   for (t in src) {
261     i = length(t = src[t])
262     dst[buckets[i]++] = t
263   }
264
265   return count
266 }