fiv/tiff-tables.awk
Přemysl Eric Janouch 81145064de
Generate TIFF structs/enums from a text file
This is to make the tables much easier to maintain.
2022-06-10 02:18:14 +02:00

95 lines
2.1 KiB
Awk
Executable File

#!/usr/bin/awk -f
BEGIN {
FS = ", *"
print "// Generated by tiff-tables.awk. DO NOT MODIFY."
}
{
# Remember and strip consecutive comments.
if (match($0, /#/))
comment[++comments] = substr($0, RSTART + 1)
else if (!/[[:space:]]/)
comments = 0
sub(/#.*$/, "")
sub(/[[:space:]]*$/, "")
}
# Converts arbitrary strings to C identifiers (when running in the C locale).
function identifize(s) {
# Regard parenthesised text as comments.
while (match(s, /[[:space:]]\([^)]+\)/)) {
comment[++comments] = substr(s, RSTART, RLENGTH)
s = substr(s, 1, RSTART - 1) substr(s, RSTART + RLENGTH)
}
# Capitalize words (toupper is POSIX), removing spaces and dashes between.
while (match(s, /[-[:space:]]./)) {
s = substr(s, 1, RSTART - 1) \
toupper(substr(s, RSTART + 1, 1)) \
substr(s, RSTART + RLENGTH)
}
# Replace any remaining non-identifier characters with underscores.
gsub(/[^[:alnum:]]/, "_", s)
return s
}
function flushcomments(prefix, i, acc) {
for (i = 1; i <= comments; i++)
acc = acc prefix comment[i] "\n"
comments = 0
return acc
}
function flushvalues() {
if (values) {
allvalues = allvalues "enum " fieldname " {\n" values "};\n\n"
values = ""
fields = fields "\n\t\t{}\n\t}},"
} else if (fields) {
fields = fields " NULL},"
}
}
function flushsection() {
if (section) {
flushvalues()
print "};\n\n" allvalues "static struct tiff_entry " \
sectionsnakecase "_entries[] = {" fields "\n\t{}\n};"
}
}
# Section marker
/^= / {
flushsection()
section = identifize(substr($0, 3))
sectionsnakecase = tolower(substr($0, 3))
gsub(/[^[:alnum:]]/, "_", sectionsnakecase)
fields = ""
allvalues = ""
print "\n" flushcomments("//") "enum {"
}
# Field
section && /^[^\t=]/ {
flushvalues()
fieldname = section "_" identifize($2)
fields = fields "\n\t{\"" $2 "\", " fieldname ","
print flushcomments("\t//") "\t" fieldname " = " $1 ","
}
# Value
section && /^\t/ {
sub(/^\t*/, "")
valuename = fieldname "_" identifize($2)
if (!values)
fields = fields " (struct tiff_value[]) {"
values = values flushcomments("\t//") "\t" valuename " = " $1 ",\n"
fields = fields "\n\t\t{\"" $2 "\", " valuename "},"
}
END {
flushsection()
}