 - Add the character "E" to the understood lock types.  This means
   the VOP requires an exclusive lock.

Sponsored by:	Isilon Systems, Inc.

#!/usr/bin/awk -f

#-
# Copyright (c) 1992, 1993
#	The Regents of the University of California.  All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
# 4. Neither the name of the University nor the names of its contributors
#    may be used to endorse or promote products derived from this software
#    without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.

#
#	@(#)vnode_if.sh	8.1 (Berkeley) 6/10/93
# $FreeBSD$
#
# Script to produce VFS front-end sugar.
#
# usage: vnode_if.awk <srcfile> [-c | -h]
#	(where <srcfile> is currently /sys/kern/vnode_if.src)
#

function usage()
{
	print "usage: vnode_if.awk <srcfile> [-c|-h|-p|-q]";
	exit 1;
}

function die(msg, what)
{
	printf msg "\n", what > "/dev/stderr";
	exit 1;
}

function t_spc(type)
{
	# Append a space if the type is not a pointer
	return (type ~ /\*$/) ? type : type " ";
}

# These are just for convenience ...
function printc(s) {print s > cfile;}
function printh(s) {print s > hfile;}
function printp(s) {print s > pfile;}
function printq(s) {print s > qfile;}

function add_debug_code(name, arg, pos, ind)
{
	if (arg == "vpp")
		star = "*";
	else
		star = "";
	if (lockdata[name, arg, pos] && (lockdata[name, arg, pos] != "-")) {
		if (arg ~ /^\*/) {
			printc(ind"if ("substr(arg, 2)" != NULL) {");
		}
		printc(ind"ASSERT_VI_UNLOCKED("star"a->a_"arg", \""uname"\");");
		# Add assertions for locking
		if (lockdata[name, arg, pos] == "L")
			printc(ind"ASSERT_VOP_LOCKED(" star "a->a_"arg", \""uname"\");");
		else if (lockdata[name, arg, pos] == "U")
			printc(ind"ASSERT_VOP_UNLOCKED(" star "a->a_"arg", \""uname"\");");
		else if (lockdata[name, arg, pos] == "E")
			printc(ind"ASSERT_VOP_ELOCKED(" star "a->a_"arg", \""uname"\");");
		else if (0) {
			# XXX More checks!
		}
		if (arg ~ /^\*/) {
			printc("ind}");
		}
	}
}

function add_debug_pre(name)
{
	if (lockdata[name, "pre"]) {
		printc("#ifdef	DEBUG_VFS_LOCKS");
		printc("\t"lockdata[name, "pre"]"(a);");
		printc("#endif");
	}
}

function add_debug_post(name)
{
	if (lockdata[name, "post"]) {
		printc("#ifdef	DEBUG_VFS_LOCKS");
		printc("\t"lockdata[name, "post"]"(a, rc);");
		printc("#endif");
	}
}

function find_arg_with_type (type)
{
	for (jj = 0; jj < numargs; jj++) {
		if (types[jj] == type) {
			return "VOPARG_OFFSETOF(struct " \
			    name "_args,a_" args[jj] ")";
		}
	}

	return "VDESC_NO_OFFSET";
}

BEGIN{

# Process the command line
for (i = 1; i < ARGC; i++) {
	arg = ARGV[i];
	if (arg !~ /^-[chpq]+$/ && arg !~ /\.src$/)
		usage();
	if (arg ~ /^-.*c/)
		cfile = "vnode_if.c";
	if (arg ~ /^-.*h/)
		hfile = "vnode_if.h";
	if (arg ~ /^-.*p/)
		pfile = "vnode_if_newproto.h";
	if (arg ~ /^-.*q/)
		qfile = "vnode_if_typedef.h";
	if (arg ~ /\.src$/)
		srcfile = arg;
}
ARGC = 1;

if (!cfile && !hfile && !pfile && !qfile)
	exit 0;

if (!srcfile)
	usage();

common_head = \
    "/*\n" \
    " * This file is produced automatically.\n" \
    " * Do not modify anything in here by hand.\n" \
    " *\n" \
    " * Created from $FreeBSD$\n" \
    " */\n" \
    "\n";

if (pfile) {
	printp(common_head)
	printp("struct vop_vector {")
	printp("\tstruct vop_vector\t*vop_default;")
	printp("\tvop_bypass_t\t*vop_bypass;")
}

if (qfile) {
	printq(common_head)
}

if (hfile) {
	printh(common_head "extern struct vnodeop_desc vop_default_desc;");
	printh("#include \"vnode_if_typedef.h\"")
	printh("#include \"vnode_if_newproto.h\"")
}

if (cfile) {
	printc(common_head \
	    "#include <sys/param.h>\n" \
	    "#include <sys/systm.h>\n" \
	    "#include <sys/vnode.h>\n" \
	    "#include <sys/systm.h>\n" \
	    "\n" \
	    "struct vnodeop_desc vop_default_desc = {\n" \
	    "	\"default\",\n" \
	    "	0,\n" \
	    "	(void *)(uintptr_t)vop_panic,\n" \
	    "	NULL,\n" \
	    "	VDESC_NO_OFFSET,\n" \
	    "	VDESC_NO_OFFSET,\n" \
	    "	VDESC_NO_OFFSET,\n" \
	    "	VDESC_NO_OFFSET,\n" \
	    "	NULL,\n" \
	    "};\n");
}

while ((getline < srcfile) > 0) {
	if (NF == 0)
		continue;
	if ($1 ~ /^#%/) {
		if (NF != 6  ||  $1 != "#%"  || \
		    $2 !~ /^[a-z]+$/  ||  $3 !~ /^[a-z]+$/  || \
		    $4 !~ /^.$/  ||  $5 !~ /^.$/  ||  $6 !~ /^.$/)
			continue;
		lockdata["vop_" $2, $3, "Entry"] = $4;
		lockdata["vop_" $2, $3, "OK"]    = $5;
		lockdata["vop_" $2, $3, "Error"] = $6;
		continue;
	}

	if ($1 ~ /^#!/) {
		if (NF != 4 || $1 != "#!")
			continue;
		if ($3 != "pre" && $3 != "post")
			continue;
		lockdata["vop_" $2, $3] = $4;
		continue;
	}
	if ($1 ~ /^#/)
		continue;

	# Get the function name.
	name = $1;
	uname = toupper(name);

	# Start constructing a ktrpoint string
	ctrstr = "\"" uname;
	# Get the function arguments.
	for (numargs = 0; ; ++numargs) {
		if ((getline < srcfile) <= 0) {
			die("Unable to read through the arguments for \"%s\"",
			    name);
		}
		if ($1 ~ /^\};/)
			break;

		# Delete comments, if any.
		gsub (/\/\*.*\*\//, "");

		# Condense whitespace and delete leading/trailing space.
		gsub(/[[:space:]]+/, " ");
		sub(/^ /, "");
		sub(/ $/, "");

		# Pick off direction.
		if ($1 != "INOUT" && $1 != "IN" && $1 != "OUT")
			die("No IN/OUT direction for \"%s\".", $0);
		dirs[numargs] = $1;
		sub(/^[A-Z]* /, "");

		if ((reles[numargs] = $1) == "WILLRELE")
			sub(/^[A-Z]* /, "");
		else
			reles[numargs] = "WONTRELE";

		# kill trailing ;
		if (sub(/;$/, "") < 1)
			die("Missing end-of-line ; in \"%s\".", $0);

		# pick off variable name
		if ((argp = match($0, /[A-Za-z0-9_]+$/)) < 1)
			die("Missing var name \"a_foo\" in \"%s\".", $0);
		args[numargs] = substr($0, argp);
		$0 = substr($0, 1, argp - 1);

		# what is left must be type
		# remove trailing space (if any)
		sub(/ $/, "");
		types[numargs] = $0;

		# We can do a maximum of 6 arguments to CTR*
		if (numargs <= 6) {
			if (numargs == 0)
				ctrstr = ctrstr "(" args[numargs];
			else
				ctrstr = ctrstr ", " args[numargs];
			if (types[numargs] ~ /\*/)
				ctrstr = ctrstr " 0x%lX";
			else
				ctrstr = ctrstr " %ld";
		}
	}
	if (numargs > 6)
		ctrargs = 6;
	else
		ctrargs = numargs;
	ctrstr = "\tCTR" ctrargs "(KTR_VOP,\n\t    " ctrstr ")\",\n\t    ";
	ctrstr = ctrstr "a->a_" args[0];
	for (i = 1; i < ctrargs; ++i)
		ctrstr = ctrstr ", a->a_" args[i];
	ctrstr = ctrstr ");";

	if (pfile) {
		printp("\t"name"_t\t*"name";")
	}
	if (qfile) {
		printq("struct "name"_args;")
		printq("typedef int "name"_t(struct "name"_args *);\n")
	}

	if (hfile) {
		# Print out the vop_F_args structure.
		printh("struct "name"_args {\n\tstruct vop_generic_args a_gen;");
		for (i = 0; i < numargs; ++i)
			printh("\t" t_spc(types[i]) "a_" args[i] ";");
		printh("};");
		printh("");

		# Print out extern declaration.
		printh("extern struct vnodeop_desc " name "_desc;");
		printh("");

		# Print out function prototypes.
		printh("int " uname "_AP(struct " name "_args *);");
		printh("int " uname "_APV(struct vop_vector *vop, struct " name "_args *);");
		printh("");
		printh("static __inline int " uname "(");
		for (i = 0; i < numargs; ++i) {
			printh("\t" t_spc(types[i]) args[i] \
			    (i < numargs - 1 ? "," : ")"));
		}
		printh("{");
		printh("\tstruct " name "_args a;");
		printh("");
		printh("\ta.a_gen.a_desc = &" name "_desc;");
		for (i = 0; i < numargs; ++i)
			printh("\ta.a_" args[i] " = " args[i] ";");
		printh("\treturn (" uname "_APV("args[0]"->v_op, &a));");
		printh("}");

		printh("");
	}

	if (cfile) {
		# Print out the vop_F_vp_offsets structure.  This all depends
		# on naming conventions and nothing else.
		printc("static int " name "_vp_offsets[] = {");
		# as a side effect, figure out the releflags
		releflags = "";
		vpnum = 0;
		for (i = 0; i < numargs; i++) {
			if (types[i] == "struct vnode *") {
				printc("\tVOPARG_OFFSETOF(struct " name \
				    "_args,a_" args[i] "),");
				if (reles[i] == "WILLRELE") {
					releflags = releflags \
					    "|VDESC_VP" vpnum "_WILLRELE";
				}
				vpnum++;
			}
		}

		sub(/^\|/, "", releflags);
		printc("\tVDESC_NO_OFFSET");
		printc("};");

		# Print out function.
		printc("\nint\n" uname "_AP(struct " name "_args *a)");
		printc("{");
		printc("");
		printc("\treturn(" uname "_APV(a->a_" args[0] "->v_op, a));");
		printc("}");
		printc("\nint\n" uname "_APV(struct vop_vector *vop, struct " name "_args *a)");
		printc("{");
		printc("\tint rc;");
		printc("");
		printc("\tVNASSERT(a->a_gen.a_desc == &" name "_desc, a->a_" args[0]",");
		printc("\t    (\"Wrong a_desc in " name "(%p, %p)\", a->a_" args[0]", a));");
		printc("\twhile(vop != NULL && \\");
		printc("\t    vop->"name" == NULL && vop->vop_bypass == NULL)")
		printc("\t\tvop = vop->vop_default;")
		printc("\tVNASSERT(vop != NULL, a->a_" args[0]", (\"No "name"(%p, %p)\", a->a_" args[0]", a));")
		for (i = 0; i < numargs; ++i)
			add_debug_code(name, args[i], "Entry", "\t");
		add_debug_pre(name);
		printc("\tif (vop->"name" != NULL)")
		printc("\t\trc = vop->"name"(a);")
		printc("\telse")
		printc("\t\trc = vop->vop_bypass(&a->a_gen);")
		printc(ctrstr);
		printc("\tif (rc == 0) {");
		for (i = 0; i < numargs; ++i)
			add_debug_code(name, args[i], "OK", "\t\t");
		printc("\t} else {");
		for (i = 0; i < numargs; ++i)
			add_debug_code(name, args[i], "Error", "\t\t");
		printc("\t}");
		add_debug_post(name);
		printc("\treturn (rc);");
		printc("}\n");

		# Print out the vnodeop_desc structure.
		printc("struct vnodeop_desc " name "_desc = {");
		# printable name
		printc("\t\"" name "\",");
		# flags
		vppwillrele = "";
		for (i = 0; i < numargs; i++) {
			if (types[i] == "struct vnode **" && \
			    reles[i] == "WILLRELE") {
				vppwillrele = "|VDESC_VPP_WILLRELE";
			}
		}

		if (!releflags)
			releflags = "0";
		printc("\t" releflags vppwillrele ",");

		# function to call
		printc("\t(void*)(uintptr_t)" uname "_AP,");
		# vp offsets
		printc("\t" name "_vp_offsets,");
		# vpp (if any)
		printc("\t" find_arg_with_type("struct vnode **") ",");
		# cred (if any)
		printc("\t" find_arg_with_type("struct ucred *") ",");
		# thread (if any)
		printc("\t" find_arg_with_type("struct thread *") ",");
		# componentname
		printc("\t" find_arg_with_type("struct componentname *") ",");
		# transport layer information
		printc("\tNULL,\n};\n");
	}
}

if (pfile)
	printp("};")

if (hfile)
	close(hfile);
if (cfile)
	close(cfile);
if (pfile)
	close(pfile);
close(srcfile);

exit 0;

}

#!/usr/bin/awk -f

#-
# Copyright (c) 1992, 1993
#	The Regents of the University of California.  All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
# 4. Neither the name of the University nor the names of its contributors
#    may be used to endorse or promote products derived from this software
#    without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.

#
#	@(#)vnode_if.sh	8.1 (Berkeley) 6/10/93
# $FreeBSD$
#
# Script to produce VFS front-end sugar.
#
# usage: vnode_if.awk <srcfile> [-c | -h]
#	(where <srcfile> is currently /sys/kern/vnode_if.src)
#

function usage()
{
	print "usage: vnode_if.awk <srcfile> [-c|-h|-p|-q]";
	exit 1;
}

function die(msg, what)
{
	printf msg "\n", what > "/dev/stderr";
	exit 1;
}

function t_spc(type)
{
	# Append a space if the type is not a pointer
	return (type ~ /\*$/) ? type : type " ";
}

# These are just for convenience ...
function printc(s) {print s > cfile;}
function printh(s) {print s > hfile;}
function printp(s) {print s > pfile;}
function printq(s) {print s > qfile;}

function add_debug_code(name, arg, pos, ind)
{
	if (arg == "vpp")
		star = "*";
	else
		star = "";
	if (lockdata[name, arg, pos] && (lockdata[name, arg, pos] != "-")) {
		if (arg ~ /^\*/) {
			printc(ind"if ("substr(arg, 2)" != NULL) {");
		}
		printc(ind"ASSERT_VI_UNLOCKED("star"a->a_"arg", \""uname"\");");
		# Add assertions for locking
		if (lockdata[name, arg, pos] == "L")
			printc(ind"ASSERT_VOP_LOCKED(" star "a->a_"arg", \""uname"\");");
		else if (lockdata[name, arg, pos] == "U")
			printc(ind"ASSERT_VOP_UNLOCKED(" star "a->a_"arg", \""uname"\");");
		else if (0) {
			# XXX More checks!
		}
		if (arg ~ /^\*/) {
			printc("ind}");
		}
	}
}

function add_debug_pre(name)
{
	if (lockdata[name, "pre"]) {
		printc("#ifdef	DEBUG_VFS_LOCKS");
		printc("\t"lockdata[name, "pre"]"(a);");
		printc("#endif");
	}
}

function add_debug_post(name)
{
	if (lockdata[name, "post"]) {
		printc("#ifdef	DEBUG_VFS_LOCKS");
		printc("\t"lockdata[name, "post"]"(a, rc);");
		printc("#endif");
	}
}

function find_arg_with_type (type)
{
	for (jj = 0; jj < numargs; jj++) {
		if (types[jj] == type) {
			return "VOPARG_OFFSETOF(struct " \
			    name "_args,a_" args[jj] ")";
		}
	}

	return "VDESC_NO_OFFSET";
}

BEGIN{

# Process the command line
for (i = 1; i < ARGC; i++) {
	arg = ARGV[i];
	if (arg !~ /^-[chpq]+$/ && arg !~ /\.src$/)
		usage();
	if (arg ~ /^-.*c/)
		cfile = "vnode_if.c";
	if (arg ~ /^-.*h/)
		hfile = "vnode_if.h";
	if (arg ~ /^-.*p/)
		pfile = "vnode_if_newproto.h";
	if (arg ~ /^-.*q/)
		qfile = "vnode_if_typedef.h";
	if (arg ~ /\.src$/)
		srcfile = arg;
}
ARGC = 1;

if (!cfile && !hfile && !pfile && !qfile)
	exit 0;

if (!srcfile)
	usage();

common_head = \
    "/*\n" \
    " * This file is produced automatically.\n" \
    " * Do not modify anything in here by hand.\n" \
    " *\n" \
    " * Created from $FreeBSD$\n" \
    " */\n" \
    "\n";

if (pfile) {
	printp(common_head)
	printp("struct vop_vector {")
	printp("\tstruct vop_vector\t*vop_default;")
	printp("\tvop_bypass_t\t*vop_bypass;")
}

if (qfile) {
	printq(common_head)
}

if (hfile) {
	printh(common_head "extern struct vnodeop_desc vop_default_desc;");
	printh("#include \"vnode_if_typedef.h\"")
	printh("#include \"vnode_if_newproto.h\"")
}

if (cfile) {
	printc(common_head \
	    "#include <sys/param.h>\n" \
	    "#include <sys/systm.h>\n" \
	    "#include <sys/vnode.h>\n" \
	    "#include <sys/systm.h>\n" \
	    "\n" \
	    "struct vnodeop_desc vop_default_desc = {\n" \
	    "	\"default\",\n" \
	    "	0,\n" \
	    "	(void *)(uintptr_t)vop_panic,\n" \
	    "	NULL,\n" \
	    "	VDESC_NO_OFFSET,\n" \
	    "	VDESC_NO_OFFSET,\n" \
	    "	VDESC_NO_OFFSET,\n" \
	    "	VDESC_NO_OFFSET,\n" \
	    "	NULL,\n" \
	    "};\n");
}

while ((getline < srcfile) > 0) {
	if (NF == 0)
		continue;
	if ($1 ~ /^#%/) {
		if (NF != 6  ||  $1 != "#%"  || \
		    $2 !~ /^[a-z]+$/  ||  $3 !~ /^[a-z]+$/  || \
		    $4 !~ /^.$/  ||  $5 !~ /^.$/  ||  $6 !~ /^.$/)
			continue;
		lockdata["vop_" $2, $3, "Entry"] = $4;
		lockdata["vop_" $2, $3, "OK"]    = $5;
		lockdata["vop_" $2, $3, "Error"] = $6;
		continue;
	}

	if ($1 ~ /^#!/) {
		if (NF != 4 || $1 != "#!")
			continue;
		if ($3 != "pre" && $3 != "post")
			continue;
		lockdata["vop_" $2, $3] = $4;
		continue;
	}
	if ($1 ~ /^#/)
		continue;

	# Get the function name.
	name = $1;
	uname = toupper(name);

	# Start constructing a ktrpoint string
	ctrstr = "\"" uname;
	# Get the function arguments.
	for (numargs = 0; ; ++numargs) {
		if ((getline < srcfile) <= 0) {
			die("Unable to read through the arguments for \"%s\"",
			    name);
		}
		if ($1 ~ /^\};/)
			break;

		# Delete comments, if any.
		gsub (/\/\*.*\*\//, "");

		# Condense whitespace and delete leading/trailing space.
		gsub(/[[:space:]]+/, " ");
		sub(/^ /, "");
		sub(/ $/, "");

		# Pick off direction.
		if ($1 != "INOUT" && $1 != "IN" && $1 != "OUT")
			die("No IN/OUT direction for \"%s\".", $0);
		dirs[numargs] = $1;
		sub(/^[A-Z]* /, "");

		if ((reles[numargs] = $1) == "WILLRELE")
			sub(/^[A-Z]* /, "");
		else
			reles[numargs] = "WONTRELE";

		# kill trailing ;
		if (sub(/;$/, "") < 1)
			die("Missing end-of-line ; in \"%s\".", $0);

		# pick off variable name
		if ((argp = match($0, /[A-Za-z0-9_]+$/)) < 1)
			die("Missing var name \"a_foo\" in \"%s\".", $0);
		args[numargs] = substr($0, argp);
		$0 = substr($0, 1, argp - 1);

		# what is left must be type
		# remove trailing space (if any)
		sub(/ $/, "");
		types[numargs] = $0;

		# We can do a maximum of 6 arguments to CTR*
		if (numargs <= 6) {
			if (numargs == 0)
				ctrstr = ctrstr "(" args[numargs];
			else
				ctrstr = ctrstr ", " args[numargs];
			if (types[numargs] ~ /\*/)
				ctrstr = ctrstr " 0x%lX";
			else
				ctrstr = ctrstr " %ld";
		}
	}
	if (numargs > 6)
		ctrargs = 6;
	else
		ctrargs = numargs;
	ctrstr = "\tCTR" ctrargs "(KTR_VOP,\n\t    " ctrstr ")\",\n\t    ";
	ctrstr = ctrstr "a->a_" args[0];
	for (i = 1; i < ctrargs; ++i)
		ctrstr = ctrstr ", a->a_" args[i];
	ctrstr = ctrstr ");";

	if (pfile) {
		printp("\t"name"_t\t*"name";")
	}
	if (qfile) {
		printq("struct "name"_args;")
		printq("typedef int "name"_t(struct "name"_args *);\n")
	}

	if (hfile) {
		# Print out the vop_F_args structure.
		printh("struct "name"_args {\n\tstruct vop_generic_args a_gen;");
		for (i = 0; i < numargs; ++i)
			printh("\t" t_spc(types[i]) "a_" args[i] ";");
		printh("};");
		printh("");

		# Print out extern declaration.
		printh("extern struct vnodeop_desc " name "_desc;");
		printh("");

		# Print out function prototypes.
		printh("int " uname "_AP(struct " name "_args *);");
		printh("int " uname "_APV(struct vop_vector *vop, struct " name "_args *);");
		printh("");
		printh("static __inline int " uname "(");
		for (i = 0; i < numargs; ++i) {
			printh("\t" t_spc(types[i]) args[i] \
			    (i < numargs - 1 ? "," : ")"));
		}
		printh("{");
		printh("\tstruct " name "_args a;");
		printh("");
		printh("\ta.a_gen.a_desc = &" name "_desc;");
		for (i = 0; i < numargs; ++i)
			printh("\ta.a_" args[i] " = " args[i] ";");
		printh("\treturn (" uname "_APV("args[0]"->v_op, &a));");
		printh("}");

		printh("");
	}

	if (cfile) {
		# Print out the vop_F_vp_offsets structure.  This all depends
		# on naming conventions and nothing else.
		printc("static int " name "_vp_offsets[] = {");
		# as a side effect, figure out the releflags
		releflags = "";
		vpnum = 0;
		for (i = 0; i < numargs; i++) {
			if (types[i] == "struct vnode *") {
				printc("\tVOPARG_OFFSETOF(struct " name \
				    "_args,a_" args[i] "),");
				if (reles[i] == "WILLRELE") {
					releflags = releflags \
					    "|VDESC_VP" vpnum "_WILLRELE";
				}
				vpnum++;
			}
		}

		sub(/^\|/, "", releflags);
		printc("\tVDESC_NO_OFFSET");
		printc("};");

		# Print out function.
		printc("\nint\n" uname "_AP(struct " name "_args *a)");
		printc("{");
		printc("");
		printc("\treturn(" uname "_APV(a->a_" args[0] "->v_op, a));");
		printc("}");
		printc("\nint\n" uname "_APV(struct vop_vector *vop, struct " name "_args *a)");
		printc("{");
		printc("\tint rc;");
		printc("");
		printc("\tVNASSERT(a->a_gen.a_desc == &" name "_desc, a->a_" args[0]",");
		printc("\t    (\"Wrong a_desc in " name "(%p, %p)\", a->a_" args[0]", a));");
		printc("\twhile(vop != NULL && \\");
		printc("\t    vop->"name" == NULL && vop->vop_bypass == NULL)")
		printc("\t\tvop = vop->vop_default;")
		printc("\tVNASSERT(vop != NULL, a->a_" args[0]", (\"No "name"(%p, %p)\", a->a_" args[0]", a));")
		for (i = 0; i < numargs; ++i)
			add_debug_code(name, args[i], "Entry", "\t");
		add_debug_pre(name);
		printc("\tif (vop->"name" != NULL)")
		printc("\t\trc = vop->"name"(a);")
		printc("\telse")
		printc("\t\trc = vop->vop_bypass(&a->a_gen);")
		printc(ctrstr);
		printc("\tif (rc == 0) {");
		for (i = 0; i < numargs; ++i)
			add_debug_code(name, args[i], "OK", "\t\t");
		printc("\t} else {");
		for (i = 0; i < numargs; ++i)
			add_debug_code(name, args[i], "Error", "\t\t");
		printc("\t}");
		add_debug_post(name);
		printc("\treturn (rc);");
		printc("}\n");

		# Print out the vnodeop_desc structure.
		printc("struct vnodeop_desc " name "_desc = {");
		# printable name
		printc("\t\"" name "\",");
		# flags
		vppwillrele = "";
		for (i = 0; i < numargs; i++) {
			if (types[i] == "struct vnode **" && \
			    reles[i] == "WILLRELE") {
				vppwillrele = "|VDESC_VPP_WILLRELE";
			}
		}

		if (!releflags)
			releflags = "0";
		printc("\t" releflags vppwillrele ",");

		# function to call
		printc("\t(void*)(uintptr_t)" uname "_AP,");
		# vp offsets
		printc("\t" name "_vp_offsets,");
		# vpp (if any)
		printc("\t" find_arg_with_type("struct vnode **") ",");
		# cred (if any)
		printc("\t" find_arg_with_type("struct ucred *") ",");
		# thread (if any)
		printc("\t" find_arg_with_type("struct thread *") ",");
		# componentname
		printc("\t" find_arg_with_type("struct componentname *") ",");
		# transport layer information
		printc("\tNULL,\n};\n");
	}
}

if (pfile)
	printp("};")

if (hfile)
	close(hfile);
if (cfile)
	close(cfile);
if (pfile)
	close(pfile);
close(srcfile);

exit 0;

}


Revert "Update min/max length to be inclusive"

This reverts commit 29ea83f7cd7440be605244a9ac75ecd09b903439.

#!/usr/bin/awk -F, -f

BEGIN {
    FS=","
    print "#!/usr/bin/awk -F, -f" RS

    print "# generated by: awk-csvalid https://github.com/tesera/awk-csvalid" RS
    print "# awk-csvalid csv toolset generator: https://github.com/tesera/awk-csvalid"
    print "# usage:"
    print "#    validate:     awk -f action=validate validator.awk > violations.txt"
    print "#    create table: awk -v action=table -f validator.awk | psql afgo_dev"
    print "#    sanitize csv: awk -v action=sanitize -f validator.awk > sanitized.csv"
    print "#    insert sql:   awk -v action=insert -f validator.awk | psql afgo_dev" RS
    print "# awk is a simple unix text file parser: http://www.gnu.org/software/gawk/manual/gawk.html"
    print "# awk primer:"
    print "#    NR = number/index current record"
    print "#    RS = record seperator new line i.e. \\n"
    print "#    FS = field seperator i.e. ,"
    print "#    /pattern/ { expression } = if pattern is truthy run expression" RS

    print "BEGIN {"
    print "    FS=\",\"; OFS=\",\"; err_count=0; cats[\"na\"]=0;"
    print "    if(!action) action = \"validate\""
    print "    summary_header=\"file_name,field_name,rule,message,violation_count\""
    print "    CSVFILENAME = CSVFILENAME ? CSVFILENAME : FILENAME"
    print "    FPAT = \"([^,]*)|(\\\"[^\\\"]+\\\")\""
    print "}" RS

    print "# builtin helper functions"
    print "function eql(x,y) {v=1; for (i in x) v=(v&&x[i]==y[i]); return v;}"
    print "function are_headers_valid(valid_headers) { v=0; split($0, h, \",\"); split(valid_headers, vh, \"|\"); return eql(h, vh); }"
    print "function is_unique(i, val) { if (vals[i,val]) { return 0; } else { vals[i,val] = 1; return 1; } }"
    print "function is_numeric(x){ return(x==x+0) }"
    print "function print_cats(categories) { for (category in categories) { if (categories[category]) print \"      \" category \": \" categories[category]; } }"
    print "function log_err(cat) { cats[cat]++; err_count++; }"
    print RS
    print "#get rid of the evil windows cr"
    print "{ sub(\"\\r$\", \"\") }"
    print RS
    print "{"
    print "     for (i = 1; i <= NF; i++) {"
    print "         if (substr($i, 1, 1) == \"\\\"\") {"
    print "             len = length($i)"
    print "             $i = substr($i, 2, len - 2)"
    print "         }"
    print "     }"
    print "}"
    print RS
}

# BUILD OPTIONS MAP
$1 == "option" {
    options[$2]=$3;
}

# RENDER PFKEY CHECK
$1 == "file" {
    file_options[$2]=$3;
    if ($2 == "pkey") {
        pkeys=$3
        gsub(/\|/, " \"-\" ", pkeys)
        pkeycheck="action ~ /validate/ && NR > 1 { pkey=" pkeys "; if(keys[pkey]) { if (dupkeys[pkey]) dupkeys[pkey]++; else dupkeys[pkey] = 1 } else { keys[pkey] = NR } }"
    }
}

# RENDER HEADERS CHECK
$1 == "headers" && $2 == "names" {
    split($3, headers, "|")
    print "# make header index/map"
    print "NR > 1 {"
    print "field_width = " length(headers)
    for (i in headers) {
        header_name = headers[i]
        header_index[header_name] = i
        print "    " headers[i]  "=$" i
    }

    print "}" RS
    print "# awk rules based on user csv ruleset"
    print "NR == 1 && action == \"validate\" { headers=\"" $3 "\"; if (!are_headers_valid(headers)) { gsub(/\\|/, FS, headers); print RS \"INVALID HEADERS IN \" CSVFILENAME RS \"WAS: \" RS $0 RS \"EXPECTED:\" RS headers RS; exit 0; } }"
    print "NR == 1 && action == \"validate:summary\" { headers=\"" $3 "\"; if (!are_headers_valid(headers)) { violations[CSVFILENAME FS \"headers\" FS  \"names\" FS \"csv headers are invalid\" FS \"error\"]=1; exit 0; } }"
    print pkeycheck
    cat = "error"
    test = "NF != field_width"
    msg = "row \" NR \" in \" CSVFILENAME \" has \" NF \" columns and \" field_width \" was expected"
    mini_msg = "row \" NR \" has an invalid column count"
    rule_type = "invalid-column-count"
    # print "action ~ /^validate/ && NR > 1 { if(NF != field_width) { print \"row \" NR \" in \" CSVFILENAME \" has \" NF \" records and \" field_width \" was expected\"; next;} }"
}

{
    # SET DEFAULTS IF NOT PASSED IN VIA RULES
    defaults["mode"]    = "text"
    defaults["summary"] = "true"
    defaults["dcat"]    = "warning"
    for (option in defaults) {
        if (!options[option]) options[option] = defaults[option]
    }
}

# RENDER VALUE CHECKS
$1 == "field" {

    # PARSE RULE FIELDS
    rule_type     = $2
    split($3,params," ")
    field         = params[1]
    cat           = params[3]
    field_index   = header_index[field]
    test          = ""
    msg           = ""

    # BUILD VIOLATION TEST
    if (rule_type == "type") {
        type = params[2]

        if (type ~ /^integer|number$/) {
            cat       = "error"
            test      = field " && !is_numeric(" field ")"
            msg       = "Field " field " in \" CSVFILENAME \" line \" NR \" should be a numeric but was \" " field " \" "
        }

    } else if (rule_type == "required") {
        req = params[2]

        if (req == "true") {
            test        = field " == \"\""
            mini_msg    = "value is required but was empty"
            msg         = "Field " field " in \" CSVFILENAME \" line \" NR \" is required"
        } else if (req != "false") {
            test        = req " && " field " == \"\""
            mini_msg    = "value is required if " req
            msg         = "Field " field " in \" CSVFILENAME \" line \" NR \" is required if " req
        }

    } else if (rule_type == "unique") {
        cat         = "error"
        test        = "!is_unique(" field ")"
        mini_msg    = "value should be unique but had duplicates"
        msg         = "Field " field " in \" CSVFILENAME \" line \" NR \" is a duplicate and should be unique"

    } else if (rule_type ~ /^minimum|maximum$/) {
        comparator  = $2 == "maximum" ? ">" : "<"
        limit       = params[2]
        term        = $2 == "maximum" ? "less" : "greater"

        cat         = "error"
        test        = field " != \"\" && " field " " comparator " " limit
        mini_msg    = "value should be " term " than: " limit
        msg         = field " in \" CSVFILENAME \" line \" NR \" should be " term " than " limit " and was \" " field " \" "

    } else if (rule_type == "pattern") {
        pattern     = params[2]

        cat         = "error"
        test        = field " != \"\" && " field " !~ " pattern
        mini_msg    = "value should match: " pattern
        msg         = field " in \" CSVFILENAME \" line \" NR \" should match the following pattern " pattern " and was \" " field " \" "

    } else if (rule_type ~ /^minLength|maxLength$/) {
        comparator  = $2 == "maxLength" ? ">" : "<"
        limit       = params[2]
        term        = $2 == "maxLength" ? "less" : "greater"

        cat         = "error"
        test        = field " != \"\" && length(" field ") " comparator " " limit
        mini_msg    = "max length is: " limit
        msg         = field " length in \" CSVFILENAME \" line \" NR \" should be " term " than " limit " and was \" length(" field ") \" "
    }
}

{
    # RENDER VIOLATION HANDLER
    if (test) {
        if (!cat) cat = options["dcat"]
        handler_prefix = "{ log_err(\"" cat "\"); "

        if (options["mode"] == "text") {
            err_handler = handler_prefix "print \"" msg "\" RS $0 RS; }"

        } else if (options["mode"] == "wrap") {
            acc = "$" field_index
            err_handler = handler_prefix "FS=\",\";" acc "=\">>\" " acc " \"<<\"; print $0 }"

        } else if (options["mode"] == "append") {
            err_handler = handler_prefix "print $0 FS \"" msg "\" }"
        }

        if (rule_type != "none") {
            print "action == \"validate\" && NR > 1 && " test " " err_handler " "
            summary_handler = "key=CSVFILENAME FS \"" field "\" FS  \"" rule_type "\" FS \"" mini_msg "\" FS \"" cat "\"; if(!violations[key]) { violations[key]=0; } violations[key]++;"
            print "action == \"validate:summary\" && NR > 1 && " test " { " summary_handler " } "
        }
    }
}

# BUILD MAP OF SQL TYPES FOR SQL CREATE AND COPY
$1 == "field" {
    sql_types_map["string"] = "text"
    sql_types_map["integer"] = "integer"
    sql_types_map["number"] = "numeric"

    rule_type = $2 ? sql_types_map[$2] : sql_types_map["string"]

    split($3, params, " ")
    field = params[1]

    sql_types[field] = rule_type
}

END {
    # SANITIZE EMPTY VALUES TO PASSED IN DEFAULTS OR NULL
    print RS "# sanitize rules"
    print "action ~ /^(sanitize|insert)$/ && NR > 1 {"
    for (field in sql_types) {
        sql_type    = sql_types[field]
        field_index = header_index[field]
        dval        = sql_type == "numeric" ? options["dvalnum"] : options["dvalstr"]
        dval        = dval ? dval : "\\\\N"

        print "    if (" field " == \"\") $" field_index " = \"" dval "\""
    }
    print "}"

    # SQL COPY
    print RS "# action handlers"
    print "action == \"insert\" && NR == 1 {"
    print "    print \"COPY " file_options["table"] " (\" addfields FS \"source_row_index\" FS $0 \") FROM stdin;\""
    print "}"

    print   "action == \"insert\" && NR > 1 {"
    print   "   record = addvals \"\\t\" NR"
    print   "   for (i = 1; i <= NF; i++) {"
    print   "       record = record \"\\t\" $i"
    print   "   }"
    print   "   print record"
    print   "}"

    # SQL CREATE TABLE
    print "action == \"table\" && NR == 1 {"
    fields=""
    for (i = 1; i <= length(headers); i++) {
        field     = headers[i]
        sql_type  = sql_types[field]
        fields    = fields field " " sql_type
        if (i < length(headers)) fields = fields ","
    }

    if(file_options["pkey"]) {
        cols    = file_options["pkey"]
        gsub(/\|/, ",", cols)
        fields  = fields ", CONSTRAINT " file_options["table"] "_pkey PRIMARY KEY (" cols ") "
    }
    if(file_options["fkey"]) {
        split(file_options["fkey"], ref, " ")
        ftable  = ref[1]
        fcols   = ref[2]
        gsub(/\|/, ",", fcols)
        fields  = fields ", CONSTRAINT " file_options["table"] "_" ftable "_fkey FOREIGN KEY (" fcols ") REFERENCES " ftable " (" fcols ") MATCH FULL "
        fields  = fields "ON UPDATE CASCADE ON DELETE NO ACTION"
    }
    print "     print \"CREATE TABLE IF NOT EXISTS " file_options["table"] " (" fields ");\""
    print "}"

    print "action == \"sanitize\" { print }"

    # END
    print "# la fin"
    print "END {"
    print "    if (action == \"validate:summary\" && length(dupkeys) > 0) for (dup in dupkeys) { violation=CSVFILENAME FS \"" file_options["pkey"] "\" FS  \"duplicate\" FS dup \" violates pkey\" FS \"error\"; violations[violation] = dupkeys[dup]}"
    print "    if (action == \"validate:summary\") { if (length(violations) > 0) for (violation in violations) { print violation FS violations[violation]; } }"
    #print "    if (action == \"insert\") print \"\\\\.\""
    print "    if (action == \"validate\" && options[\"summary\"] == \"true\") { print RS \"violation summary: \" RS \"   counts:   \" RS \"      total: \" err_count; print_cats(cats); }"
    print "}"
}

#!/usr/bin/awk -F, -f

BEGIN {
    FS=","
    print "#!/usr/bin/awk -F, -f" RS

    print "# generated by: awk-csvalid https://github.com/tesera/awk-csvalid" RS
    print "# awk-csvalid csv toolset generator: https://github.com/tesera/awk-csvalid"
    print "# usage:"
    print "#    validate:     awk -f action=validate validator.awk > violations.txt"
    print "#    create table: awk -v action=table -f validator.awk | psql afgo_dev"
    print "#    sanitize csv: awk -v action=sanitize -f validator.awk > sanitized.csv"
    print "#    insert sql:   awk -v action=insert -f validator.awk | psql afgo_dev" RS
    print "# awk is a simple unix text file parser: http://www.gnu.org/software/gawk/manual/gawk.html"
    print "# awk primer:"
    print "#    NR = number/index current record"
    print "#    RS = record seperator new line i.e. \\n"
    print "#    FS = field seperator i.e. ,"
    print "#    /pattern/ { expression } = if pattern is truthy run expression" RS

    print "BEGIN {"
    print "    FS=\",\"; OFS=\",\"; err_count=0; cats[\"na\"]=0;"
    print "    if(!action) action = \"validate\""
    print "    summary_header=\"file_name,field_name,rule,message,violation_count\""
    print "    CSVFILENAME = CSVFILENAME ? CSVFILENAME : FILENAME"
    print "    FPAT = \"([^,]*)|(\\\"[^\\\"]+\\\")\""
    print "}" RS

    print "# builtin helper functions"
    print "function eql(x,y) {v=1; for (i in x) v=(v&&x[i]==y[i]); return v;}"
    print "function are_headers_valid(valid_headers) { v=0; split($0, h, \",\"); split(valid_headers, vh, \"|\"); return eql(h, vh); }"
    print "function is_unique(i, val) { if (vals[i,val]) { return 0; } else { vals[i,val] = 1; return 1; } }"
    print "function is_numeric(x){ return(x==x+0) }"
    print "function print_cats(categories) { for (category in categories) { if (categories[category]) print \"      \" category \": \" categories[category]; } }"
    print "function log_err(cat) { cats[cat]++; err_count++; }"
    print RS
    print "#get rid of the evil windows cr"
    print "{ sub(\"\\r$\", \"\") }"
    print RS
    print "{"
    print "     for (i = 1; i <= NF; i++) {"
    print "         if (substr($i, 1, 1) == \"\\\"\") {"
    print "             len = length($i)"
    print "             $i = substr($i, 2, len - 2)"
    print "         }"
    print "     }"
    print "}"
    print RS
}

# BUILD OPTIONS MAP
$1 == "option" {
    options[$2]=$3;
}

# RENDER PFKEY CHECK
$1 == "file" {
    file_options[$2]=$3;
    if ($2 == "pkey") {
        pkeys=$3
        gsub(/\|/, " \"-\" ", pkeys)
        pkeycheck="action ~ /validate/ && NR > 1 { pkey=" pkeys "; if(keys[pkey]) { if (dupkeys[pkey]) dupkeys[pkey]++; else dupkeys[pkey] = 1 } else { keys[pkey] = NR } }"
    }
}

# RENDER HEADERS CHECK
$1 == "headers" && $2 == "names" {
    split($3, headers, "|")
    print "# make header index/map"
    print "NR > 1 {"
    print "field_width = " length(headers)
    for (i in headers) {
        header_name = headers[i]
        header_index[header_name] = i
        print "    " headers[i]  "=$" i
    }

    print "}" RS
    print "# awk rules based on user csv ruleset"
    print "NR == 1 && action == \"validate\" { headers=\"" $3 "\"; if (!are_headers_valid(headers)) { gsub(/\\|/, FS, headers); print RS \"INVALID HEADERS IN \" CSVFILENAME RS \"WAS: \" RS $0 RS \"EXPECTED:\" RS headers RS; exit 0; } }"
    print "NR == 1 && action == \"validate:summary\" { headers=\"" $3 "\"; if (!are_headers_valid(headers)) { violations[CSVFILENAME FS \"headers\" FS  \"names\" FS \"csv headers are invalid\" FS \"error\"]=1; exit 0; } }"
    print pkeycheck
    cat = "error"
    test = "NF != field_width"
    msg = "row \" NR \" in \" CSVFILENAME \" has \" NF \" columns and \" field_width \" was expected"
    mini_msg = "row \" NR \" has an invalid column count"
    rule_type = "invalid-column-count"
    # print "action ~ /^validate/ && NR > 1 { if(NF != field_width) { print \"row \" NR \" in \" CSVFILENAME \" has \" NF \" records and \" field_width \" was expected\"; next;} }"
}

{
    # SET DEFAULTS IF NOT PASSED IN VIA RULES
    defaults["mode"]    = "text"
    defaults["summary"] = "true"
    defaults["dcat"]    = "warning"
    for (option in defaults) {
        if (!options[option]) options[option] = defaults[option]
    }
}

# RENDER VALUE CHECKS
$1 == "field" {

    # PARSE RULE FIELDS
    rule_type     = $2
    split($3,params," ")
    field         = params[1]
    cat           = params[3]
    field_index   = header_index[field]
    test          = ""
    msg           = ""

    # BUILD VIOLATION TEST
    if (rule_type == "type") {
        type = params[2]

        if (type ~ /^integer|number$/) {
            cat       = "error"
            test      = field " && !is_numeric(" field ")"
            msg       = "Field " field " in \" CSVFILENAME \" line \" NR \" should be a numeric but was \" " field " \" "
        }

    } else if (rule_type == "required") {
        req = params[2]

        if (req == "true") {
            test        = field " == \"\""
            mini_msg    = "value is required but was empty"
            msg         = "Field " field " in \" CSVFILENAME \" line \" NR \" is required"
        } else if (req != "false") {
            test        = req " && " field " == \"\""
            mini_msg    = "value is required if " req
            msg         = "Field " field " in \" CSVFILENAME \" line \" NR \" is required if " req
        }

    } else if (rule_type == "unique") {
        cat         = "error"
        test        = "!is_unique(" field ")"
        mini_msg    = "value should be unique but had duplicates"
        msg         = "Field " field " in \" CSVFILENAME \" line \" NR \" is a duplicate and should be unique"

    } else if (rule_type ~ /^minimum|maximum$/) {
        comparator  = $2 == "maximum" ? ">" : "<"
        limit       = params[2]
        term        = $2 == "maximum" ? "less" : "greater"

        cat         = "error"
        test        = field " != \"\" && " field " " comparator " " limit
        mini_msg    = "value should be " term " than: " limit
        msg         = field " in \" CSVFILENAME \" line \" NR \" should be " term " than " limit " and was \" " field " \" "

    } else if (rule_type == "pattern") {
        pattern     = params[2]

        cat         = "error"
        test        = field " != \"\" && " field " !~ " pattern
        mini_msg    = "value should match: " pattern
        msg         = field " in \" CSVFILENAME \" line \" NR \" should match the following pattern " pattern " and was \" " field " \" "

    } else if (rule_type ~ /^minLength|maxLength$/) {
        comparator  = $2 == "maxLength" ? ">=" : "<="
        limit       = params[2]
        term        = $2 == "maxLength" ? "less" : "greater"

        cat         = "error"
        test        = field " != \"\" && length(" field ") " comparator " " limit
        mini_msg    = "max length is: " limit
        msg         = field " length in \" CSVFILENAME \" line \" NR \" should be " term " than " limit " and was \" length(" field ") \" "
    }
}

{
    # RENDER VIOLATION HANDLER
    if (test) {
        if (!cat) cat = options["dcat"]
        handler_prefix = "{ log_err(\"" cat "\"); "

        if (options["mode"] == "text") {
            err_handler = handler_prefix "print \"" msg "\" RS $0 RS; }"

        } else if (options["mode"] == "wrap") {
            acc = "$" field_index
            err_handler = handler_prefix "FS=\",\";" acc "=\">>\" " acc " \"<<\"; print $0 }"

        } else if (options["mode"] == "append") {
            err_handler = handler_prefix "print $0 FS \"" msg "\" }"
        }

        if (rule_type != "none") {
            print "action == \"validate\" && NR > 1 && " test " " err_handler " "
            summary_handler = "key=CSVFILENAME FS \"" field "\" FS  \"" rule_type "\" FS \"" mini_msg "\" FS \"" cat "\"; if(!violations[key]) { violations[key]=0; } violations[key]++;"
            print "action == \"validate:summary\" && NR > 1 && " test " { " summary_handler " } "
        }
    }
}

# BUILD MAP OF SQL TYPES FOR SQL CREATE AND COPY
$1 == "field" {
    sql_types_map["string"] = "text"
    sql_types_map["integer"] = "integer"
    sql_types_map["number"] = "numeric"

    rule_type = $2 ? sql_types_map[$2] : sql_types_map["string"]

    split($3, params, " ")
    field = params[1]

    sql_types[field] = rule_type
}

END {
    # SANITIZE EMPTY VALUES TO PASSED IN DEFAULTS OR NULL
    print RS "# sanitize rules"
    print "action ~ /^(sanitize|insert)$/ && NR > 1 {"
    for (field in sql_types) {
        sql_type    = sql_types[field]
        field_index = header_index[field]
        dval        = sql_type == "numeric" ? options["dvalnum"] : options["dvalstr"]
        dval        = dval ? dval : "\\\\N"

        print "    if (" field " == \"\") $" field_index " = \"" dval "\""
    }
    print "}"

    # SQL COPY
    print RS "# action handlers"
    print "action == \"insert\" && NR == 1 {"
    print "    print \"COPY " file_options["table"] " (\" addfields FS \"source_row_index\" FS $0 \") FROM stdin;\""
    print "}"

    print   "action == \"insert\" && NR > 1 {"
    print   "   record = addvals \"\\t\" NR"
    print   "   for (i = 1; i <= NF; i++) {"
    print   "       record = record \"\\t\" $i"
    print   "   }"
    print   "   print record"
    print   "}"

    # SQL CREATE TABLE
    print "action == \"table\" && NR == 1 {"
    fields=""
    for (i = 1; i <= length(headers); i++) {
        field     = headers[i]
        sql_type  = sql_types[field]
        fields    = fields field " " sql_type
        if (i < length(headers)) fields = fields ","
    }

    if(file_options["pkey"]) {
        cols    = file_options["pkey"]
        gsub(/\|/, ",", cols)
        fields  = fields ", CONSTRAINT " file_options["table"] "_pkey PRIMARY KEY (" cols ") "
    }
    if(file_options["fkey"]) {
        split(file_options["fkey"], ref, " ")
        ftable  = ref[1]
        fcols   = ref[2]
        gsub(/\|/, ",", fcols)
        fields  = fields ", CONSTRAINT " file_options["table"] "_" ftable "_fkey FOREIGN KEY (" fcols ") REFERENCES " ftable " (" fcols ") MATCH FULL "
        fields  = fields "ON UPDATE CASCADE ON DELETE NO ACTION"
    }
    print "     print \"CREATE TABLE IF NOT EXISTS " file_options["table"] " (" fields ");\""
    print "}"

    print "action == \"sanitize\" { print }"

    # END
    print "# la fin"
    print "END {"
    print "    if (action == \"validate:summary\" && length(dupkeys) > 0) for (dup in dupkeys) { violation=CSVFILENAME FS \"" file_options["pkey"] "\" FS  \"duplicate\" FS dup \" violates pkey\" FS \"error\"; violations[violation] = dupkeys[dup]}"
    print "    if (action == \"validate:summary\") { if (length(violations) > 0) for (violation in violations) { print violation FS violations[violation]; } }"
    #print "    if (action == \"insert\") print \"\\\\.\""
    print "    if (action == \"validate\" && options[\"summary\"] == \"true\") { print RS \"violation summary: \" RS \"   counts:   \" RS \"      total: \" err_count; print_cats(cats); }"
    print "}"
}


Pass doxygen doc comments through to the output.

#!/usr/bin/awk -f
#
# Copyright (c) 1992, 1993
#        The Regents of the University of California.  All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
# 4. Neither the name of the University nor the names of its contributors
#    may be used to endorse or promote products derived from this software
#    without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
# From @(#)vnode_if.sh        8.1 (Berkeley) 6/10/93
# From @(#)makedevops.sh 1.1 1998/06/14 13:53:12 dfr Exp $
# From @(#)makedevops.sh ?.? 1998/10/05
# From src/sys/kern/makedevops.pl,v 1.12 1999/11/22 14:40:04 n_hibma Exp
# From src/sys/kern/makeobjops.pl,v 1.8 2001/11/16 02:02:42 joe Exp
#
# $FreeBSD$

#
#   Script to produce kobj front-end sugar.
#

function usage ()
{
	print "usage: makeobjops.awk <srcfile.m> [-d] [-p] [-l <nr>] [-c|-h]";
	print "where -c   produce only .c files";
	print "      -h   produce only .h files";
	print "      -p   use the path component in the source file for destination dir";
	print "      -l   set line width for output files [80]";
	print "      -d   switch on debugging";
	exit 1;
}

function warn (msg)
{
	print "makeobjops.awk:", msg > "/dev/stderr";
}

function warnsrc (msg)
{
	warn(src ":" lineno ": " msg);
}

function debug (msg)
{
	if (opt_d)
		warn(msg);
}

function die (msg)
{
	warn(msg);
	exit 1;
}

#   These are just for convenience ...
function printc(s) {if (opt_c) print s > ctmpfilename;}
function printh(s) {if (opt_h) print s > htmpfilename;}

#
#   If a line exceeds maxlength, split it into multiple
#   lines at commas.  Subsequent lines are indented by
#   the specified number of spaces.
#
#   In other words:  Lines are split by replacing ", "
#   by ",\n" plus indent spaces.
#

function format_line (line, maxlength, indent)
{
	rline = "";

	while (length(line) > maxlength) {
		#
		#   Find the rightmost ", " so that the part
		#   to the left of it is just within maxlength.
		#   If there is none, give up and leave it as-is.
		#
		if (!match(substr(line, 1, maxlength + 1), /^.*, /))
			break;
		rline = rline substr(line, 1, RLENGTH - 1) "\n";
		line = sprintf("%*s", indent, "") substr(line, RLENGTH + 1);
	}
	return rline line;
}

#
#   Join an array into a string.
#

function join (separator, array, num)
{
	_result = ""
	if (num) {
		while (num > 1)
			_result = separator array[num--] _result;
		_result = array[1] _result;
	}
	return _result;
}

#
#   Execute a system command and report if it failed.
#

function system_check (cmd)
{
	if ((rc = system(cmd)))
		warn(cmd " failed (" rc ")");
}

#
#   Handle "INTERFACE" line.
#

function handle_interface ()
{
	intname = $2;
	sub(/;$/, "", intname);
	if (intname !~ /^[a-z_][a-z0-9_]*$/) {
		debug($0);
		warnsrc("Invalid interface name '" intname "', use [a-z_][a-z0-9_]*");
		error = 1;
		return;
	}
	if (!/;[ 	]*$/)
		warnsrc("Semicolon missing at end of line, no problem");

	debug("Interface " intname);

	printh("#ifndef _" intname "_if_h_");
	printh("#define _" intname "_if_h_\n");
	printc("#include \"" intname "_if.h\"\n");
}

#
# Pass doc comments through to the C file
#
function handle_doc ()
{
	doc = ""
	while (!/\*\//) {
		doc = doc $0 "\n";
		getline < src;
		lineno++;
	}
	doc = doc $0 "\n";
	return doc;
}

#
#   Handle "CODE" and "HEADER" sections.
#   Returns the code as-is.
#

function handle_code ()
{
	code = "\n";
	getline < src;
	indent = $0;
	sub(/[^	 ].*$/, "", indent);	# find the indent used
	while (!/^}/) {
		sub("^" indent, "");	# remove the indent
		code = code $0 "\n";
		getline < src;
		lineno++;;
	}
	return code;
}

#
#   Handle "METHOD" and "STATICMETHOD" sections.
#

function handle_method (static, doc)
{
	#
	#   Get the return type and function name and delete that from
	#   the line. What is left is the possibly first function argument
	#   if it is on the same line.
	#
	if (!intname) {
		warnsrc("No interface name defined");
		error = 1;
		return;
	}
	sub(/^[^ 	]+[ 	]+/, "");
	ret = $0;
	sub(/[ 	]*\{.*$/, "", ret);
	name = ret;
	sub(/^.*[ 	]/, "", name);	# last element is name of method
	sub(/[ 	]+[^ 	]+$/, "", ret);	# return type
	debug("Method: name=" name " return type=" ret);

	sub(/^[^\{]*\{[	 ]*/, "");

	if (!name || !ret) {
		debug($0);
		warnsrc("Invalid method specification");
		error = 1;
		return;
	}

	if (name !~ /^[a-z_][a-z_0-9]*$/) {
		warnsrc("Invalid method name '" name "', use [a-z_][a-z0-9_]*");
		error = 1;
		return;
	}

	if (methods[name]) {
		warnsrc("Duplicate method name");
		error = 1;
		return;
	}
	methods[name] = name;

	line = $0;
	while (line !~ /\}/ && (getline < src) > 0) {
		line = line " " $0;
		lineno++
	}

	default = "";
	if (!match(line, /\};?/)) {
		warnsrc("Premature end of file");
		error = 1;
		return;
	}
	extra = substr(line, RSTART + RLENGTH);
	if (extra ~ /[	 ]*DEFAULT[ 	]*[a-zA-Z_][a-zA-Z_0-9]*[ 	]*;/) {
		default = extra;
		sub(/.*DEFAULT[	 ]*/, "", default);
		sub(/[; 	]+.*$/, "", default);
	}
	else if (extra && opt_d) {
		#   Warn about garbage at end of line.
		warnsrc("Ignored '" extra "'");
	}
	sub(/\};?.*$/, "", line);

	#
	#   Create a list of variables without the types prepended.
	#
	sub(/^[	 ]+/, "", line);	# remove leading ...
	sub(/[ 	]+$/, "", line);	# ... and trailing whitespace
	gsub(/[	 ]+/, " ", line);	# remove double spaces

	num_arguments = split(line, arguments, / *; */) - 1;
	delete varnames;		# list of varnames
	num_varnames = 0;
	for (i = 1; i <= num_arguments; i++) {
		if (!arguments[i])
			continue;	# skip argument if argument is empty
		num_ar = split(arguments[i], ar, /[* 	]+/);
		if (num_ar < 2) {	# only 1 word in argument?
			warnsrc("no type for '" arguments[i] "'");
			error = 1;
			return;
		}
		#   Last element is name of variable.
		varnames[++num_varnames] = ar[num_ar];
	}

	argument_list = join(", ", arguments, num_arguments);
	varname_list = join(", ", varnames, num_varnames);

	if (opt_d) {
		warn("Arguments: " argument_list);
		warn("Varnames: " varname_list);
	}

	mname = intname "_" name;	# method name
	umname = toupper(mname);	# uppercase method name

	firstvar = varnames[1];

	if (default == "")
		default = "kobj_error_method";

	# the method description
	printh("/** @brief Unique descriptor for the " umname "() method */");
	printh("extern struct kobjop_desc " mname "_desc;");
	# the method typedef
	printh("/** @brief A function implementing the " umname "() method */");
	prototype = "typedef " ret " " mname "_t(";
	printh(format_line(prototype argument_list ");",
	    line_width, length(prototype)));

	# Print out the method desc
	printc("struct kobj_method " mname "_method_default = {");
	printc("\t&" mname "_desc, (kobjop_t) " default);
	printc("};\n");

	printc("struct kobjop_desc " mname "_desc = {");
	printc("\t0, &" mname "_method_default");
	printc("};\n");

	# Print out the method itself
	printh(doc);
	if (0) {		# haven't chosen the format yet
		printh("static __inline " ret " " umname "(" varname_list ")");
		printh("\t" join(";\n\t", arguments, num_arguments) ";");
	}
	else {
		prototype = "static __inline " ret " " umname "(";
		printh(format_line(prototype argument_list ")",
		    line_width, length(prototype)));
	}
	printh("{");
	printh("\tkobjop_t _m;");
	if (!static)
		firstvar = "((kobj_t)" firstvar ")";
	printh("\tKOBJOPLOOKUP(" firstvar "->ops," mname ");");
	retrn =  (ret != "void") ? "return " : "";
	printh("\t" retrn "((" mname "_t *) _m)(" varname_list ");");
	printh("}\n");
}

#
#   Begin of the main program.
#

BEGIN {

line_width = 80;
gerror = 0;

#
#   Process the command line.
#

num_files = 0;

for (i = 1; i < ARGC; i++) {
	if (ARGV[i] ~ /^-/) {
		#
		#   awk doesn't have getopt(), so we have to do it ourselves.
		#   This is a bit clumsy, but it works.
		#
		for (j = 2; j <= length(ARGV[i]); j++) {
			o = substr(ARGV[i], j, 1);
			if	(o == "c")	opt_c = 1;
			else if	(o == "h")	opt_h = 1;
			else if	(o == "p")	opt_p = 1;
			else if	(o == "d")	opt_d = 1;
			else if	(o == "l") {
				if (length(ARGV[i]) > j) {
					opt_l = substr(ARGV[i], j + 1);
					break;
				}
				else {
					if (++i < ARGC)
						opt_l = ARGV[i];
					else
						usage();
				}
			}
			else
				usage();
		}
	}
	else if (ARGV[i] ~ /\.m$/)
		filenames[num_files++] = ARGV[i];
	else
		usage();
}

if (!num_files || !(opt_c || opt_h))
	usage();

if (opt_p)
	debug("Will produce files in original not in current directory");

if (opt_l) {
	if (opt_l !~ /^[0-9]+$/ || opt_l < 1)
		die("Invalid line width '" opt_l "'");
	line_width = opt_l;
	debug("Line width set to " line_width);
}

for (i = 0; i < num_files; i++)
	debug("Filename: " filenames[i]);

for (file_i = 0; file_i < num_files; file_i++) {
	src = filenames[file_i];
	cfilename = hfilename = src;
	sub(/\.m$/, ".c", cfilename);
	sub(/\.m$/, ".h", hfilename);
	if (!opt_p) {
		sub(/^.*\//, "", cfilename);
		sub(/^.*\//, "", hfilename);
	}

	debug("Processing from " src " to " cfilename " / " hfilename);

	ctmpfilename = cfilename ".tmp";
	htmpfilename = hfilename ".tmp";

	common_head = \
	    "/*\n" \
	    " * This file is produced automatically.\n" \
	    " * Do not modify anything in here by hand.\n" \
	    " *\n" \
	    " * Created from source file\n" \
	    " *   " src "\n" \
	    " * with\n" \
	    " *   makeobjops.awk\n" \
	    " *\n" \
	    " * See the source file for legal information\n" \
	    " */\n";

	printc(common_head "\n" \
	    "#include <sys/param.h>\n" \
	    "#include <sys/queue.h>\n" \
	    "#include <sys/kernel.h>\n" \
	    "#include <sys/kobj.h>");

	printh(common_head);

	delete methods;		# clear list of methods
	intname = "";
	lineno = 0;
	error = 0;		# to signal clean up and gerror setting
	lastdoc = "";

	while (!error && (getline < src) > 0) {
		lineno++;

		#
		#   Take special notice of include directives.
		#
		if (/^#[ 	]*include[ 	]+["<][^">]+[">]/) {
			incld = $0;
			sub(/^#[ 	]*include[ 	]+/, "", incld);
			debug("Included file: " incld);
			printc("#include " incld);
		}

		sub(/#.*/, "");		# remove comments
		sub(/^[	 ]+/, "");	# remove leading ...
		sub(/[ 	]+$/, "");	# ... and trailing whitespace

		if (/^$/) {		# skip empty lines
		}
		else if (/^\/\*\*/)
			lastdoc = handle_doc();
		else if (/^INTERFACE[ 	]+[^ 	;]*[ 	]*;?[ 	]*$/) {
			printh(lastdoc);
			lastdoc = "";
			handle_interface();
		} else if (/^CODE[ 	]*{$/)
			printc(handle_code());
		else if (/^HEADER[	 ]*{$/)
			printh(handle_code());
		else if (/^METHOD/) {
			handle_method(0, lastdoc);
			lastdoc = "";
		} else if (/^STATICMETHOD/) {
			handle_method(1, lastdoc);
			lastdoc = "";
		} else {
			debug($0);
			warnsrc("Invalid line encountered");
			error = 1;
		}
	}

	#
	#   Print the final '#endif' in the header file.
	#
	printh("#endif /* _" intname "_if_h_ */");

	close (ctmpfilename);
	close (htmpfilename);

	if (error) {
		warn("Output skipped");
		system_check("rm -f " ctmpfilename " " htmpfilename);
		gerror = 1;
	}
	else {
		if (opt_c)
			system_check("mv -f " ctmpfilename " " cfilename);
		if (opt_h)
			system_check("mv -f " htmpfilename " " hfilename);
	}
}

exit gerror;

}

#!/usr/bin/awk -f
#
# Copyright (c) 1992, 1993
#        The Regents of the University of California.  All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
# 4. Neither the name of the University nor the names of its contributors
#    may be used to endorse or promote products derived from this software
#    without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
# From @(#)vnode_if.sh        8.1 (Berkeley) 6/10/93
# From @(#)makedevops.sh 1.1 1998/06/14 13:53:12 dfr Exp $
# From @(#)makedevops.sh ?.? 1998/10/05
# From src/sys/kern/makedevops.pl,v 1.12 1999/11/22 14:40:04 n_hibma Exp
# From src/sys/kern/makeobjops.pl,v 1.8 2001/11/16 02:02:42 joe Exp
#
# $FreeBSD$

#
#   Script to produce kobj front-end sugar.
#

function usage ()
{
	print "usage: makeobjops.awk <srcfile.m> [-d] [-p] [-l <nr>] [-c|-h]";
	print "where -c   produce only .c files";
	print "      -h   produce only .h files";
	print "      -p   use the path component in the source file for destination dir";
	print "      -l   set line width for output files [80]";
	print "      -d   switch on debugging";
	exit 1;
}

function warn (msg)
{
	print "makeobjops.awk:", msg > "/dev/stderr";
}

function warnsrc (msg)
{
	warn(src ":" lineno ": " msg);
}

function debug (msg)
{
	if (opt_d)
		warn(msg);
}

function die (msg)
{
	warn(msg);
	exit 1;
}

#   These are just for convenience ...
function printc(s) {if (opt_c) print s > ctmpfilename;}
function printh(s) {if (opt_h) print s > htmpfilename;}

#
#   If a line exceeds maxlength, split it into multiple
#   lines at commas.  Subsequent lines are indented by
#   the specified number of spaces.
#
#   In other words:  Lines are split by replacing ", "
#   by ",\n" plus indent spaces.
#

function format_line (line, maxlength, indent)
{
	rline = "";

	while (length(line) > maxlength) {
		#
		#   Find the rightmost ", " so that the part
		#   to the left of it is just within maxlength.
		#   If there is none, give up and leave it as-is.
		#
		if (!match(substr(line, 1, maxlength + 1), /^.*, /))
			break;
		rline = rline substr(line, 1, RLENGTH - 1) "\n";
		line = sprintf("%*s", indent, "") substr(line, RLENGTH + 1);
	}
	return rline line;
}

#
#   Join an array into a string.
#

function join (separator, array, num)
{
	_result = ""
	if (num) {
		while (num > 1)
			_result = separator array[num--] _result;
		_result = array[1] _result;
	}
	return _result;
}

#
#   Execute a system command and report if it failed.
#

function system_check (cmd)
{
	if ((rc = system(cmd)))
		warn(cmd " failed (" rc ")");
}

#
#   Handle "INTERFACE" line.
#

function handle_interface ()
{
	intname = $2;
	sub(/;$/, "", intname);
	if (intname !~ /^[a-z_][a-z0-9_]*$/) {
		debug($0);
		warnsrc("Invalid interface name '" intname "', use [a-z_][a-z0-9_]*");
		error = 1;
		return;
	}
	if (!/;[ 	]*$/)
		warnsrc("Semicolon missing at end of line, no problem");

	debug("Interface " intname);

	printh("#ifndef _" intname "_if_h_");
	printh("#define _" intname "_if_h_\n");
	printc("#include \"" intname "_if.h\"\n");
}

#
#   Handle "CODE" and "HEADER" sections.
#   Returns the code as-is.
#

function handle_code ()
{
	code = "\n";
	getline < src;
	indent = $0;
	sub(/[^	 ].*$/, "", indent);	# find the indent used
	while (!/^}/) {
		sub("^" indent, "");	# remove the indent
		code = code $0 "\n";
		getline < src;
		lineno++;;
	}
	return code;
}

#
#   Handle "METHOD" and "STATICMETHOD" sections.
#

function handle_method (static)
{
	#
	#   Get the return type and function name and delete that from
	#   the line. What is left is the possibly first function argument
	#   if it is on the same line.
	#
	if (!intname) {
		warnsrc("No interface name defined");
		error = 1;
		return;
	}
	sub(/^[^ 	]+[ 	]+/, "");
	ret = $0;
	sub(/[ 	]*\{.*$/, "", ret);
	name = ret;
	sub(/^.*[ 	]/, "", name);	# last element is name of method
	sub(/[ 	]+[^ 	]+$/, "", ret);	# return type
	debug("Method: name=" name " return type=" ret);

	sub(/^[^\{]*\{[	 ]*/, "");

	if (!name || !ret) {
		debug($0);
		warnsrc("Invalid method specification");
		error = 1;
		return;
	}

	if (name !~ /^[a-z_][a-z_0-9]*$/) {
		warnsrc("Invalid method name '" name "', use [a-z_][a-z0-9_]*");
		error = 1;
		return;
	}

	if (methods[name]) {
		warnsrc("Duplicate method name");
		error = 1;
		return;
	}
	methods[name] = name;

	line = $0;
	while (line !~ /\}/ && (getline < src) > 0) {
		line = line " " $0;
		lineno++
	}

	default = "";
	if (!match(line, /\};?/)) {
		warnsrc("Premature end of file");
		error = 1;
		return;
	}
	extra = substr(line, RSTART + RLENGTH);
	if (extra ~ /[	 ]*DEFAULT[ 	]*[a-zA-Z_][a-zA-Z_0-9]*[ 	]*;/) {
		default = extra;
		sub(/.*DEFAULT[	 ]*/, "", default);
		sub(/[; 	]+.*$/, "", default);
	}
	else if (extra && opt_d) {
		#   Warn about garbage at end of line.
		warnsrc("Ignored '" extra "'");
	}
	sub(/\};?.*$/, "", line);

	#
	#   Create a list of variables without the types prepended.
	#
	sub(/^[	 ]+/, "", line);	# remove leading ...
	sub(/[ 	]+$/, "", line);	# ... and trailing whitespace
	gsub(/[	 ]+/, " ", line);	# remove double spaces

	num_arguments = split(line, arguments, / *; */) - 1;
	delete varnames;		# list of varnames
	num_varnames = 0;
	for (i = 1; i <= num_arguments; i++) {
		if (!arguments[i])
			continue;	# skip argument if argument is empty
		num_ar = split(arguments[i], ar, /[* 	]+/);
		if (num_ar < 2) {	# only 1 word in argument?
			warnsrc("no type for '" arguments[i] "'");
			error = 1;
			return;
		}
		#   Last element is name of variable.
		varnames[++num_varnames] = ar[num_ar];
	}

	argument_list = join(", ", arguments, num_arguments);
	varname_list = join(", ", varnames, num_varnames);

	if (opt_d) {
		warn("Arguments: " argument_list);
		warn("Varnames: " varname_list);
	}

	mname = intname "_" name;	# method name
	umname = toupper(mname);	# uppercase method name

	firstvar = varnames[1];

	if (default == "")
		default = "kobj_error_method";

	# the method description
	printh("extern struct kobjop_desc " mname "_desc;");
	# the method typedef
	prototype = "typedef " ret " " mname "_t(";
	printh(format_line(prototype argument_list ");",
	    line_width, length(prototype)));

	# Print out the method desc
	printc("struct kobj_method " mname "_method_default = {");
	printc("\t&" mname "_desc, (kobjop_t) " default);
	printc("};\n");

	printc("struct kobjop_desc " mname "_desc = {");
	printc("\t0, &" mname "_method_default");
	printc("};\n");

	# Print out the method itself
	if (0) {		# haven't chosen the format yet
		printh("static __inline " ret " " umname "(" varname_list ")");
		printh("\t" join(";\n\t", arguments, num_arguments) ";");
	}
	else {
		prototype = "static __inline " ret " " umname "(";
		printh(format_line(prototype argument_list ")",
		    line_width, length(prototype)));
	}
	printh("{");
	printh("\tkobjop_t _m;");
	if (!static)
		firstvar = "((kobj_t)" firstvar ")";
	printh("\tKOBJOPLOOKUP(" firstvar "->ops," mname ");");
	retrn =  (ret != "void") ? "return " : "";
	printh("\t" retrn "((" mname "_t *) _m)(" varname_list ");");
	printh("}\n");
}

#
#   Begin of the main program.
#

BEGIN {

line_width = 80;
gerror = 0;

#
#   Process the command line.
#

num_files = 0;

for (i = 1; i < ARGC; i++) {
	if (ARGV[i] ~ /^-/) {
		#
		#   awk doesn't have getopt(), so we have to do it ourselves.
		#   This is a bit clumsy, but it works.
		#
		for (j = 2; j <= length(ARGV[i]); j++) {
			o = substr(ARGV[i], j, 1);
			if	(o == "c")	opt_c = 1;
			else if	(o == "h")	opt_h = 1;
			else if	(o == "p")	opt_p = 1;
			else if	(o == "d")	opt_d = 1;
			else if	(o == "l") {
				if (length(ARGV[i]) > j) {
					opt_l = substr(ARGV[i], j + 1);
					break;
				}
				else {
					if (++i < ARGC)
						opt_l = ARGV[i];
					else
						usage();
				}
			}
			else
				usage();
		}
	}
	else if (ARGV[i] ~ /\.m$/)
		filenames[num_files++] = ARGV[i];
	else
		usage();
}

if (!num_files || !(opt_c || opt_h))
	usage();

if (opt_p)
	debug("Will produce files in original not in current directory");

if (opt_l) {
	if (opt_l !~ /^[0-9]+$/ || opt_l < 1)
		die("Invalid line width '" opt_l "'");
	line_width = opt_l;
	debug("Line width set to " line_width);
}

for (i = 0; i < num_files; i++)
	debug("Filename: " filenames[i]);

for (file_i = 0; file_i < num_files; file_i++) {
	src = filenames[file_i];
	cfilename = hfilename = src;
	sub(/\.m$/, ".c", cfilename);
	sub(/\.m$/, ".h", hfilename);
	if (!opt_p) {
		sub(/^.*\//, "", cfilename);
		sub(/^.*\//, "", hfilename);
	}

	debug("Processing from " src " to " cfilename " / " hfilename);

	ctmpfilename = cfilename ".tmp";
	htmpfilename = hfilename ".tmp";

	common_head = \
	    "/*\n" \
	    " * This file is produced automatically.\n" \
	    " * Do not modify anything in here by hand.\n" \
	    " *\n" \
	    " * Created from source file\n" \
	    " *   " src "\n" \
	    " * with\n" \
	    " *   makeobjops.awk\n" \
	    " *\n" \
	    " * See the source file for legal information\n" \
	    " */\n";

	printc(common_head "\n" \
	    "#include <sys/param.h>\n" \
	    "#include <sys/queue.h>\n" \
	    "#include <sys/kernel.h>\n" \
	    "#include <sys/kobj.h>");

	printh(common_head);

	delete methods;		# clear list of methods
	intname = "";
	lineno = 0;
	error = 0;		# to signal clean up and gerror setting

	while (!error && (getline < src) > 0) {
		lineno++;

		#
		#   Take special notice of include directives.
		#
		if (/^#[ 	]*include[ 	]+["<][^">]+[">]/) {
			incld = $0;
			sub(/^#[ 	]*include[ 	]+/, "", incld);
			debug("Included file: " incld);
			printc("#include " incld);
		}

		sub(/#.*/, "");		# remove comments
		sub(/^[	 ]+/, "");	# remove leading ...
		sub(/[ 	]+$/, "");	# ... and trailing whitespace

		if (/^$/) {		# skip empty lines
		}
		else if (/^INTERFACE[ 	]+[^ 	;]*[ 	]*;?[ 	]*$/)
			handle_interface();
		else if (/^CODE[ 	]*{$/)
			printc(handle_code());
		else if (/^HEADER[	 ]*{$/)
			printh(handle_code());
		else if (/^METHOD/)
			handle_method(0);
		else if (/^STATICMETHOD/)
			handle_method(1);
		else {
			debug($0);
			warnsrc("Invalid line encountered");
			error = 1;
		}
	}

	#
	#   Print the final '#endif' in the header file.
	#
	printh("#endif /* _" intname "_if_h_ */");

	close (ctmpfilename);
	close (htmpfilename);

	if (error) {
		warn("Output skipped");
		system_check("rm -f " ctmpfilename " " htmpfilename);
		gerror = 1;
	}
	else {
		if (opt_c)
			system_check("mv -f " ctmpfilename " " cfilename);
		if (opt_h)
			system_check("mv -f " htmpfilename " " hfilename);
	}
}

exit gerror;

}