xref: /freebsd/sys/tools/makeobjops.awk (revision d37eb51047221dc3322b34db1038ff3aa533883f)
1#!/usr/bin/awk -f
2
3#-
4# SPDX-License-Identifier: BSD-3-Clause
5#
6# Copyright (c) 1992, 1993
7#        The Regents of the University of California.  All rights reserved.
8#
9# Redistribution and use in source and binary forms, with or without
10# modification, are permitted provided that the following conditions
11# are met:
12# 1. Redistributions of source code must retain the above copyright
13#    notice, this list of conditions and the following disclaimer.
14# 2. Redistributions in binary form must reproduce the above copyright
15#    notice, this list of conditions and the following disclaimer in the
16#    documentation and/or other materials provided with the distribution.
17# 3. Neither the name of the University nor the names of its contributors
18#    may be used to endorse or promote products derived from this software
19#    without specific prior written permission.
20#
21# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24# ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31# SUCH DAMAGE.
32# From src/sys/kern/makedevops.pl,v 1.12 1999/11/22 14:40:04 n_hibma Exp
33# From src/sys/kern/makeobjops.pl,v 1.8 2001/11/16 02:02:42 joe Exp
34#
35
36#
37#   Script to produce kobj front-end sugar.
38#
39
40function usage ()
41{
42	print "usage: makeobjops.awk <srcfile.m> [-d] [-p] [-l <nr>] [-c|-h]";
43	print "where -c   produce only .c files";
44	print "      -h   produce only .h files";
45	print "      -p   use the path component in the source file for destination dir";
46	print "      -l   set line width for output files [80]";
47	print "      -d   switch on debugging";
48	exit 1;
49}
50
51function warn (msg)
52{
53	print "makeobjops.awk:", msg > "/dev/stderr";
54}
55
56function warnsrc (msg)
57{
58	warn(src ":" lineno ": " msg);
59}
60
61function debug (msg)
62{
63	if (opt_d)
64		warn(msg);
65}
66
67function die (msg)
68{
69	warn(msg);
70	exit 1;
71}
72
73#   These are just for convenience ...
74function printc(s) {if (opt_c) print s > ctmpfilename;}
75function printh(s) {if (opt_h) print s > htmpfilename;}
76
77#
78#   If a line exceeds maxlength, split it into multiple
79#   lines at commas.  Subsequent lines are indented by
80#   the specified number of spaces.
81#
82#   In other words:  Lines are split by replacing ", "
83#   by ",\n" plus indent spaces.
84#
85
86function format_line (line, maxlength, indent)
87{
88	rline = "";
89
90	while (length(line) > maxlength) {
91		#
92		#   Find the rightmost ", " so that the part
93		#   to the left of it is just within maxlength.
94		#   If there is none, give up and leave it as-is.
95		#
96		if (!match(substr(line, 1, maxlength + 1), /^.*, /))
97			break;
98		rline = rline substr(line, 1, RLENGTH - 1) "\n";
99		line = sprintf("%*s", indent, "") substr(line, RLENGTH + 1);
100	}
101	return rline line;
102}
103
104#
105#   Join an array into a string.
106#
107
108function join (separator, array, num)
109{
110	_result = ""
111	if (num) {
112		while (num > 1)
113			_result = separator array[num--] _result;
114		_result = array[1] _result;
115	}
116	return _result;
117}
118
119#
120#   Execute a system command and report if it failed.
121#
122
123function system_check (cmd)
124{
125	if ((rc = system(cmd)))
126		warn(cmd " failed (" rc ")");
127}
128
129#
130#   Handle "INTERFACE" line.
131#
132
133function handle_interface ()
134{
135	intname = $2;
136	sub(/;$/, "", intname);
137	if (intname !~ /^[a-z_][a-z0-9_]*$/) {
138		debug($0);
139		warnsrc("Invalid interface name '" intname "', use [a-z_][a-z0-9_]*");
140		error = 1;
141		return;
142	}
143	if (!/;[ 	]*$/)
144		warnsrc("Semicolon missing at end of line, no problem");
145
146	debug("Interface " intname);
147
148	printh("#ifndef _" intname "_if_h_");
149	printh("#define _" intname "_if_h_\n");
150	printc("#include \"" intname "_if.h\"\n");
151}
152
153#
154# Pass doc comments through to the C file
155#
156function handle_doc ()
157{
158	doc = ""
159	while (!/\*\//) {
160		doc = doc $0 "\n";
161		getline < src;
162		lineno++;
163	}
164	doc = doc $0 "\n";
165	return doc;
166}
167
168#
169#   Handle "CODE" and "HEADER" sections.
170#   Returns the code as-is.
171#
172
173function handle_code ()
174{
175	code = "\n";
176	getline < src;
177	indent = $0;
178	sub(/[^	 ].*$/, "", indent);	# find the indent used
179	while (!/^}/) {
180		sub("^" indent, "");	# remove the indent
181		code = code $0 "\n";
182		getline < src;
183		lineno++;;
184	}
185	return code;
186}
187
188#
189#   Handle "METHOD" and "STATICMETHOD" sections.
190#
191
192function handle_method (static, doc)
193{
194	#
195	#   Get the return type and function name and delete that from
196	#   the line. What is left is the possibly first function argument
197	#   if it is on the same line.
198	#
199	if (!intname) {
200		warnsrc("No interface name defined");
201		error = 1;
202		return;
203	}
204	sub(/^[^ 	]+[ 	]+/, "");
205	ret = $0;
206	sub(/[ 	]*\{.*$/, "", ret);
207	name = ret;
208	sub(/^.*[ 	]/, "", name);	# last element is name of method
209	sub(/[ 	]+[^ 	]+$/, "", ret);	# return type
210	debug("Method: name=" name " return type=" ret);
211
212	sub(/^[^\{]*\{[	 ]*/, "");
213
214	if (!name || !ret) {
215		debug($0);
216		warnsrc("Invalid method specification");
217		error = 1;
218		return;
219	}
220
221	if (name !~ /^[a-z_][a-z_0-9]*$/) {
222		warnsrc("Invalid method name '" name "', use [a-z_][a-z0-9_]*");
223		error = 1;
224		return;
225	}
226
227	if (methods[name]) {
228		warnsrc("Duplicate method name");
229		error = 1;
230		return;
231	}
232	methods[name] = name;
233
234	line = $0;
235	while (line !~ /\}/ && (getline < src) > 0) {
236		line = line " " $0;
237		lineno++
238	}
239
240	default_function = "";
241	if (!match(line, /\};?/)) {
242		warnsrc("Premature end of file");
243		error = 1;
244		return;
245	}
246	extra = substr(line, RSTART + RLENGTH);
247	if (extra ~ /[	 ]*DEFAULT[ 	]*[a-zA-Z_][a-zA-Z_0-9]*[ 	]*;/) {
248		default_function = extra;
249		sub(/.*DEFAULT[	 ]*/, "", default_function);
250		sub(/[; 	]+.*$/, "", default_function);
251	}
252	else if (extra && opt_d) {
253		#   Warn about garbage at end of line.
254		warnsrc("Ignored '" extra "'");
255	}
256	sub(/\};?.*$/, "", line);
257
258	#
259	#   Create a list of variables without the types prepended.
260	#
261	sub(/^[	 ]+/, "", line);	# remove leading ...
262	sub(/[ 	]+$/, "", line);	# ... and trailing whitespace
263	gsub(/[	 ]+/, " ", line);	# remove double spaces
264
265	num_arguments = split(line, arguments, / *; */) - 1;
266	delete varnames;		# list of varnames
267	num_varnames = 0;
268	for (i = 1; i <= num_arguments; i++) {
269		if (!arguments[i])
270			continue;	# skip argument if argument is empty
271		num_ar = split(arguments[i], ar, /[* 	]+/);
272		if (num_ar < 2) {	# only 1 word in argument?
273			warnsrc("no type for '" arguments[i] "'");
274			error = 1;
275			return;
276		}
277		#   Last element is name of variable.
278		varnames[++num_varnames] = ar[num_ar];
279	}
280
281	argument_list = join(", ", arguments, num_arguments);
282	varname_list = join(", ", varnames, num_varnames);
283
284	if (opt_d) {
285		warn("Arguments: " argument_list);
286		warn("Varnames: " varname_list);
287	}
288
289	mname = intname "_" name;	# method name
290	umname = toupper(mname);	# uppercase method name
291
292	firstvar = varnames[1];
293
294	if (default_function == "")
295		default_function = "kobj_error_method";
296
297	# the method description
298	printh("/** @brief Unique descriptor for the " umname "() method */");
299	printh("extern struct kobjop_desc " mname "_desc;");
300	# the method typedef
301	printh("/** @brief A function implementing the " umname "() method */");
302	prototype = "typedef " ret " " mname "_t(";
303	printh(format_line(prototype argument_list ");",
304	    line_width, length(prototype)));
305
306	# Print out the method desc
307	printc("struct kobjop_desc " mname "_desc = {");
308	printc("\t0, { &" mname "_desc, (kobjop_t)" default_function " }");
309	printc("};\n");
310
311	# Print out the method itself
312	printh(doc);
313	if (0) {		# haven't chosen the format yet
314		printh("static __inline " ret " " umname "(" varname_list ")");
315		printh("\t" join(";\n\t", arguments, num_arguments) ";");
316	}
317	else {
318		prototype = "static __inline " ret " " umname "(";
319		printh(format_line(prototype argument_list ")",
320		    line_width, length(prototype)));
321	}
322	printh("{");
323	printh("\tkobjop_t _m;");
324	if (ret != "void")
325		printh("\t" ret " rc;");
326	if (!static)
327		firstvar = "((kobj_t)" firstvar ")";
328	if (prolog != "")
329		printh(prolog);
330	printh("\tKOBJOPLOOKUP(" firstvar "->ops," mname ");");
331	rceq = (ret != "void") ? "rc = " : "";
332	printh("\t" rceq "((" mname "_t *) _m)(" varname_list ");");
333	if (epilog != "")
334		printh(epilog);
335	if (ret != "void")
336		printh("\treturn (rc);");
337	printh("}\n");
338}
339
340#
341#   Begin of the main program.
342#
343
344BEGIN {
345
346line_width = 80;
347gerror = 0;
348
349#
350#   Process the command line.
351#
352
353num_files = 0;
354
355for (i = 1; i < ARGC; i++) {
356	if (ARGV[i] ~ /^-/) {
357		#
358		#   awk doesn't have getopt(), so we have to do it ourselves.
359		#   This is a bit clumsy, but it works.
360		#
361		for (j = 2; j <= length(ARGV[i]); j++) {
362			o = substr(ARGV[i], j, 1);
363			if	(o == "c")	opt_c = 1;
364			else if	(o == "h")	opt_h = 1;
365			else if	(o == "p")	opt_p = 1;
366			else if	(o == "d")	opt_d = 1;
367			else if	(o == "l") {
368				if (length(ARGV[i]) > j) {
369					opt_l = substr(ARGV[i], j + 1);
370					break;
371				}
372				else {
373					if (++i < ARGC)
374						opt_l = ARGV[i];
375					else
376						usage();
377				}
378			}
379			else
380				usage();
381		}
382	}
383	else if (ARGV[i] ~ /\.m$/)
384		filenames[num_files++] = ARGV[i];
385	else
386		usage();
387}
388
389if (!num_files || !(opt_c || opt_h))
390	usage();
391
392if (opt_p)
393	debug("Will produce files in original not in current directory");
394
395if (opt_l) {
396	if (opt_l !~ /^[0-9]+$/ || opt_l < 1)
397		die("Invalid line width '" opt_l "'");
398	line_width = opt_l;
399	debug("Line width set to " line_width);
400}
401
402for (i = 0; i < num_files; i++)
403	debug("Filename: " filenames[i]);
404
405for (file_i = 0; file_i < num_files; file_i++) {
406	src = filenames[file_i];
407	cfilename = hfilename = src;
408	sub(/\.m$/, ".c", cfilename);
409	sub(/\.m$/, ".h", hfilename);
410	if (!opt_p) {
411		sub(/^.*\//, "", cfilename);
412		sub(/^.*\//, "", hfilename);
413	}
414
415	debug("Processing from " src " to " cfilename " / " hfilename);
416
417	ctmpfilename = cfilename ".tmp";
418	htmpfilename = hfilename ".tmp";
419
420	# Avoid a literal generated file tag here.
421	generated = "@" "generated";
422
423	common_head = \
424	    "/*\n" \
425	    " * This file is " generated " automatically.\n" \
426	    " * Do not modify anything in here by hand.\n" \
427	    " *\n" \
428	    " * Created from source file\n" \
429	    " *   " src "\n" \
430	    " * with\n" \
431	    " *   makeobjops.awk\n" \
432	    " *\n" \
433	    " * See the source file for legal information\n" \
434	    " */\n";
435
436	printc(common_head "\n" \
437	    "#include <sys/param.h>\n" \
438	    "#include <sys/queue.h>\n" \
439	    "#include <sys/kernel.h>\n" \
440	    "#include <sys/kobj.h>");
441
442	printh(common_head);
443
444	delete methods;		# clear list of methods
445	intname = "";
446	lineno = 0;
447	error = 0;		# to signal clean up and gerror setting
448	lastdoc = "";
449	prolog = "";
450	epilog = "";
451
452	while (!error && (getline < src) > 0) {
453		lineno++;
454
455		#
456		#   Take special notice of include directives.
457		#
458		if (/^#[ 	]*include[ 	]+["<][^">]+[">]/) {
459			incld = $0;
460			sub(/^#[ 	]*include[ 	]+/, "", incld);
461			debug("Included file: " incld);
462			printc("#include " incld);
463		}
464		else if (/^#[ 	]*if/ || /^#[   ]*else/ || /^#[   ]*elif/ ||
465		    /^#[   ]*endif/) {
466			printh($0);
467			printc($0);
468		}
469
470		sub(/#.*/, "");		# remove comments
471		sub(/^[	 ]+/, "");	# remove leading ...
472		sub(/[ 	]+$/, "");	# ... and trailing whitespace
473
474		if (/^$/) {		# skip empty lines
475		}
476		else if (/^\/\*\*/)
477			lastdoc = handle_doc();
478		else if (/^INTERFACE[ 	]+[^ 	;]*[ 	]*;?[ 	]*$/) {
479			printh(lastdoc);
480			lastdoc = "";
481			handle_interface();
482		} else if (/^CODE[ 	]*{$/)
483			printc(handle_code());
484		else if (/^HEADER[	 ]*{$/)
485			printh(handle_code());
486		else if (/^METHOD/) {
487			handle_method(0, lastdoc);
488			lastdoc = "";
489			prolog = "";
490			epilog = "";
491		} else if (/^STATICMETHOD/) {
492			handle_method(1, lastdoc);
493			lastdoc = "";
494			prolog = "";
495			epilog = "";
496		} else if (/^PROLOG[ 	]*{$/)
497			prolog = handle_code();
498		else if (/^EPILOG[ 	]*{$/)
499			epilog = handle_code();
500		else {
501			debug($0);
502			warnsrc("Invalid line encountered");
503			error = 1;
504		}
505	}
506
507	#
508	#   Print the final '#endif' in the header file.
509	#
510	printh("#endif /* _" intname "_if_h_ */");
511
512	close (ctmpfilename);
513	close (htmpfilename);
514
515	if (error) {
516		warn("Output skipped");
517		system_check("rm -f " ctmpfilename " " htmpfilename);
518		gerror = 1;
519	}
520	else {
521		if (opt_c)
522			system_check("mv -f " ctmpfilename " " cfilename);
523		if (opt_h)
524			system_check("mv -f " htmpfilename " " hfilename);
525	}
526}
527
528exit gerror;
529
530}
531