#! /bin/sh

# $NetBSD: mknodenames.sh,v 1.6 2018/08/18 03:09:37 kre Exp $

# Use this script however you like, but it would be amazing if
# it has any purpose other than as part of building the shell...

if [ -z "$1" ]; then
	echo "Usage: $0 nodes.h" 1>&2
	exit 1
fi

NODES=$1

test -t 1 && test -z "$2" && exec > nodenames.h

echo "\
/*
 * Automatically generated by $0
 * DO NOT EDIT. Do Not 'cvs add'.
 */
"
echo "#ifndef NODENAMES_H_INCLUDED"
echo "#define NODENAMES_H_INCLUDED"
echo
echo "#ifdef DEBUG"

MAX=$(awk < "$NODES" '
	/#define/ {
		if ($3 > MAX) MAX = $3
	}
	END { print MAX }
')

echo
echo '#ifdef DEFINE_NODENAMES'
echo "STATIC const char * const NodeNames[${MAX} + 1] = {"

grep '^#define' "$NODES" | sort -k3n | while read define name number opt_comment
do
	: ${next:=0}
	while [ "$number" -gt "$next" ]
	do
		echo '	"???",'
		next=$(( next + 1))
	done
	echo '	"'"$name"'",'
	next=$(( number + 1 ))
done

echo "};"
echo '#else'
echo "extern const char * const NodeNames[${MAX} + 1];"
echo '#endif'
echo
echo '#define NODETYPENAME(type) \'
echo '	((unsigned)(type) <= '"${MAX}"' ? NodeNames[(type)] : "??OOR??")'
echo
echo '#define NODETYPE(type)	NODETYPENAME(type), (type)'
echo '#define PRIdsNT		"s(%d)"'
echo
echo '#else /* DEBUG */'
echo
echo '#define NODETYPE(type)	(type)'
echo '#define PRIdsNT		"d"'
echo
echo '#endif /* DEBUG */'
echo
echo '#endif /* !NODENAMES_H_INCLUDED */'
