fiv/tiff-tables.awk

113 lines
2.6 KiB
Awk
Raw Permalink Normal View History

#!/usr/bin/awk -f
BEGIN {
FS = ", *"
print "// Generated by tiff-tables.awk. DO NOT MODIFY."
print ""
print "#ifndef TIFF_TABLES_CONSTANTS_ONLY"
print "#include <stddef.h>"
print "#include <stdint.h>"
print ""
print "struct tiff_value {"
print "\tconst char *name;"
print "\tuint16_t value;"
print "};"
print ""
print "struct tiff_entry {"
print "\tconst char *name;"
print "\tuint16_t tag;"
print "\tstruct tiff_value *values;"
print "};"
print "#endif"
}
{
# 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 "#ifndef TIFF_TABLES_CONSTANTS_ONLY"
print "static struct tiff_entry " \
sectionsnakecase "_entries[] = {" fields "\n\t{}\n};"
print "#endif"
}
}
# 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()
}