#!/bin/sh -
# Usage: mklayout HEADER... -- KIND NAME [KIND NAME]... < preprocessed > libdash_layout.c
#
# Writes libdash_struct_layout, a table of the size of each named struct or
# union and the offset of every one of its fields, for bindings that mirror
# the layouts by hand (libdash/_dash.py) to check themselves against.
#
# The fields come from the HEADERs as the compiler sees them: stdin is their
# preprocessed text, so conditional fields (e.g., parsefile's lleft) are in
# or out exactly as compiled. A declaration this script can't read (an array,
# a bitfield, a function pointer, several declarators) is an error, not a
# guess.

headers=
while [ $# -gt 0 ] && [ "$1" != -- ]; do
	headers="$headers $1"
	shift
done
if [ $# -eq 0 ]; then
	echo "usage: mklayout HEADER... -- KIND NAME [KIND NAME]..." >&2
	exit 2
fi
shift

exec awk -v headers="$headers" -v types="$*" '
function fail(msg) {
	print "mklayout: " msg > "/dev/stderr"
	failed = 1
	exit 1
}

/^[ \t]*#/ { next }
{ text = text " " $0 }

END {
	if (failed)
		exit 1

	gsub(/[ \t\r\n]+/, " ", text)

	print "/* Generated by mklayout; do not edit. */"
	print ""
	print "#include <stddef.h>"
	nh = split(headers, h, " ")
	for (i = 1; i <= nh; i++)
		print "#include \"" h[i] "\""
	print ""
	print "const struct libdash_layout {"
	print "\tconst char *type;\t/* e.g., \"struct ncmd\" */"
	print "\tconst char *field;\t/* NULL: value is the sizeof type */"
	print "\tsize_t value;\t\t/* otherwise, the offsetof field */"
	print "} libdash_struct_layout[] = {"

	nt = split(types, t, " ")
	if (nt == 0 || nt % 2 != 0)
		fail("expected KIND NAME pairs, got: " types)

	for (i = 1; i <= nt; i += 2) {
		kind = t[i]
		name = t[i + 1]
		type = kind " " name
		if (kind != "struct" && kind != "union")
			fail(type ": KIND must be struct or union")

		if (!match(text, "(^| )" kind " " name " ?\\{"))
			fail(type ": no definition in" headers)
		body = substr(text, RSTART + RLENGTH)
		if (!match(body, /\}/))
			fail(type ": unterminated definition")
		body = substr(body, 1, RSTART - 1)
		if (body ~ /\{/)
			fail(type ": nested definitions are not supported")

		print "\t{ \"" type "\", NULL, sizeof (" type ") },"

		nd = split(body, decl, ";")
		for (j = 1; j <= nd; j++) {
			d = decl[j]
			gsub(/^ +| +$/, "", d)
			if (d == "")
				continue
			if (d ~ /[^A-Za-z0-9_ *]/)
				fail(type ": cannot read declaration \"" d ";\"")
			if (!match(d, /[A-Za-z_][A-Za-z0-9_]*$/) || RSTART == 1)
				fail(type ": cannot read declaration \"" d ";\"")
			field = substr(d, RSTART)
			print "\t{ \"" type "\", \"" field "\", offsetof (" type ", " field ") },"
		}
	}

	print "\t{ NULL, NULL, 0 }"
	print "};"
}
'
