xref: /linux/scripts/kernel-doc (revision eab795ddd84ffdb1c67250062d01a81be20bb208)
1#!/usr/bin/env perl
2# SPDX-License-Identifier: GPL-2.0
3
4use warnings;
5use strict;
6
7## Copyright (c) 1998 Michael Zucchi, All Rights Reserved        ##
8## Copyright (C) 2000, 1  Tim Waugh <twaugh@redhat.com>          ##
9## Copyright (C) 2001  Simon Huggins                             ##
10## Copyright (C) 2005-2012  Randy Dunlap                         ##
11## Copyright (C) 2012  Dan Luedtke                               ##
12## 								 ##
13## #define enhancements by Armin Kuster <akuster@mvista.com>	 ##
14## Copyright (c) 2000 MontaVista Software, Inc.			 ##
15## 								 ##
16## This software falls under the GNU General Public License.     ##
17## Please read the COPYING file for more information             ##
18
19# 18/01/2001 - 	Cleanups
20# 		Functions prototyped as foo(void) same as foo()
21# 		Stop eval'ing where we don't need to.
22# -- huggie@earth.li
23
24# 27/06/2001 -  Allowed whitespace after initial "/**" and
25#               allowed comments before function declarations.
26# -- Christian Kreibich <ck@whoop.org>
27
28# Still to do:
29# 	- add perldoc documentation
30# 	- Look more closely at some of the scarier bits :)
31
32# 26/05/2001 - 	Support for separate source and object trees.
33#		Return error code.
34# 		Keith Owens <kaos@ocs.com.au>
35
36# 23/09/2001 - Added support for typedefs, structs, enums and unions
37#              Support for Context section; can be terminated using empty line
38#              Small fixes (like spaces vs. \s in regex)
39# -- Tim Jansen <tim@tjansen.de>
40
41# 25/07/2012 - Added support for HTML5
42# -- Dan Luedtke <mail@danrl.de>
43
44sub usage {
45    my $message = <<"EOF";
46Usage: $0 [OPTION ...] FILE ...
47
48Read C language source or header FILEs, extract embedded documentation comments,
49and print formatted documentation to standard output.
50
51The documentation comments are identified by "/**" opening comment mark. See
52Documentation/doc-guide/kernel-doc.rst for the documentation comment syntax.
53
54Output format selection (mutually exclusive):
55  -man			Output troff manual page format. This is the default.
56  -rst			Output reStructuredText format.
57  -none			Do not output documentation, only warnings.
58
59Output selection (mutually exclusive):
60  -export		Only output documentation for symbols that have been
61			exported using EXPORT_SYMBOL() or EXPORT_SYMBOL_GPL()
62                        in any input FILE or -export-file FILE.
63  -internal		Only output documentation for symbols that have NOT been
64			exported using EXPORT_SYMBOL() or EXPORT_SYMBOL_GPL()
65                        in any input FILE or -export-file FILE.
66  -function NAME	Only output documentation for the given function(s)
67			or DOC: section title(s). All other functions and DOC:
68			sections are ignored. May be specified multiple times.
69  -nosymbol NAME	Exclude the specified symbols from the output
70		        documentation. May be specified multiple times.
71
72Output selection modifiers:
73  -no-doc-sections	Do not output DOC: sections.
74  -enable-lineno        Enable output of #define LINENO lines. Only works with
75                        reStructuredText format.
76  -export-file FILE     Specify an additional FILE in which to look for
77                        EXPORT_SYMBOL() and EXPORT_SYMBOL_GPL(). To be used with
78                        -export or -internal. May be specified multiple times.
79
80Other parameters:
81  -v			Verbose output, more warnings and other information.
82  -h			Print this help.
83  -Werror		Treat warnings as errors.
84
85EOF
86    print $message;
87    exit 1;
88}
89
90#
91# format of comments.
92# In the following table, (...)? signifies optional structure.
93#                         (...)* signifies 0 or more structure elements
94# /**
95#  * function_name(:)? (- short description)?
96# (* @parameterx: (description of parameter x)?)*
97# (* a blank line)?
98#  * (Description:)? (Description of function)?
99#  * (section header: (section description)? )*
100#  (*)?*/
101#
102# So .. the trivial example would be:
103#
104# /**
105#  * my_function
106#  */
107#
108# If the Description: header tag is omitted, then there must be a blank line
109# after the last parameter specification.
110# e.g.
111# /**
112#  * my_function - does my stuff
113#  * @my_arg: its mine damnit
114#  *
115#  * Does my stuff explained.
116#  */
117#
118#  or, could also use:
119# /**
120#  * my_function - does my stuff
121#  * @my_arg: its mine damnit
122#  * Description: Does my stuff explained.
123#  */
124# etc.
125#
126# Besides functions you can also write documentation for structs, unions,
127# enums and typedefs. Instead of the function name you must write the name
128# of the declaration;  the struct/union/enum/typedef must always precede
129# the name. Nesting of declarations is not supported.
130# Use the argument mechanism to document members or constants.
131# e.g.
132# /**
133#  * struct my_struct - short description
134#  * @a: first member
135#  * @b: second member
136#  *
137#  * Longer description
138#  */
139# struct my_struct {
140#     int a;
141#     int b;
142# /* private: */
143#     int c;
144# };
145#
146# All descriptions can be multiline, except the short function description.
147#
148# For really longs structs, you can also describe arguments inside the
149# body of the struct.
150# eg.
151# /**
152#  * struct my_struct - short description
153#  * @a: first member
154#  * @b: second member
155#  *
156#  * Longer description
157#  */
158# struct my_struct {
159#     int a;
160#     int b;
161#     /**
162#      * @c: This is longer description of C
163#      *
164#      * You can use paragraphs to describe arguments
165#      * using this method.
166#      */
167#     int c;
168# };
169#
170# This should be use only for struct/enum members.
171#
172# You can also add additional sections. When documenting kernel functions you
173# should document the "Context:" of the function, e.g. whether the functions
174# can be called form interrupts. Unlike other sections you can end it with an
175# empty line.
176# A non-void function should have a "Return:" section describing the return
177# value(s).
178# Example-sections should contain the string EXAMPLE so that they are marked
179# appropriately in DocBook.
180#
181# Example:
182# /**
183#  * user_function - function that can only be called in user context
184#  * @a: some argument
185#  * Context: !in_interrupt()
186#  *
187#  * Some description
188#  * Example:
189#  *    user_function(22);
190#  */
191# ...
192#
193#
194# All descriptive text is further processed, scanning for the following special
195# patterns, which are highlighted appropriately.
196#
197# 'funcname()' - function
198# '$ENVVAR' - environmental variable
199# '&struct_name' - name of a structure (up to two words including 'struct')
200# '&struct_name.member' - name of a structure member
201# '@parameter' - name of a parameter
202# '%CONST' - name of a constant.
203# '``LITERAL``' - literal string without any spaces on it.
204
205## init lots of data
206
207my $errors = 0;
208my $warnings = 0;
209my $anon_struct_union = 0;
210
211# match expressions used to find embedded type information
212my $type_constant = '\b``([^\`]+)``\b';
213my $type_constant2 = '\%([-_\w]+)';
214my $type_func = '(\w+)\(\)';
215my $type_param = '\@(\w*((\.\w+)|(->\w+))*(\.\.\.)?)';
216my $type_param_ref = '([\!]?)\@(\w*((\.\w+)|(->\w+))*(\.\.\.)?)';
217my $type_fp_param = '\@(\w+)\(\)';  # Special RST handling for func ptr params
218my $type_fp_param2 = '\@(\w+->\S+)\(\)';  # Special RST handling for structs with func ptr params
219my $type_env = '(\$\w+)';
220my $type_enum = '\&(enum\s*([_\w]+))';
221my $type_struct = '\&(struct\s*([_\w]+))';
222my $type_typedef = '\&(typedef\s*([_\w]+))';
223my $type_union = '\&(union\s*([_\w]+))';
224my $type_member = '\&([_\w]+)(\.|->)([_\w]+)';
225my $type_fallback = '\&([_\w]+)';
226my $type_member_func = $type_member . '\(\)';
227
228# Output conversion substitutions.
229#  One for each output format
230
231# these are pretty rough
232my @highlights_man = (
233                      [$type_constant, "\$1"],
234                      [$type_constant2, "\$1"],
235                      [$type_func, "\\\\fB\$1\\\\fP"],
236                      [$type_enum, "\\\\fI\$1\\\\fP"],
237                      [$type_struct, "\\\\fI\$1\\\\fP"],
238                      [$type_typedef, "\\\\fI\$1\\\\fP"],
239                      [$type_union, "\\\\fI\$1\\\\fP"],
240                      [$type_param, "\\\\fI\$1\\\\fP"],
241                      [$type_param_ref, "\\\\fI\$1\$2\\\\fP"],
242                      [$type_member, "\\\\fI\$1\$2\$3\\\\fP"],
243                      [$type_fallback, "\\\\fI\$1\\\\fP"]
244		     );
245my $blankline_man = "";
246
247# rst-mode
248my @highlights_rst = (
249                       [$type_constant, "``\$1``"],
250                       [$type_constant2, "``\$1``"],
251                       # Note: need to escape () to avoid func matching later
252                       [$type_member_func, "\\:c\\:type\\:`\$1\$2\$3\\\\(\\\\) <\$1>`"],
253                       [$type_member, "\\:c\\:type\\:`\$1\$2\$3 <\$1>`"],
254		       [$type_fp_param, "**\$1\\\\(\\\\)**"],
255		       [$type_fp_param2, "**\$1\\\\(\\\\)**"],
256                       [$type_func, "\$1()"],
257                       [$type_enum, "\\:c\\:type\\:`\$1 <\$2>`"],
258                       [$type_struct, "\\:c\\:type\\:`\$1 <\$2>`"],
259                       [$type_typedef, "\\:c\\:type\\:`\$1 <\$2>`"],
260                       [$type_union, "\\:c\\:type\\:`\$1 <\$2>`"],
261                       # in rst this can refer to any type
262                       [$type_fallback, "\\:c\\:type\\:`\$1`"],
263                       [$type_param_ref, "**\$1\$2**"]
264		      );
265my $blankline_rst = "\n";
266
267# read arguments
268if ($#ARGV == -1) {
269    usage();
270}
271
272my $kernelversion;
273my $sphinx_major;
274
275my $dohighlight = "";
276
277my $verbose = 0;
278my $Werror = 0;
279my $output_mode = "rst";
280my $output_preformatted = 0;
281my $no_doc_sections = 0;
282my $enable_lineno = 0;
283my @highlights = @highlights_rst;
284my $blankline = $blankline_rst;
285my $modulename = "Kernel API";
286
287use constant {
288    OUTPUT_ALL          => 0, # output all symbols and doc sections
289    OUTPUT_INCLUDE      => 1, # output only specified symbols
290    OUTPUT_EXPORTED     => 2, # output exported symbols
291    OUTPUT_INTERNAL     => 3, # output non-exported symbols
292};
293my $output_selection = OUTPUT_ALL;
294my $show_not_found = 0;	# No longer used
295
296my @export_file_list;
297
298my @build_time;
299if (defined($ENV{'KBUILD_BUILD_TIMESTAMP'}) &&
300    (my $seconds = `date -d"${ENV{'KBUILD_BUILD_TIMESTAMP'}}" +%s`) ne '') {
301    @build_time = gmtime($seconds);
302} else {
303    @build_time = localtime;
304}
305
306my $man_date = ('January', 'February', 'March', 'April', 'May', 'June',
307		'July', 'August', 'September', 'October',
308		'November', 'December')[$build_time[4]] .
309  " " . ($build_time[5]+1900);
310
311# Essentially these are globals.
312# They probably want to be tidied up, made more localised or something.
313# CAVEAT EMPTOR!  Some of the others I localised may not want to be, which
314# could cause "use of undefined value" or other bugs.
315my ($function, %function_table, %parametertypes, $declaration_purpose);
316my %nosymbol_table = ();
317my $declaration_start_line;
318my ($type, $declaration_name, $return_type);
319my ($newsection, $newcontents, $prototype, $brcount, %source_map);
320
321if (defined($ENV{'KBUILD_VERBOSE'})) {
322	$verbose = "$ENV{'KBUILD_VERBOSE'}";
323}
324
325if (defined($ENV{'KDOC_WERROR'})) {
326	$Werror = "$ENV{'KDOC_WERROR'}";
327}
328
329if (defined($ENV{'KCFLAGS'})) {
330	my $kcflags = "$ENV{'KCFLAGS'}";
331
332	if ($kcflags =~ /Werror/) {
333		$Werror = 1;
334	}
335}
336
337# Generated docbook code is inserted in a template at a point where
338# docbook v3.1 requires a non-zero sequence of RefEntry's; see:
339# https://www.oasis-open.org/docbook/documentation/reference/html/refentry.html
340# We keep track of number of generated entries and generate a dummy
341# if needs be to ensure the expanded template can be postprocessed
342# into html.
343my $section_counter = 0;
344
345my $lineprefix="";
346
347# Parser states
348use constant {
349    STATE_NORMAL        => 0,        # normal code
350    STATE_NAME          => 1,        # looking for function name
351    STATE_BODY_MAYBE    => 2,        # body - or maybe more description
352    STATE_BODY          => 3,        # the body of the comment
353    STATE_BODY_WITH_BLANK_LINE => 4, # the body, which has a blank line
354    STATE_PROTO         => 5,        # scanning prototype
355    STATE_DOCBLOCK      => 6,        # documentation block
356    STATE_INLINE        => 7,        # gathering doc outside main block
357};
358my $state;
359my $in_doc_sect;
360my $leading_space;
361
362# Inline documentation state
363use constant {
364    STATE_INLINE_NA     => 0, # not applicable ($state != STATE_INLINE)
365    STATE_INLINE_NAME   => 1, # looking for member name (@foo:)
366    STATE_INLINE_TEXT   => 2, # looking for member documentation
367    STATE_INLINE_END    => 3, # done
368    STATE_INLINE_ERROR  => 4, # error - Comment without header was found.
369                              # Spit a warning as it's not
370                              # proper kernel-doc and ignore the rest.
371};
372my $inline_doc_state;
373
374#declaration types: can be
375# 'function', 'struct', 'union', 'enum', 'typedef'
376my $decl_type;
377
378my $doc_start = '^/\*\*\s*$'; # Allow whitespace at end of comment start.
379my $doc_end = '\*/';
380my $doc_com = '\s*\*\s*';
381my $doc_com_body = '\s*\* ?';
382my $doc_decl = $doc_com . '(\w+)';
383# @params and a strictly limited set of supported section names
384my $doc_sect = $doc_com .
385    '\s*(\@[.\w]+|\@\.\.\.|description|context|returns?|notes?|examples?)\s*:(.*)';
386my $doc_content = $doc_com_body . '(.*)';
387my $doc_block = $doc_com . 'DOC:\s*(.*)?';
388my $doc_inline_start = '^\s*/\*\*\s*$';
389my $doc_inline_sect = '\s*\*\s*(@\s*[\w][\w\.]*\s*):(.*)';
390my $doc_inline_end = '^\s*\*/\s*$';
391my $doc_inline_oneline = '^\s*/\*\*\s*(@[\w\s]+):\s*(.*)\s*\*/\s*$';
392my $export_symbol = '^\s*EXPORT_SYMBOL(_GPL)?\s*\(\s*(\w+)\s*\)\s*;';
393
394my %parameterdescs;
395my %parameterdesc_start_lines;
396my @parameterlist;
397my %sections;
398my @sectionlist;
399my %section_start_lines;
400my $sectcheck;
401my $struct_actual;
402
403my $contents = "";
404my $new_start_line = 0;
405
406# the canonical section names. see also $doc_sect above.
407my $section_default = "Description";	# default section
408my $section_intro = "Introduction";
409my $section = $section_default;
410my $section_context = "Context";
411my $section_return = "Return";
412
413my $undescribed = "-- undescribed --";
414
415reset_state();
416
417while ($ARGV[0] =~ m/^--?(.*)/) {
418    my $cmd = $1;
419    shift @ARGV;
420    if ($cmd eq "man") {
421	$output_mode = "man";
422	@highlights = @highlights_man;
423	$blankline = $blankline_man;
424    } elsif ($cmd eq "rst") {
425	$output_mode = "rst";
426	@highlights = @highlights_rst;
427	$blankline = $blankline_rst;
428    } elsif ($cmd eq "none") {
429	$output_mode = "none";
430    } elsif ($cmd eq "module") { # not needed for XML, inherits from calling document
431	$modulename = shift @ARGV;
432    } elsif ($cmd eq "function") { # to only output specific functions
433	$output_selection = OUTPUT_INCLUDE;
434	$function = shift @ARGV;
435	$function_table{$function} = 1;
436    } elsif ($cmd eq "nosymbol") { # Exclude specific symbols
437	my $symbol = shift @ARGV;
438	$nosymbol_table{$symbol} = 1;
439    } elsif ($cmd eq "export") { # only exported symbols
440	$output_selection = OUTPUT_EXPORTED;
441	%function_table = ();
442    } elsif ($cmd eq "internal") { # only non-exported symbols
443	$output_selection = OUTPUT_INTERNAL;
444	%function_table = ();
445    } elsif ($cmd eq "export-file") {
446	my $file = shift @ARGV;
447	push(@export_file_list, $file);
448    } elsif ($cmd eq "v") {
449	$verbose = 1;
450    } elsif ($cmd eq "Werror") {
451	$Werror = 1;
452    } elsif (($cmd eq "h") || ($cmd eq "help")) {
453	usage();
454    } elsif ($cmd eq 'no-doc-sections') {
455	    $no_doc_sections = 1;
456    } elsif ($cmd eq 'enable-lineno') {
457	    $enable_lineno = 1;
458    } elsif ($cmd eq 'show-not-found') {
459	$show_not_found = 1;  # A no-op but don't fail
460    } else {
461	# Unknown argument
462        usage();
463    }
464}
465
466# continue execution near EOF;
467
468# The C domain dialect changed on Sphinx 3. So, we need to check the
469# version in order to produce the right tags.
470sub findprog($)
471{
472	foreach(split(/:/, $ENV{PATH})) {
473		return "$_/$_[0]" if(-x "$_/$_[0]");
474	}
475}
476
477sub get_sphinx_version()
478{
479	my $ver;
480	my $major = 1;
481
482	my $cmd = "sphinx-build";
483	if (!findprog($cmd)) {
484		my $cmd = "sphinx-build3";
485		return $major if (!findprog($cmd));
486	}
487
488	open IN, "$cmd --version 2>&1 |";
489	while (<IN>) {
490		if (m/^\s*sphinx-build\s+([\d]+)\.([\d\.]+)(\+\/[\da-f]+)?$/) {
491			$major=$1;
492			last;
493		}
494		# Sphinx 1.2.x uses a different format
495		if (m/^\s*Sphinx.*\s+([\d]+)\.([\d\.]+)$/) {
496			$major=$1;
497			last;
498		}
499	}
500	close IN;
501
502	return $major;
503}
504
505# get kernel version from env
506sub get_kernel_version() {
507    my $version = 'unknown kernel version';
508
509    if (defined($ENV{'KERNELVERSION'})) {
510	$version = $ENV{'KERNELVERSION'};
511    }
512    return $version;
513}
514
515#
516sub print_lineno {
517    my $lineno = shift;
518    if ($enable_lineno && defined($lineno)) {
519        print "#define LINENO " . $lineno . "\n";
520    }
521}
522##
523# dumps section contents to arrays/hashes intended for that purpose.
524#
525sub dump_section {
526    my $file = shift;
527    my $name = shift;
528    my $contents = join "\n", @_;
529
530    if ($name =~ m/$type_param/) {
531	$name = $1;
532	$parameterdescs{$name} = $contents;
533	$sectcheck = $sectcheck . $name . " ";
534        $parameterdesc_start_lines{$name} = $new_start_line;
535        $new_start_line = 0;
536    } elsif ($name eq "@\.\.\.") {
537	$name = "...";
538	$parameterdescs{$name} = $contents;
539	$sectcheck = $sectcheck . $name . " ";
540        $parameterdesc_start_lines{$name} = $new_start_line;
541        $new_start_line = 0;
542    } else {
543	if (defined($sections{$name}) && ($sections{$name} ne "")) {
544	    # Only warn on user specified duplicate section names.
545	    if ($name ne $section_default) {
546		print STDERR "${file}:$.: warning: duplicate section name '$name'\n";
547		++$warnings;
548	    }
549	    $sections{$name} .= $contents;
550	} else {
551	    $sections{$name} = $contents;
552	    push @sectionlist, $name;
553            $section_start_lines{$name} = $new_start_line;
554            $new_start_line = 0;
555	}
556    }
557}
558
559##
560# dump DOC: section after checking that it should go out
561#
562sub dump_doc_section {
563    my $file = shift;
564    my $name = shift;
565    my $contents = join "\n", @_;
566
567    if ($no_doc_sections) {
568        return;
569    }
570
571    return if (defined($nosymbol_table{$name}));
572
573    if (($output_selection == OUTPUT_ALL) ||
574	(($output_selection == OUTPUT_INCLUDE) &&
575	 defined($function_table{$name})))
576    {
577	dump_section($file, $name, $contents);
578	output_blockhead({'sectionlist' => \@sectionlist,
579			  'sections' => \%sections,
580			  'module' => $modulename,
581			  'content-only' => ($output_selection != OUTPUT_ALL), });
582    }
583}
584
585##
586# output function
587#
588# parameterdescs, a hash.
589#  function => "function name"
590#  parameterlist => @list of parameters
591#  parameterdescs => %parameter descriptions
592#  sectionlist => @list of sections
593#  sections => %section descriptions
594#
595
596sub output_highlight {
597    my $contents = join "\n",@_;
598    my $line;
599
600#   DEBUG
601#   if (!defined $contents) {
602#	use Carp;
603#	confess "output_highlight got called with no args?\n";
604#   }
605
606#   print STDERR "contents b4:$contents\n";
607    eval $dohighlight;
608    die $@ if $@;
609#   print STDERR "contents af:$contents\n";
610
611    foreach $line (split "\n", $contents) {
612	if (! $output_preformatted) {
613	    $line =~ s/^\s*//;
614	}
615	if ($line eq ""){
616	    if (! $output_preformatted) {
617		print $lineprefix, $blankline;
618	    }
619	} else {
620	    if ($output_mode eq "man" && substr($line, 0, 1) eq ".") {
621		print "\\&$line";
622	    } else {
623		print $lineprefix, $line;
624	    }
625	}
626	print "\n";
627    }
628}
629
630##
631# output function in man
632sub output_function_man(%) {
633    my %args = %{$_[0]};
634    my ($parameter, $section);
635    my $count;
636
637    print ".TH \"$args{'function'}\" 9 \"$args{'function'}\" \"$man_date\" \"Kernel Hacker's Manual\" LINUX\n";
638
639    print ".SH NAME\n";
640    print $args{'function'} . " \\- " . $args{'purpose'} . "\n";
641
642    print ".SH SYNOPSIS\n";
643    if ($args{'functiontype'} ne "") {
644	print ".B \"" . $args{'functiontype'} . "\" " . $args{'function'} . "\n";
645    } else {
646	print ".B \"" . $args{'function'} . "\n";
647    }
648    $count = 0;
649    my $parenth = "(";
650    my $post = ",";
651    foreach my $parameter (@{$args{'parameterlist'}}) {
652	if ($count == $#{$args{'parameterlist'}}) {
653	    $post = ");";
654	}
655	$type = $args{'parametertypes'}{$parameter};
656	if ($type =~ m/([^\(]*\(\*)\s*\)\s*\(([^\)]*)\)/) {
657	    # pointer-to-function
658	    print ".BI \"" . $parenth . $1 . "\" " . $parameter . " \") (" . $2 . ")" . $post . "\"\n";
659	} else {
660	    $type =~ s/([^\*])$/$1 /;
661	    print ".BI \"" . $parenth . $type . "\" " . $parameter . " \"" . $post . "\"\n";
662	}
663	$count++;
664	$parenth = "";
665    }
666
667    print ".SH ARGUMENTS\n";
668    foreach $parameter (@{$args{'parameterlist'}}) {
669	my $parameter_name = $parameter;
670	$parameter_name =~ s/\[.*//;
671
672	print ".IP \"" . $parameter . "\" 12\n";
673	output_highlight($args{'parameterdescs'}{$parameter_name});
674    }
675    foreach $section (@{$args{'sectionlist'}}) {
676	print ".SH \"", uc $section, "\"\n";
677	output_highlight($args{'sections'}{$section});
678    }
679}
680
681##
682# output enum in man
683sub output_enum_man(%) {
684    my %args = %{$_[0]};
685    my ($parameter, $section);
686    my $count;
687
688    print ".TH \"$args{'module'}\" 9 \"enum $args{'enum'}\" \"$man_date\" \"API Manual\" LINUX\n";
689
690    print ".SH NAME\n";
691    print "enum " . $args{'enum'} . " \\- " . $args{'purpose'} . "\n";
692
693    print ".SH SYNOPSIS\n";
694    print "enum " . $args{'enum'} . " {\n";
695    $count = 0;
696    foreach my $parameter (@{$args{'parameterlist'}}) {
697	print ".br\n.BI \"    $parameter\"\n";
698	if ($count == $#{$args{'parameterlist'}}) {
699	    print "\n};\n";
700	    last;
701	}
702	else {
703	    print ", \n.br\n";
704	}
705	$count++;
706    }
707
708    print ".SH Constants\n";
709    foreach $parameter (@{$args{'parameterlist'}}) {
710	my $parameter_name = $parameter;
711	$parameter_name =~ s/\[.*//;
712
713	print ".IP \"" . $parameter . "\" 12\n";
714	output_highlight($args{'parameterdescs'}{$parameter_name});
715    }
716    foreach $section (@{$args{'sectionlist'}}) {
717	print ".SH \"$section\"\n";
718	output_highlight($args{'sections'}{$section});
719    }
720}
721
722##
723# output struct in man
724sub output_struct_man(%) {
725    my %args = %{$_[0]};
726    my ($parameter, $section);
727
728    print ".TH \"$args{'module'}\" 9 \"" . $args{'type'} . " " . $args{'struct'} . "\" \"$man_date\" \"API Manual\" LINUX\n";
729
730    print ".SH NAME\n";
731    print $args{'type'} . " " . $args{'struct'} . " \\- " . $args{'purpose'} . "\n";
732
733    my $declaration = $args{'definition'};
734    $declaration =~ s/\t/  /g;
735    $declaration =~ s/\n/"\n.br\n.BI \"/g;
736    print ".SH SYNOPSIS\n";
737    print $args{'type'} . " " . $args{'struct'} . " {\n.br\n";
738    print ".BI \"$declaration\n};\n.br\n\n";
739
740    print ".SH Members\n";
741    foreach $parameter (@{$args{'parameterlist'}}) {
742	($parameter =~ /^#/) && next;
743
744	my $parameter_name = $parameter;
745	$parameter_name =~ s/\[.*//;
746
747	($args{'parameterdescs'}{$parameter_name} ne $undescribed) || next;
748	print ".IP \"" . $parameter . "\" 12\n";
749	output_highlight($args{'parameterdescs'}{$parameter_name});
750    }
751    foreach $section (@{$args{'sectionlist'}}) {
752	print ".SH \"$section\"\n";
753	output_highlight($args{'sections'}{$section});
754    }
755}
756
757##
758# output typedef in man
759sub output_typedef_man(%) {
760    my %args = %{$_[0]};
761    my ($parameter, $section);
762
763    print ".TH \"$args{'module'}\" 9 \"$args{'typedef'}\" \"$man_date\" \"API Manual\" LINUX\n";
764
765    print ".SH NAME\n";
766    print "typedef " . $args{'typedef'} . " \\- " . $args{'purpose'} . "\n";
767
768    foreach $section (@{$args{'sectionlist'}}) {
769	print ".SH \"$section\"\n";
770	output_highlight($args{'sections'}{$section});
771    }
772}
773
774sub output_blockhead_man(%) {
775    my %args = %{$_[0]};
776    my ($parameter, $section);
777    my $count;
778
779    print ".TH \"$args{'module'}\" 9 \"$args{'module'}\" \"$man_date\" \"API Manual\" LINUX\n";
780
781    foreach $section (@{$args{'sectionlist'}}) {
782	print ".SH \"$section\"\n";
783	output_highlight($args{'sections'}{$section});
784    }
785}
786
787##
788# output in restructured text
789#
790
791#
792# This could use some work; it's used to output the DOC: sections, and
793# starts by putting out the name of the doc section itself, but that tends
794# to duplicate a header already in the template file.
795#
796sub output_blockhead_rst(%) {
797    my %args = %{$_[0]};
798    my ($parameter, $section);
799
800    foreach $section (@{$args{'sectionlist'}}) {
801	next if (defined($nosymbol_table{$section}));
802
803	if ($output_selection != OUTPUT_INCLUDE) {
804	    print "**$section**\n\n";
805	}
806        print_lineno($section_start_lines{$section});
807	output_highlight_rst($args{'sections'}{$section});
808	print "\n";
809    }
810}
811
812#
813# Apply the RST highlights to a sub-block of text.
814#
815sub highlight_block($) {
816    # The dohighlight kludge requires the text be called $contents
817    my $contents = shift;
818    eval $dohighlight;
819    die $@ if $@;
820    return $contents;
821}
822
823#
824# Regexes used only here.
825#
826my $sphinx_literal = '^[^.].*::$';
827my $sphinx_cblock = '^\.\.\ +code-block::';
828
829sub output_highlight_rst {
830    my $input = join "\n",@_;
831    my $output = "";
832    my $line;
833    my $in_literal = 0;
834    my $litprefix;
835    my $block = "";
836
837    foreach $line (split "\n",$input) {
838	#
839	# If we're in a literal block, see if we should drop out
840	# of it.  Otherwise pass the line straight through unmunged.
841	#
842	if ($in_literal) {
843	    if (! ($line =~ /^\s*$/)) {
844		#
845		# If this is the first non-blank line in a literal
846		# block we need to figure out what the proper indent is.
847		#
848		if ($litprefix eq "") {
849		    $line =~ /^(\s*)/;
850		    $litprefix = '^' . $1;
851		    $output .= $line . "\n";
852		} elsif (! ($line =~ /$litprefix/)) {
853		    $in_literal = 0;
854		} else {
855		    $output .= $line . "\n";
856		}
857	    } else {
858		$output .= $line . "\n";
859	    }
860	}
861	#
862	# Not in a literal block (or just dropped out)
863	#
864	if (! $in_literal) {
865	    $block .= $line . "\n";
866	    if (($line =~ /$sphinx_literal/) || ($line =~ /$sphinx_cblock/)) {
867		$in_literal = 1;
868		$litprefix = "";
869		$output .= highlight_block($block);
870		$block = ""
871	    }
872	}
873    }
874
875    if ($block) {
876	$output .= highlight_block($block);
877    }
878    foreach $line (split "\n", $output) {
879	print $lineprefix . $line . "\n";
880    }
881}
882
883sub output_function_rst(%) {
884    my %args = %{$_[0]};
885    my ($parameter, $section);
886    my $oldprefix = $lineprefix;
887    my $start = "";
888
889    if ($sphinx_major < 3) {
890	if ($args{'typedef'}) {
891	    print ".. c:type:: ". $args{'function'} . "\n\n";
892	    print_lineno($declaration_start_line);
893	    print "   **Typedef**: ";
894	    $lineprefix = "";
895	    output_highlight_rst($args{'purpose'});
896	    $start = "\n\n**Syntax**\n\n  ``";
897	} else {
898	    print ".. c:function:: ";
899	}
900    } else {
901	print ".. c:macro:: ". $args{'function'} . "\n\n";
902
903	if ($args{'typedef'}) {
904	    print_lineno($declaration_start_line);
905	    print "   **Typedef**: ";
906	    $lineprefix = "";
907	    output_highlight_rst($args{'purpose'});
908	    $start = "\n\n**Syntax**\n\n  ``";
909	} else {
910	    print "``";
911	}
912    }
913    if ($args{'functiontype'} ne "") {
914	$start .= $args{'functiontype'} . " " . $args{'function'} . " (";
915    } else {
916	$start .= $args{'function'} . " (";
917    }
918    print $start;
919
920    my $count = 0;
921    foreach my $parameter (@{$args{'parameterlist'}}) {
922	if ($count ne 0) {
923	    print ", ";
924	}
925	$count++;
926	$type = $args{'parametertypes'}{$parameter};
927
928	if ($type =~ m/([^\(]*\(\*)\s*\)\s*\(([^\)]*)\)/) {
929	    # pointer-to-function
930	    print $1 . $parameter . ") (" . $2 . ")";
931	} else {
932	    print $type . " " . $parameter;
933	}
934    }
935    if ($args{'typedef'}) {
936	print ");``\n\n";
937    } else {
938	if ($sphinx_major < 3) {
939	    print ")\n\n";
940	} else {
941	    print ")``\n";
942	}
943	print_lineno($declaration_start_line);
944	$lineprefix = "   ";
945	output_highlight_rst($args{'purpose'});
946	print "\n";
947    }
948
949    print "**Parameters**\n\n";
950    $lineprefix = "  ";
951    foreach $parameter (@{$args{'parameterlist'}}) {
952	my $parameter_name = $parameter;
953	$parameter_name =~ s/\[.*//;
954	$type = $args{'parametertypes'}{$parameter};
955
956	if ($type ne "") {
957	    print "``$type $parameter``\n";
958	} else {
959	    print "``$parameter``\n";
960	}
961
962        print_lineno($parameterdesc_start_lines{$parameter_name});
963
964	if (defined($args{'parameterdescs'}{$parameter_name}) &&
965	    $args{'parameterdescs'}{$parameter_name} ne $undescribed) {
966	    output_highlight_rst($args{'parameterdescs'}{$parameter_name});
967	} else {
968	    print "  *undescribed*\n";
969	}
970	print "\n";
971    }
972
973    $lineprefix = $oldprefix;
974    output_section_rst(@_);
975}
976
977sub output_section_rst(%) {
978    my %args = %{$_[0]};
979    my $section;
980    my $oldprefix = $lineprefix;
981    $lineprefix = "";
982
983    foreach $section (@{$args{'sectionlist'}}) {
984	print "**$section**\n\n";
985        print_lineno($section_start_lines{$section});
986	output_highlight_rst($args{'sections'}{$section});
987	print "\n";
988    }
989    print "\n";
990    $lineprefix = $oldprefix;
991}
992
993sub output_enum_rst(%) {
994    my %args = %{$_[0]};
995    my ($parameter);
996    my $oldprefix = $lineprefix;
997    my $count;
998
999    if ($sphinx_major < 3) {
1000	my $name = "enum " . $args{'enum'};
1001	print "\n\n.. c:type:: " . $name . "\n\n";
1002    } else {
1003	my $name = $args{'enum'};
1004	print "\n\n.. c:enum:: " . $name . "\n\n";
1005    }
1006    print_lineno($declaration_start_line);
1007    $lineprefix = "   ";
1008    output_highlight_rst($args{'purpose'});
1009    print "\n";
1010
1011    print "**Constants**\n\n";
1012    $lineprefix = "  ";
1013    foreach $parameter (@{$args{'parameterlist'}}) {
1014	print "``$parameter``\n";
1015	if ($args{'parameterdescs'}{$parameter} ne $undescribed) {
1016	    output_highlight_rst($args{'parameterdescs'}{$parameter});
1017	} else {
1018	    print "  *undescribed*\n";
1019	}
1020	print "\n";
1021    }
1022
1023    $lineprefix = $oldprefix;
1024    output_section_rst(@_);
1025}
1026
1027sub output_typedef_rst(%) {
1028    my %args = %{$_[0]};
1029    my ($parameter);
1030    my $oldprefix = $lineprefix;
1031    my $name;
1032
1033    if ($sphinx_major < 3) {
1034	$name = "typedef " . $args{'typedef'};
1035    } else {
1036	$name = $args{'typedef'};
1037    }
1038    print "\n\n.. c:type:: " . $name . "\n\n";
1039    print_lineno($declaration_start_line);
1040    $lineprefix = "   ";
1041    output_highlight_rst($args{'purpose'});
1042    print "\n";
1043
1044    $lineprefix = $oldprefix;
1045    output_section_rst(@_);
1046}
1047
1048sub output_struct_rst(%) {
1049    my %args = %{$_[0]};
1050    my ($parameter);
1051    my $oldprefix = $lineprefix;
1052
1053    if ($sphinx_major < 3) {
1054	my $name = $args{'type'} . " " . $args{'struct'};
1055	print "\n\n.. c:type:: " . $name . "\n\n";
1056    } else {
1057	my $name = $args{'struct'};
1058	print "\n\n.. c:struct:: " . $name . "\n\n";
1059    }
1060    print_lineno($declaration_start_line);
1061    $lineprefix = "   ";
1062    output_highlight_rst($args{'purpose'});
1063    print "\n";
1064
1065    print "**Definition**\n\n";
1066    print "::\n\n";
1067    my $declaration = $args{'definition'};
1068    $declaration =~ s/\t/  /g;
1069    print "  " . $args{'type'} . " " . $args{'struct'} . " {\n$declaration  };\n\n";
1070
1071    print "**Members**\n\n";
1072    $lineprefix = "  ";
1073    foreach $parameter (@{$args{'parameterlist'}}) {
1074	($parameter =~ /^#/) && next;
1075
1076	my $parameter_name = $parameter;
1077	$parameter_name =~ s/\[.*//;
1078
1079	($args{'parameterdescs'}{$parameter_name} ne $undescribed) || next;
1080	$type = $args{'parametertypes'}{$parameter};
1081        print_lineno($parameterdesc_start_lines{$parameter_name});
1082	print "``" . $parameter . "``\n";
1083	output_highlight_rst($args{'parameterdescs'}{$parameter_name});
1084	print "\n";
1085    }
1086    print "\n";
1087
1088    $lineprefix = $oldprefix;
1089    output_section_rst(@_);
1090}
1091
1092## none mode output functions
1093
1094sub output_function_none(%) {
1095}
1096
1097sub output_enum_none(%) {
1098}
1099
1100sub output_typedef_none(%) {
1101}
1102
1103sub output_struct_none(%) {
1104}
1105
1106sub output_blockhead_none(%) {
1107}
1108
1109##
1110# generic output function for all types (function, struct/union, typedef, enum);
1111# calls the generated, variable output_ function name based on
1112# functype and output_mode
1113sub output_declaration {
1114    no strict 'refs';
1115    my $name = shift;
1116    my $functype = shift;
1117    my $func = "output_${functype}_$output_mode";
1118
1119    return if (defined($nosymbol_table{$name}));
1120
1121    if (($output_selection == OUTPUT_ALL) ||
1122	(($output_selection == OUTPUT_INCLUDE ||
1123	  $output_selection == OUTPUT_EXPORTED) &&
1124	 defined($function_table{$name})) ||
1125	($output_selection == OUTPUT_INTERNAL &&
1126	 !($functype eq "function" && defined($function_table{$name}))))
1127    {
1128	&$func(@_);
1129	$section_counter++;
1130    }
1131}
1132
1133##
1134# generic output function - calls the right one based on current output mode.
1135sub output_blockhead {
1136    no strict 'refs';
1137    my $func = "output_blockhead_" . $output_mode;
1138    &$func(@_);
1139    $section_counter++;
1140}
1141
1142##
1143# takes a declaration (struct, union, enum, typedef) and
1144# invokes the right handler. NOT called for functions.
1145sub dump_declaration($$) {
1146    no strict 'refs';
1147    my ($prototype, $file) = @_;
1148    my $func = "dump_" . $decl_type;
1149    &$func(@_);
1150}
1151
1152sub dump_union($$) {
1153    dump_struct(@_);
1154}
1155
1156sub dump_struct($$) {
1157    my $x = shift;
1158    my $file = shift;
1159
1160    if ($x =~ /(struct|union)\s+(\w+)\s*\{(.*)\}(\s*(__packed|__aligned|____cacheline_aligned_in_smp|____cacheline_aligned|__attribute__\s*\(\([a-z0-9,_\s\(\)]*\)\)))*/) {
1161	my $decl_type = $1;
1162	$declaration_name = $2;
1163	my $members = $3;
1164
1165	# ignore members marked private:
1166	$members =~ s/\/\*\s*private:.*?\/\*\s*public:.*?\*\///gosi;
1167	$members =~ s/\/\*\s*private:.*//gosi;
1168	# strip comments:
1169	$members =~ s/\/\*.*?\*\///gos;
1170	# strip attributes
1171	$members =~ s/\s*__attribute__\s*\(\([a-z0-9,_\*\s\(\)]*\)\)/ /gi;
1172	$members =~ s/\s*__aligned\s*\([^;]*\)/ /gos;
1173	$members =~ s/\s*__packed\s*/ /gos;
1174	$members =~ s/\s*CRYPTO_MINALIGN_ATTR/ /gos;
1175	$members =~ s/\s*____cacheline_aligned_in_smp/ /gos;
1176	$members =~ s/\s*____cacheline_aligned/ /gos;
1177
1178	# replace DECLARE_BITMAP
1179	$members =~ s/__ETHTOOL_DECLARE_LINK_MODE_MASK\s*\(([^\)]+)\)/DECLARE_BITMAP($1, __ETHTOOL_LINK_MODE_MASK_NBITS)/gos;
1180	$members =~ s/DECLARE_BITMAP\s*\(([^,)]+),\s*([^,)]+)\)/unsigned long $1\[BITS_TO_LONGS($2)\]/gos;
1181	# replace DECLARE_HASHTABLE
1182	$members =~ s/DECLARE_HASHTABLE\s*\(([^,)]+),\s*([^,)]+)\)/unsigned long $1\[1 << (($2) - 1)\]/gos;
1183	# replace DECLARE_KFIFO
1184	$members =~ s/DECLARE_KFIFO\s*\(([^,)]+),\s*([^,)]+),\s*([^,)]+)\)/$2 \*$1/gos;
1185	# replace DECLARE_KFIFO_PTR
1186	$members =~ s/DECLARE_KFIFO_PTR\s*\(([^,)]+),\s*([^,)]+)\)/$2 \*$1/gos;
1187
1188	my $declaration = $members;
1189
1190	# Split nested struct/union elements as newer ones
1191	while ($members =~ m/(struct|union)([^\{\};]+)\{([^\{\}]*)\}([^\{\}\;]*)\;/) {
1192		my $newmember;
1193		my $maintype = $1;
1194		my $ids = $4;
1195		my $content = $3;
1196		foreach my $id(split /,/, $ids) {
1197			$newmember .= "$maintype $id; ";
1198
1199			$id =~ s/[:\[].*//;
1200			$id =~ s/^\s*\**(\S+)\s*/$1/;
1201			foreach my $arg (split /;/, $content) {
1202				next if ($arg =~ m/^\s*$/);
1203				if ($arg =~ m/^([^\(]+\(\*?\s*)([\w\.]*)(\s*\).*)/) {
1204					# pointer-to-function
1205					my $type = $1;
1206					my $name = $2;
1207					my $extra = $3;
1208					next if (!$name);
1209					if ($id =~ m/^\s*$/) {
1210						# anonymous struct/union
1211						$newmember .= "$type$name$extra; ";
1212					} else {
1213						$newmember .= "$type$id.$name$extra; ";
1214					}
1215				} else {
1216					my $type;
1217					my $names;
1218					$arg =~ s/^\s+//;
1219					$arg =~ s/\s+$//;
1220					# Handle bitmaps
1221					$arg =~ s/:\s*\d+\s*//g;
1222					# Handle arrays
1223					$arg =~ s/\[.*\]//g;
1224					# The type may have multiple words,
1225					# and multiple IDs can be defined, like:
1226					#	const struct foo, *bar, foobar
1227					# So, we remove spaces when parsing the
1228					# names, in order to match just names
1229					# and commas for the names
1230					$arg =~ s/\s*,\s*/,/g;
1231					if ($arg =~ m/(.*)\s+([\S+,]+)/) {
1232						$type = $1;
1233						$names = $2;
1234					} else {
1235						$newmember .= "$arg; ";
1236						next;
1237					}
1238					foreach my $name (split /,/, $names) {
1239						$name =~ s/^\s*\**(\S+)\s*/$1/;
1240						next if (($name =~ m/^\s*$/));
1241						if ($id =~ m/^\s*$/) {
1242							# anonymous struct/union
1243							$newmember .= "$type $name; ";
1244						} else {
1245							$newmember .= "$type $id.$name; ";
1246						}
1247					}
1248				}
1249			}
1250		}
1251		$members =~ s/(struct|union)([^\{\};]+)\{([^\{\}]*)\}([^\{\}\;]*)\;/$newmember/;
1252	}
1253
1254	# Ignore other nested elements, like enums
1255	$members =~ s/(\{[^\{\}]*\})//g;
1256
1257	create_parameterlist($members, ';', $file, $declaration_name);
1258	check_sections($file, $declaration_name, $decl_type, $sectcheck, $struct_actual);
1259
1260	# Adjust declaration for better display
1261	$declaration =~ s/([\{;])/$1\n/g;
1262	$declaration =~ s/\}\s+;/};/g;
1263	# Better handle inlined enums
1264	do {} while ($declaration =~ s/(enum\s+\{[^\}]+),([^\n])/$1,\n$2/);
1265
1266	my @def_args = split /\n/, $declaration;
1267	my $level = 1;
1268	$declaration = "";
1269	foreach my $clause (@def_args) {
1270		$clause =~ s/^\s+//;
1271		$clause =~ s/\s+$//;
1272		$clause =~ s/\s+/ /;
1273		next if (!$clause);
1274		$level-- if ($clause =~ m/(\})/ && $level > 1);
1275		if (!($clause =~ m/^\s*#/)) {
1276			$declaration .= "\t" x $level;
1277		}
1278		$declaration .= "\t" . $clause . "\n";
1279		$level++ if ($clause =~ m/(\{)/ && !($clause =~m/\}/));
1280	}
1281	output_declaration($declaration_name,
1282			   'struct',
1283			   {'struct' => $declaration_name,
1284			    'module' => $modulename,
1285			    'definition' => $declaration,
1286			    'parameterlist' => \@parameterlist,
1287			    'parameterdescs' => \%parameterdescs,
1288			    'parametertypes' => \%parametertypes,
1289			    'sectionlist' => \@sectionlist,
1290			    'sections' => \%sections,
1291			    'purpose' => $declaration_purpose,
1292			    'type' => $decl_type
1293			   });
1294    }
1295    else {
1296	print STDERR "${file}:$.: error: Cannot parse struct or union!\n";
1297	++$errors;
1298    }
1299}
1300
1301
1302sub show_warnings($$) {
1303	my $functype = shift;
1304	my $name = shift;
1305
1306	return 0 if (defined($nosymbol_table{$name}));
1307
1308	return 1 if ($output_selection == OUTPUT_ALL);
1309
1310	if ($output_selection == OUTPUT_EXPORTED) {
1311		if (defined($function_table{$name})) {
1312			return 1;
1313		} else {
1314			return 0;
1315		}
1316	}
1317        if ($output_selection == OUTPUT_INTERNAL) {
1318		if (!($functype eq "function" && defined($function_table{$name}))) {
1319			return 1;
1320		} else {
1321			return 0;
1322		}
1323	}
1324	if ($output_selection == OUTPUT_INCLUDE) {
1325		if (defined($function_table{$name})) {
1326			return 1;
1327		} else {
1328			return 0;
1329		}
1330	}
1331	die("Please add the new output type at show_warnings()");
1332}
1333
1334sub dump_enum($$) {
1335    my $x = shift;
1336    my $file = shift;
1337    my $members;
1338
1339
1340    $x =~ s@/\*.*?\*/@@gos;	# strip comments.
1341    # strip #define macros inside enums
1342    $x =~ s@#\s*((define|ifdef)\s+|endif)[^;]*;@@gos;
1343
1344    if ($x =~ /typedef\s+enum\s*\{(.*)\}\s*(\w*)\s*;/) {
1345	$declaration_name = $2;
1346	$members = $1;
1347    } elsif ($x =~ /enum\s+(\w*)\s*\{(.*)\}/) {
1348	$declaration_name = $1;
1349	$members = $2;
1350    }
1351
1352    if ($declaration_name) {
1353	my %_members;
1354
1355	$members =~ s/\s+$//;
1356
1357	foreach my $arg (split ',', $members) {
1358	    $arg =~ s/^\s*(\w+).*/$1/;
1359	    push @parameterlist, $arg;
1360	    if (!$parameterdescs{$arg}) {
1361		$parameterdescs{$arg} = $undescribed;
1362	        if (show_warnings("enum", $declaration_name)) {
1363			print STDERR "${file}:$.: warning: Enum value '$arg' not described in enum '$declaration_name'\n";
1364		}
1365	    }
1366	    $_members{$arg} = 1;
1367	}
1368
1369	while (my ($k, $v) = each %parameterdescs) {
1370	    if (!exists($_members{$k})) {
1371	        if (show_warnings("enum", $declaration_name)) {
1372		     print STDERR "${file}:$.: warning: Excess enum value '$k' description in '$declaration_name'\n";
1373		}
1374	    }
1375        }
1376
1377	output_declaration($declaration_name,
1378			   'enum',
1379			   {'enum' => $declaration_name,
1380			    'module' => $modulename,
1381			    'parameterlist' => \@parameterlist,
1382			    'parameterdescs' => \%parameterdescs,
1383			    'sectionlist' => \@sectionlist,
1384			    'sections' => \%sections,
1385			    'purpose' => $declaration_purpose
1386			   });
1387    } else {
1388	print STDERR "${file}:$.: error: Cannot parse enum!\n";
1389	++$errors;
1390    }
1391}
1392
1393sub dump_typedef($$) {
1394    my $x = shift;
1395    my $file = shift;
1396
1397    $x =~ s@/\*.*?\*/@@gos;	# strip comments.
1398
1399    # Parse function prototypes
1400    if ($x =~ /typedef\s+(\w+)\s*\(\*\s*(\w\S+)\s*\)\s*\((.*)\);/ ||
1401	$x =~ /typedef\s+(\w+)\s*(\w\S+)\s*\s*\((.*)\);/) {
1402
1403	# Function typedefs
1404	$return_type = $1;
1405	$declaration_name = $2;
1406	my $args = $3;
1407
1408	create_parameterlist($args, ',', $file, $declaration_name);
1409
1410	output_declaration($declaration_name,
1411			   'function',
1412			   {'function' => $declaration_name,
1413			    'typedef' => 1,
1414			    'module' => $modulename,
1415			    'functiontype' => $return_type,
1416			    'parameterlist' => \@parameterlist,
1417			    'parameterdescs' => \%parameterdescs,
1418			    'parametertypes' => \%parametertypes,
1419			    'sectionlist' => \@sectionlist,
1420			    'sections' => \%sections,
1421			    'purpose' => $declaration_purpose
1422			   });
1423	return;
1424    }
1425
1426    while (($x =~ /\(*.\)\s*;$/) || ($x =~ /\[*.\]\s*;$/)) {
1427	$x =~ s/\(*.\)\s*;$/;/;
1428	$x =~ s/\[*.\]\s*;$/;/;
1429    }
1430
1431    if ($x =~ /typedef.*\s+(\w+)\s*;/) {
1432	$declaration_name = $1;
1433
1434	output_declaration($declaration_name,
1435			   'typedef',
1436			   {'typedef' => $declaration_name,
1437			    'module' => $modulename,
1438			    'sectionlist' => \@sectionlist,
1439			    'sections' => \%sections,
1440			    'purpose' => $declaration_purpose
1441			   });
1442    }
1443    else {
1444	print STDERR "${file}:$.: error: Cannot parse typedef!\n";
1445	++$errors;
1446    }
1447}
1448
1449sub save_struct_actual($) {
1450    my $actual = shift;
1451
1452    # strip all spaces from the actual param so that it looks like one string item
1453    $actual =~ s/\s*//g;
1454    $struct_actual = $struct_actual . $actual . " ";
1455}
1456
1457sub create_parameterlist($$$$) {
1458    my $args = shift;
1459    my $splitter = shift;
1460    my $file = shift;
1461    my $declaration_name = shift;
1462    my $type;
1463    my $param;
1464
1465    # temporarily replace commas inside function pointer definition
1466    while ($args =~ /(\([^\),]+),/) {
1467	$args =~ s/(\([^\),]+),/$1#/g;
1468    }
1469
1470    foreach my $arg (split($splitter, $args)) {
1471	# strip comments
1472	$arg =~ s/\/\*.*\*\///;
1473	# strip leading/trailing spaces
1474	$arg =~ s/^\s*//;
1475	$arg =~ s/\s*$//;
1476	$arg =~ s/\s+/ /;
1477
1478	if ($arg =~ /^#/) {
1479	    # Treat preprocessor directive as a typeless variable just to fill
1480	    # corresponding data structures "correctly". Catch it later in
1481	    # output_* subs.
1482	    push_parameter($arg, "", $file);
1483	} elsif ($arg =~ m/\(.+\)\s*\(/) {
1484	    # pointer-to-function
1485	    $arg =~ tr/#/,/;
1486	    $arg =~ m/[^\(]+\(\*?\s*([\w\.]*)\s*\)/;
1487	    $param = $1;
1488	    $type = $arg;
1489	    $type =~ s/([^\(]+\(\*?)\s*$param/$1/;
1490	    save_struct_actual($param);
1491	    push_parameter($param, $type, $file, $declaration_name);
1492	} elsif ($arg) {
1493	    $arg =~ s/\s*:\s*/:/g;
1494	    $arg =~ s/\s*\[/\[/g;
1495
1496	    my @args = split('\s*,\s*', $arg);
1497	    if ($args[0] =~ m/\*/) {
1498		$args[0] =~ s/(\*+)\s*/ $1/;
1499	    }
1500
1501	    my @first_arg;
1502	    if ($args[0] =~ /^(.*\s+)(.*?\[.*\].*)$/) {
1503		    shift @args;
1504		    push(@first_arg, split('\s+', $1));
1505		    push(@first_arg, $2);
1506	    } else {
1507		    @first_arg = split('\s+', shift @args);
1508	    }
1509
1510	    unshift(@args, pop @first_arg);
1511	    $type = join " ", @first_arg;
1512
1513	    foreach $param (@args) {
1514		if ($param =~ m/^(\*+)\s*(.*)/) {
1515		    save_struct_actual($2);
1516		    push_parameter($2, "$type $1", $file, $declaration_name);
1517		}
1518		elsif ($param =~ m/(.*?):(\d+)/) {
1519		    if ($type ne "") { # skip unnamed bit-fields
1520			save_struct_actual($1);
1521			push_parameter($1, "$type:$2", $file, $declaration_name)
1522		    }
1523		}
1524		else {
1525		    save_struct_actual($param);
1526		    push_parameter($param, $type, $file, $declaration_name);
1527		}
1528	    }
1529	}
1530    }
1531}
1532
1533sub push_parameter($$$$) {
1534	my $param = shift;
1535	my $type = shift;
1536	my $file = shift;
1537	my $declaration_name = shift;
1538
1539	if (($anon_struct_union == 1) && ($type eq "") &&
1540	    ($param eq "}")) {
1541		return;		# ignore the ending }; from anon. struct/union
1542	}
1543
1544	$anon_struct_union = 0;
1545	$param =~ s/[\[\)].*//;
1546
1547	if ($type eq "" && $param =~ /\.\.\.$/)
1548	{
1549	    if (!$param =~ /\w\.\.\.$/) {
1550	      # handles unnamed variable parameters
1551	      $param = "...";
1552	    }
1553	    elsif ($param =~ /\w\.\.\.$/) {
1554	      # for named variable parameters of the form `x...`, remove the dots
1555	      $param =~ s/\.\.\.$//;
1556	    }
1557	    if (!defined $parameterdescs{$param} || $parameterdescs{$param} eq "") {
1558		$parameterdescs{$param} = "variable arguments";
1559	    }
1560	}
1561	elsif ($type eq "" && ($param eq "" or $param eq "void"))
1562	{
1563	    $param="void";
1564	    $parameterdescs{void} = "no arguments";
1565	}
1566	elsif ($type eq "" && ($param eq "struct" or $param eq "union"))
1567	# handle unnamed (anonymous) union or struct:
1568	{
1569		$type = $param;
1570		$param = "{unnamed_" . $param . "}";
1571		$parameterdescs{$param} = "anonymous\n";
1572		$anon_struct_union = 1;
1573	}
1574
1575	# warn if parameter has no description
1576	# (but ignore ones starting with # as these are not parameters
1577	# but inline preprocessor statements);
1578	# Note: It will also ignore void params and unnamed structs/unions
1579	if (!defined $parameterdescs{$param} && $param !~ /^#/) {
1580		$parameterdescs{$param} = $undescribed;
1581
1582	        if (show_warnings($type, $declaration_name) && $param !~ /\./) {
1583			print STDERR
1584			      "${file}:$.: warning: Function parameter or member '$param' not described in '$declaration_name'\n";
1585			++$warnings;
1586		}
1587	}
1588
1589	# strip spaces from $param so that it is one continuous string
1590	# on @parameterlist;
1591	# this fixes a problem where check_sections() cannot find
1592	# a parameter like "addr[6 + 2]" because it actually appears
1593	# as "addr[6", "+", "2]" on the parameter list;
1594	# but it's better to maintain the param string unchanged for output,
1595	# so just weaken the string compare in check_sections() to ignore
1596	# "[blah" in a parameter string;
1597	###$param =~ s/\s*//g;
1598	push @parameterlist, $param;
1599	$type =~ s/\s\s+/ /g;
1600	$parametertypes{$param} = $type;
1601}
1602
1603sub check_sections($$$$$) {
1604	my ($file, $decl_name, $decl_type, $sectcheck, $prmscheck) = @_;
1605	my @sects = split ' ', $sectcheck;
1606	my @prms = split ' ', $prmscheck;
1607	my $err;
1608	my ($px, $sx);
1609	my $prm_clean;		# strip trailing "[array size]" and/or beginning "*"
1610
1611	foreach $sx (0 .. $#sects) {
1612		$err = 1;
1613		foreach $px (0 .. $#prms) {
1614			$prm_clean = $prms[$px];
1615			$prm_clean =~ s/\[.*\]//;
1616			$prm_clean =~ s/__attribute__\s*\(\([a-z,_\*\s\(\)]*\)\)//i;
1617			# ignore array size in a parameter string;
1618			# however, the original param string may contain
1619			# spaces, e.g.:  addr[6 + 2]
1620			# and this appears in @prms as "addr[6" since the
1621			# parameter list is split at spaces;
1622			# hence just ignore "[..." for the sections check;
1623			$prm_clean =~ s/\[.*//;
1624
1625			##$prm_clean =~ s/^\**//;
1626			if ($prm_clean eq $sects[$sx]) {
1627				$err = 0;
1628				last;
1629			}
1630		}
1631		if ($err) {
1632			if ($decl_type eq "function") {
1633				print STDERR "${file}:$.: warning: " .
1634					"Excess function parameter " .
1635					"'$sects[$sx]' " .
1636					"description in '$decl_name'\n";
1637				++$warnings;
1638			}
1639		}
1640	}
1641}
1642
1643##
1644# Checks the section describing the return value of a function.
1645sub check_return_section {
1646        my $file = shift;
1647        my $declaration_name = shift;
1648        my $return_type = shift;
1649
1650        # Ignore an empty return type (It's a macro)
1651        # Ignore functions with a "void" return type. (But don't ignore "void *")
1652        if (($return_type eq "") || ($return_type =~ /void\s*\w*\s*$/)) {
1653                return;
1654        }
1655
1656        if (!defined($sections{$section_return}) ||
1657            $sections{$section_return} eq "") {
1658                print STDERR "${file}:$.: warning: " .
1659                        "No description found for return value of " .
1660                        "'$declaration_name'\n";
1661                ++$warnings;
1662        }
1663}
1664
1665##
1666# takes a function prototype and the name of the current file being
1667# processed and spits out all the details stored in the global
1668# arrays/hashes.
1669sub dump_function($$) {
1670    my $prototype = shift;
1671    my $file = shift;
1672    my $noret = 0;
1673
1674    print_lineno($.);
1675
1676    $prototype =~ s/^static +//;
1677    $prototype =~ s/^extern +//;
1678    $prototype =~ s/^asmlinkage +//;
1679    $prototype =~ s/^inline +//;
1680    $prototype =~ s/^__inline__ +//;
1681    $prototype =~ s/^__inline +//;
1682    $prototype =~ s/^__always_inline +//;
1683    $prototype =~ s/^noinline +//;
1684    $prototype =~ s/__init +//;
1685    $prototype =~ s/__init_or_module +//;
1686    $prototype =~ s/__meminit +//;
1687    $prototype =~ s/__must_check +//;
1688    $prototype =~ s/__weak +//;
1689    $prototype =~ s/__sched +//;
1690    $prototype =~ s/__printf\s*\(\s*\d*\s*,\s*\d*\s*\) +//;
1691    my $define = $prototype =~ s/^#\s*define\s+//; #ak added
1692    $prototype =~ s/__attribute__\s*\(\(
1693            (?:
1694                 [\w\s]++          # attribute name
1695                 (?:\([^)]*+\))?   # attribute arguments
1696                 \s*+,?            # optional comma at the end
1697            )+
1698          \)\)\s+//x;
1699
1700    # Yes, this truly is vile.  We are looking for:
1701    # 1. Return type (may be nothing if we're looking at a macro)
1702    # 2. Function name
1703    # 3. Function parameters.
1704    #
1705    # All the while we have to watch out for function pointer parameters
1706    # (which IIRC is what the two sections are for), C types (these
1707    # regexps don't even start to express all the possibilities), and
1708    # so on.
1709    #
1710    # If you mess with these regexps, it's a good idea to check that
1711    # the following functions' documentation still comes out right:
1712    # - parport_register_device (function pointer parameters)
1713    # - atomic_set (macro)
1714    # - pci_match_device, __copy_to_user (long return type)
1715
1716    if ($define && $prototype =~ m/^()([a-zA-Z0-9_~:]+)\s+/) {
1717        # This is an object-like macro, it has no return type and no parameter
1718        # list.
1719        # Function-like macros are not allowed to have spaces between
1720        # declaration_name and opening parenthesis (notice the \s+).
1721        $return_type = $1;
1722        $declaration_name = $2;
1723        $noret = 1;
1724    } elsif ($prototype =~ m/^()([a-zA-Z0-9_~:]+)\s*\(([^\(]*)\)/ ||
1725	$prototype =~ m/^(\w+)\s+([a-zA-Z0-9_~:]+)\s*\(([^\(]*)\)/ ||
1726	$prototype =~ m/^(\w+\s*\*+)\s*([a-zA-Z0-9_~:]+)\s*\(([^\(]*)\)/ ||
1727	$prototype =~ m/^(\w+\s+\w+)\s+([a-zA-Z0-9_~:]+)\s*\(([^\(]*)\)/ ||
1728	$prototype =~ m/^(\w+\s+\w+\s*\*+)\s*([a-zA-Z0-9_~:]+)\s*\(([^\(]*)\)/ ||
1729	$prototype =~ m/^(\w+\s+\w+\s+\w+)\s+([a-zA-Z0-9_~:]+)\s*\(([^\(]*)\)/ ||
1730	$prototype =~ m/^(\w+\s+\w+\s+\w+\s*\*+)\s*([a-zA-Z0-9_~:]+)\s*\(([^\(]*)\)/ ||
1731	$prototype =~ m/^()([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
1732	$prototype =~ m/^(\w+)\s+([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
1733	$prototype =~ m/^(\w+\s*\*+)\s*([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
1734	$prototype =~ m/^(\w+\s+\w+)\s+([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
1735	$prototype =~ m/^(\w+\s+\w+\s*\*+)\s*([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
1736	$prototype =~ m/^(\w+\s+\w+\s+\w+)\s+([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
1737	$prototype =~ m/^(\w+\s+\w+\s+\w+\s*\*+)\s*([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
1738	$prototype =~ m/^(\w+\s+\w+\s+\w+\s+\w+)\s+([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
1739	$prototype =~ m/^(\w+\s+\w+\s+\w+\s+\w+\s*\*+)\s*([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
1740	$prototype =~ m/^(\w+\s+\w+\s*\*+\s*\w+\s*\*+\s*)\s*([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/)  {
1741	$return_type = $1;
1742	$declaration_name = $2;
1743	my $args = $3;
1744
1745	create_parameterlist($args, ',', $file, $declaration_name);
1746    } else {
1747	print STDERR "${file}:$.: warning: cannot understand function prototype: '$prototype'\n";
1748	return;
1749    }
1750
1751	my $prms = join " ", @parameterlist;
1752	check_sections($file, $declaration_name, "function", $sectcheck, $prms);
1753
1754        # This check emits a lot of warnings at the moment, because many
1755        # functions don't have a 'Return' doc section. So until the number
1756        # of warnings goes sufficiently down, the check is only performed in
1757        # verbose mode.
1758        # TODO: always perform the check.
1759        if ($verbose && !$noret) {
1760                check_return_section($file, $declaration_name, $return_type);
1761        }
1762
1763    output_declaration($declaration_name,
1764		       'function',
1765		       {'function' => $declaration_name,
1766			'module' => $modulename,
1767			'functiontype' => $return_type,
1768			'parameterlist' => \@parameterlist,
1769			'parameterdescs' => \%parameterdescs,
1770			'parametertypes' => \%parametertypes,
1771			'sectionlist' => \@sectionlist,
1772			'sections' => \%sections,
1773			'purpose' => $declaration_purpose
1774		       });
1775}
1776
1777sub reset_state {
1778    $function = "";
1779    %parameterdescs = ();
1780    %parametertypes = ();
1781    @parameterlist = ();
1782    %sections = ();
1783    @sectionlist = ();
1784    $sectcheck = "";
1785    $struct_actual = "";
1786    $prototype = "";
1787
1788    $state = STATE_NORMAL;
1789    $inline_doc_state = STATE_INLINE_NA;
1790}
1791
1792sub tracepoint_munge($) {
1793	my $file = shift;
1794	my $tracepointname = 0;
1795	my $tracepointargs = 0;
1796
1797	if ($prototype =~ m/TRACE_EVENT\((.*?),/) {
1798		$tracepointname = $1;
1799	}
1800	if ($prototype =~ m/DEFINE_SINGLE_EVENT\((.*?),/) {
1801		$tracepointname = $1;
1802	}
1803	if ($prototype =~ m/DEFINE_EVENT\((.*?),(.*?),/) {
1804		$tracepointname = $2;
1805	}
1806	$tracepointname =~ s/^\s+//; #strip leading whitespace
1807	if ($prototype =~ m/TP_PROTO\((.*?)\)/) {
1808		$tracepointargs = $1;
1809	}
1810	if (($tracepointname eq 0) || ($tracepointargs eq 0)) {
1811		print STDERR "${file}:$.: warning: Unrecognized tracepoint format: \n".
1812			     "$prototype\n";
1813	} else {
1814		$prototype = "static inline void trace_$tracepointname($tracepointargs)";
1815	}
1816}
1817
1818sub syscall_munge() {
1819	my $void = 0;
1820
1821	$prototype =~ s@[\r\n]+@ @gos; # strip newlines/CR's
1822##	if ($prototype =~ m/SYSCALL_DEFINE0\s*\(\s*(a-zA-Z0-9_)*\s*\)/) {
1823	if ($prototype =~ m/SYSCALL_DEFINE0/) {
1824		$void = 1;
1825##		$prototype = "long sys_$1(void)";
1826	}
1827
1828	$prototype =~ s/SYSCALL_DEFINE.*\(/long sys_/; # fix return type & func name
1829	if ($prototype =~ m/long (sys_.*?),/) {
1830		$prototype =~ s/,/\(/;
1831	} elsif ($void) {
1832		$prototype =~ s/\)/\(void\)/;
1833	}
1834
1835	# now delete all of the odd-number commas in $prototype
1836	# so that arg types & arg names don't have a comma between them
1837	my $count = 0;
1838	my $len = length($prototype);
1839	if ($void) {
1840		$len = 0;	# skip the for-loop
1841	}
1842	for (my $ix = 0; $ix < $len; $ix++) {
1843		if (substr($prototype, $ix, 1) eq ',') {
1844			$count++;
1845			if ($count % 2 == 1) {
1846				substr($prototype, $ix, 1) = ' ';
1847			}
1848		}
1849	}
1850}
1851
1852sub process_proto_function($$) {
1853    my $x = shift;
1854    my $file = shift;
1855
1856    $x =~ s@\/\/.*$@@gos; # strip C99-style comments to end of line
1857
1858    if ($x =~ m#\s*/\*\s+MACDOC\s*#io || ($x =~ /^#/ && $x !~ /^#\s*define/)) {
1859	# do nothing
1860    }
1861    elsif ($x =~ /([^\{]*)/) {
1862	$prototype .= $1;
1863    }
1864
1865    if (($x =~ /\{/) || ($x =~ /\#\s*define/) || ($x =~ /;/)) {
1866	$prototype =~ s@/\*.*?\*/@@gos;	# strip comments.
1867	$prototype =~ s@[\r\n]+@ @gos; # strip newlines/cr's.
1868	$prototype =~ s@^\s+@@gos; # strip leading spaces
1869
1870	 # Handle prototypes for function pointers like:
1871	 # int (*pcs_config)(struct foo)
1872	$prototype =~ s@^(\S+\s+)\(\s*\*(\S+)\)@$1$2@gos;
1873
1874	if ($prototype =~ /SYSCALL_DEFINE/) {
1875		syscall_munge();
1876	}
1877	if ($prototype =~ /TRACE_EVENT/ || $prototype =~ /DEFINE_EVENT/ ||
1878	    $prototype =~ /DEFINE_SINGLE_EVENT/)
1879	{
1880		tracepoint_munge($file);
1881	}
1882	dump_function($prototype, $file);
1883	reset_state();
1884    }
1885}
1886
1887sub process_proto_type($$) {
1888    my $x = shift;
1889    my $file = shift;
1890
1891    $x =~ s@[\r\n]+@ @gos; # strip newlines/cr's.
1892    $x =~ s@^\s+@@gos; # strip leading spaces
1893    $x =~ s@\s+$@@gos; # strip trailing spaces
1894    $x =~ s@\/\/.*$@@gos; # strip C99-style comments to end of line
1895
1896    if ($x =~ /^#/) {
1897	# To distinguish preprocessor directive from regular declaration later.
1898	$x .= ";";
1899    }
1900
1901    while (1) {
1902	if ( $x =~ /([^\{\};]*)([\{\};])(.*)/ ) {
1903            if( length $prototype ) {
1904                $prototype .= " "
1905            }
1906	    $prototype .= $1 . $2;
1907	    ($2 eq '{') && $brcount++;
1908	    ($2 eq '}') && $brcount--;
1909	    if (($2 eq ';') && ($brcount == 0)) {
1910		dump_declaration($prototype, $file);
1911		reset_state();
1912		last;
1913	    }
1914	    $x = $3;
1915	} else {
1916	    $prototype .= $x;
1917	    last;
1918	}
1919    }
1920}
1921
1922
1923sub map_filename($) {
1924    my $file;
1925    my ($orig_file) = @_;
1926
1927    if (defined($ENV{'SRCTREE'})) {
1928	$file = "$ENV{'SRCTREE'}" . "/" . $orig_file;
1929    } else {
1930	$file = $orig_file;
1931    }
1932
1933    if (defined($source_map{$file})) {
1934	$file = $source_map{$file};
1935    }
1936
1937    return $file;
1938}
1939
1940sub process_export_file($) {
1941    my ($orig_file) = @_;
1942    my $file = map_filename($orig_file);
1943
1944    if (!open(IN,"<$file")) {
1945	print STDERR "Error: Cannot open file $file\n";
1946	++$errors;
1947	return;
1948    }
1949
1950    while (<IN>) {
1951	if (/$export_symbol/) {
1952	    next if (defined($nosymbol_table{$2}));
1953	    $function_table{$2} = 1;
1954	}
1955    }
1956
1957    close(IN);
1958}
1959
1960#
1961# Parsers for the various processing states.
1962#
1963# STATE_NORMAL: looking for the /** to begin everything.
1964#
1965sub process_normal() {
1966    if (/$doc_start/o) {
1967	$state = STATE_NAME;	# next line is always the function name
1968	$in_doc_sect = 0;
1969	$declaration_start_line = $. + 1;
1970    }
1971}
1972
1973#
1974# STATE_NAME: Looking for the "name - description" line
1975#
1976sub process_name($$) {
1977    my $file = shift;
1978    my $identifier;
1979    my $descr;
1980
1981    if (/$doc_block/o) {
1982	$state = STATE_DOCBLOCK;
1983	$contents = "";
1984	$new_start_line = $. + 1;
1985
1986	if ( $1 eq "" ) {
1987	    $section = $section_intro;
1988	} else {
1989	    $section = $1;
1990	}
1991    }
1992    elsif (/$doc_decl/o) {
1993	$identifier = $1;
1994	if (/\s*([\w\s]+?)(\(\))?\s*-/) {
1995	    $identifier = $1;
1996	}
1997
1998	$state = STATE_BODY;
1999	# if there's no @param blocks need to set up default section
2000	# here
2001	$contents = "";
2002	$section = $section_default;
2003	$new_start_line = $. + 1;
2004	if (/-(.*)/) {
2005	    # strip leading/trailing/multiple spaces
2006	    $descr= $1;
2007	    $descr =~ s/^\s*//;
2008	    $descr =~ s/\s*$//;
2009	    $descr =~ s/\s+/ /g;
2010	    $declaration_purpose = $descr;
2011	    $state = STATE_BODY_MAYBE;
2012	} else {
2013	    $declaration_purpose = "";
2014	}
2015
2016	if (($declaration_purpose eq "") && $verbose) {
2017	    print STDERR "${file}:$.: warning: missing initial short description on line:\n";
2018	    print STDERR $_;
2019	    ++$warnings;
2020	}
2021
2022	if ($identifier =~ m/^struct\b/) {
2023	    $decl_type = 'struct';
2024	} elsif ($identifier =~ m/^union\b/) {
2025	    $decl_type = 'union';
2026	} elsif ($identifier =~ m/^enum\b/) {
2027	    $decl_type = 'enum';
2028	} elsif ($identifier =~ m/^typedef\b/) {
2029	    $decl_type = 'typedef';
2030	} else {
2031	    $decl_type = 'function';
2032	}
2033
2034	if ($verbose) {
2035	    print STDERR "${file}:$.: info: Scanning doc for $identifier\n";
2036	}
2037    } else {
2038	print STDERR "${file}:$.: warning: Cannot understand $_ on line $.",
2039	    " - I thought it was a doc line\n";
2040	++$warnings;
2041	$state = STATE_NORMAL;
2042    }
2043}
2044
2045
2046#
2047# STATE_BODY and STATE_BODY_MAYBE: the bulk of a kerneldoc comment.
2048#
2049sub process_body($$) {
2050    my $file = shift;
2051
2052    # Until all named variable macro parameters are
2053    # documented using the bare name (`x`) rather than with
2054    # dots (`x...`), strip the dots:
2055    if ($section =~ /\w\.\.\.$/) {
2056	$section =~ s/\.\.\.$//;
2057
2058	if ($verbose) {
2059	    print STDERR "${file}:$.: warning: Variable macro arguments should be documented without dots\n";
2060	    ++$warnings;
2061	}
2062    }
2063
2064    if ($state == STATE_BODY_WITH_BLANK_LINE && /^\s*\*\s?\S/) {
2065	dump_section($file, $section, $contents);
2066	$section = $section_default;
2067	$contents = "";
2068    }
2069
2070    if (/$doc_sect/i) { # case insensitive for supported section names
2071	$newsection = $1;
2072	$newcontents = $2;
2073
2074	# map the supported section names to the canonical names
2075	if ($newsection =~ m/^description$/i) {
2076	    $newsection = $section_default;
2077	} elsif ($newsection =~ m/^context$/i) {
2078	    $newsection = $section_context;
2079	} elsif ($newsection =~ m/^returns?$/i) {
2080	    $newsection = $section_return;
2081	} elsif ($newsection =~ m/^\@return$/) {
2082	    # special: @return is a section, not a param description
2083	    $newsection = $section_return;
2084	}
2085
2086	if (($contents ne "") && ($contents ne "\n")) {
2087	    if (!$in_doc_sect && $verbose) {
2088		print STDERR "${file}:$.: warning: contents before sections\n";
2089		++$warnings;
2090	    }
2091	    dump_section($file, $section, $contents);
2092	    $section = $section_default;
2093	}
2094
2095	$in_doc_sect = 1;
2096	$state = STATE_BODY;
2097	$contents = $newcontents;
2098	$new_start_line = $.;
2099	while (substr($contents, 0, 1) eq " ") {
2100	    $contents = substr($contents, 1);
2101	}
2102	if ($contents ne "") {
2103	    $contents .= "\n";
2104	}
2105	$section = $newsection;
2106	$leading_space = undef;
2107    } elsif (/$doc_end/) {
2108	if (($contents ne "") && ($contents ne "\n")) {
2109	    dump_section($file, $section, $contents);
2110	    $section = $section_default;
2111	    $contents = "";
2112	}
2113	# look for doc_com + <text> + doc_end:
2114	if ($_ =~ m'\s*\*\s*[a-zA-Z_0-9:\.]+\*/') {
2115	    print STDERR "${file}:$.: warning: suspicious ending line: $_";
2116	    ++$warnings;
2117	}
2118
2119	$prototype = "";
2120	$state = STATE_PROTO;
2121	$brcount = 0;
2122    } elsif (/$doc_content/) {
2123	if ($1 eq "") {
2124	    if ($section eq $section_context) {
2125		dump_section($file, $section, $contents);
2126		$section = $section_default;
2127		$contents = "";
2128		$new_start_line = $.;
2129		$state = STATE_BODY;
2130	    } else {
2131		if ($section ne $section_default) {
2132		    $state = STATE_BODY_WITH_BLANK_LINE;
2133		} else {
2134		    $state = STATE_BODY;
2135		}
2136		$contents .= "\n";
2137	    }
2138	} elsif ($state == STATE_BODY_MAYBE) {
2139	    # Continued declaration purpose
2140	    chomp($declaration_purpose);
2141	    $declaration_purpose .= " " . $1;
2142	    $declaration_purpose =~ s/\s+/ /g;
2143	} else {
2144	    my $cont = $1;
2145	    if ($section =~ m/^@/ || $section eq $section_context) {
2146		if (!defined $leading_space) {
2147		    if ($cont =~ m/^(\s+)/) {
2148			$leading_space = $1;
2149		    } else {
2150			$leading_space = "";
2151		    }
2152		}
2153		$cont =~ s/^$leading_space//;
2154	    }
2155	    $contents .= $cont . "\n";
2156	}
2157    } else {
2158	# i dont know - bad line?  ignore.
2159	print STDERR "${file}:$.: warning: bad line: $_";
2160	++$warnings;
2161    }
2162}
2163
2164
2165#
2166# STATE_PROTO: reading a function/whatever prototype.
2167#
2168sub process_proto($$) {
2169    my $file = shift;
2170
2171    if (/$doc_inline_oneline/) {
2172	$section = $1;
2173	$contents = $2;
2174	if ($contents ne "") {
2175	    $contents .= "\n";
2176	    dump_section($file, $section, $contents);
2177	    $section = $section_default;
2178	    $contents = "";
2179	}
2180    } elsif (/$doc_inline_start/) {
2181	$state = STATE_INLINE;
2182	$inline_doc_state = STATE_INLINE_NAME;
2183    } elsif ($decl_type eq 'function') {
2184	process_proto_function($_, $file);
2185    } else {
2186	process_proto_type($_, $file);
2187    }
2188}
2189
2190#
2191# STATE_DOCBLOCK: within a DOC: block.
2192#
2193sub process_docblock($$) {
2194    my $file = shift;
2195
2196    if (/$doc_end/) {
2197	dump_doc_section($file, $section, $contents);
2198	$section = $section_default;
2199	$contents = "";
2200	$function = "";
2201	%parameterdescs = ();
2202	%parametertypes = ();
2203	@parameterlist = ();
2204	%sections = ();
2205	@sectionlist = ();
2206	$prototype = "";
2207	$state = STATE_NORMAL;
2208    } elsif (/$doc_content/) {
2209	if ( $1 eq "" )	{
2210	    $contents .= $blankline;
2211	} else {
2212	    $contents .= $1 . "\n";
2213	}
2214    }
2215}
2216
2217#
2218# STATE_INLINE: docbook comments within a prototype.
2219#
2220sub process_inline($$) {
2221    my $file = shift;
2222
2223    # First line (state 1) needs to be a @parameter
2224    if ($inline_doc_state == STATE_INLINE_NAME && /$doc_inline_sect/o) {
2225	$section = $1;
2226	$contents = $2;
2227	$new_start_line = $.;
2228	if ($contents ne "") {
2229	    while (substr($contents, 0, 1) eq " ") {
2230		$contents = substr($contents, 1);
2231	    }
2232	    $contents .= "\n";
2233	}
2234	$inline_doc_state = STATE_INLINE_TEXT;
2235	# Documentation block end */
2236    } elsif (/$doc_inline_end/) {
2237	if (($contents ne "") && ($contents ne "\n")) {
2238	    dump_section($file, $section, $contents);
2239	    $section = $section_default;
2240	    $contents = "";
2241	}
2242	$state = STATE_PROTO;
2243	$inline_doc_state = STATE_INLINE_NA;
2244	# Regular text
2245    } elsif (/$doc_content/) {
2246	if ($inline_doc_state == STATE_INLINE_TEXT) {
2247	    $contents .= $1 . "\n";
2248	    # nuke leading blank lines
2249	    if ($contents =~ /^\s*$/) {
2250		$contents = "";
2251	    }
2252	} elsif ($inline_doc_state == STATE_INLINE_NAME) {
2253	    $inline_doc_state = STATE_INLINE_ERROR;
2254	    print STDERR "${file}:$.: warning: ";
2255	    print STDERR "Incorrect use of kernel-doc format: $_";
2256	    ++$warnings;
2257	}
2258    }
2259}
2260
2261
2262sub process_file($) {
2263    my $file;
2264    my $initial_section_counter = $section_counter;
2265    my ($orig_file) = @_;
2266
2267    $file = map_filename($orig_file);
2268
2269    if (!open(IN_FILE,"<$file")) {
2270	print STDERR "Error: Cannot open file $file\n";
2271	++$errors;
2272	return;
2273    }
2274
2275    $. = 1;
2276
2277    $section_counter = 0;
2278    while (<IN_FILE>) {
2279	while (s/\\\s*$//) {
2280	    $_ .= <IN_FILE>;
2281	}
2282	# Replace tabs by spaces
2283        while ($_ =~ s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e) {};
2284	# Hand this line to the appropriate state handler
2285	if ($state == STATE_NORMAL) {
2286	    process_normal();
2287	} elsif ($state == STATE_NAME) {
2288	    process_name($file, $_);
2289	} elsif ($state == STATE_BODY || $state == STATE_BODY_MAYBE ||
2290		 $state == STATE_BODY_WITH_BLANK_LINE) {
2291	    process_body($file, $_);
2292	} elsif ($state == STATE_INLINE) { # scanning for inline parameters
2293	    process_inline($file, $_);
2294	} elsif ($state == STATE_PROTO) {
2295	    process_proto($file, $_);
2296	} elsif ($state == STATE_DOCBLOCK) {
2297	    process_docblock($file, $_);
2298	}
2299    }
2300
2301    # Make sure we got something interesting.
2302    if ($initial_section_counter == $section_counter && $
2303	output_mode ne "none") {
2304	if ($output_selection == OUTPUT_INCLUDE) {
2305	    print STDERR "${file}:1: warning: '$_' not found\n"
2306		for keys %function_table;
2307	}
2308	else {
2309	    print STDERR "${file}:1: warning: no structured comments found\n";
2310	}
2311    }
2312    close IN_FILE;
2313}
2314
2315
2316$sphinx_major = get_sphinx_version();
2317$kernelversion = get_kernel_version();
2318
2319# generate a sequence of code that will splice in highlighting information
2320# using the s// operator.
2321for (my $k = 0; $k < @highlights; $k++) {
2322    my $pattern = $highlights[$k][0];
2323    my $result = $highlights[$k][1];
2324#   print STDERR "scanning pattern:$pattern, highlight:($result)\n";
2325    $dohighlight .=  "\$contents =~ s:$pattern:$result:gs;\n";
2326}
2327
2328# Read the file that maps relative names to absolute names for
2329# separate source and object directories and for shadow trees.
2330if (open(SOURCE_MAP, "<.tmp_filelist.txt")) {
2331	my ($relname, $absname);
2332	while(<SOURCE_MAP>) {
2333		chop();
2334		($relname, $absname) = (split())[0..1];
2335		$relname =~ s:^/+::;
2336		$source_map{$relname} = $absname;
2337	}
2338	close(SOURCE_MAP);
2339}
2340
2341if ($output_selection == OUTPUT_EXPORTED ||
2342    $output_selection == OUTPUT_INTERNAL) {
2343
2344    push(@export_file_list, @ARGV);
2345
2346    foreach (@export_file_list) {
2347	chomp;
2348	process_export_file($_);
2349    }
2350}
2351
2352foreach (@ARGV) {
2353    chomp;
2354    process_file($_);
2355}
2356if ($verbose && $errors) {
2357  print STDERR "$errors errors\n";
2358}
2359if ($verbose && $warnings) {
2360  print STDERR "$warnings warnings\n";
2361}
2362
2363if ($Werror && $warnings) {
2364    print STDERR "$warnings warnings as Errors\n";
2365    exit($warnings);
2366} else {
2367    exit($output_mode eq "none" ? 0 : $errors)
2368}
2369