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