#!/usr/bin/perl -w

#==============================================================================
#
#  apigen: code generator for VxWorks API modules
#
#  1.00  mjs  11/11/1999  Initial version
#  1.01  mjs  15/11/1999  Bug fix to .c generation; also prevent unused
#                          variable warnings
#  1.02  mjs  17/11/1999  Add -p <path> option; remove #include of atypes.h;
#                          add 'nolibinit' key
#  1.03  mjs  19/11/1999  Fix bug with pointer arguments
#  1.04  mjs  19/11/1999  Add autogeneration of hyperlinks in HTML output; fix
#                          problem with void functions with arguments
#  1.05  mjs  22/11/1999  Improve message name generation and error reporting;
#                          fix bug with pointer type functions
#  1.06  mjs  15/03/2000  Add 'process' keyword
#
#==============================================================================

use Getopt::Long;
use File::Basename;
use File::Path;

my $version = "1.06";
my $prog = basename $0;

my $syntax = <<EOF;
$prog version $version
usage: $prog [-p <path>] <spec>
    -p path - specify directory to write output files to
    -v      - be verbose, be very verbose.
EOF

my ( $spec, $path, $verbose );
GetOptions( "p=s" => \$path,
            "v"   => \$verbose ) or die $syntax;

($spec) = @ARGV or die $syntax;

if ($spec =~ /^\-/)
{
  die $syntax;
}

#------------------------------------------------------------------------------
# Parse spec file
#------------------------------------------------------------------------------

open (SPEC, "<$spec") or die "$prog: Couldn't open '$spec': $!\n";
$line = 0;
$doc = '.none';
while (<SPEC>)
{
  $line++;
  chomp;
  s/\#.*$//; # remove comments
  s/^\s*//;  # remove leading spaces
  s/\s*$//;  # remove trailing spaces
  if    (/^api\s+(\S+)$/i)                 { $api = $1; $doc = '.header'; }
  elsif (/^process\s+(\S+)$/i)             { $processname = $1; }
  elsif (/^moduleoutput\s+(\S+)$/i)        { $moduleoutput = $1; }
  elsif (/^headeroutput\s+(\S+)$/i)        { $headeroutput = $1; }
  elsif (/^codeoutput\s+(\S+)$/i)          { $codeoutput = $1; }
  elsif (/^htmloutput\s+(\S+)$/i)          { $htmloutput = $1; }
  elsif (/^nolibinit$/i)                   { $nolibinit = $1; }
  elsif (/^messageprefix\s+(\S+)$/i)       { $messageprefix = $1; }
  elsif (/^messageid\s+(\S+)$/i)           { $messageid = $1; }
  elsif (/^function\s+(.*)$/i)             { push @functions, $1; $doc = $1; }
  elsif (/^\-\s+(.*)$/ && $doc ne '.none') { $shortdesc{$doc} = "- $1"; }
  elsif (/^\?\s+(\S+)\s+(.*)$/ && $doc !~ /^\./)
                                           { $argdesc{$doc,$1} = " /* $2 */"; }
  elsif (/^\:\s+(.*)$/ && $doc ne '.none') { $longdesc{$doc} .= "$1\n"; }
  elsif (/^\>\s+(.*)$/ && $doc ne '.none') { $returns{$doc} .= "$1\n"; }
  elsif (/^\+\s+(.*)$/ && $doc ne '.none') { $seealso{$doc} = "$1"; }
  elsif (/^\s*$/)                          { $doc = '.none'; }
  else { die "$prog: Error in $spec at line $line: '$_'\n"; }
}
close SPEC;

#------------------------------------------------------------------------------
#  Check spec and set defaults
#------------------------------------------------------------------------------

die "$prog: $spec: No 'api' line\n" unless defined $api;
$api_uc = $api;
$api_uc =~ y/a-z/A-Z/;
$processname = $api unless defined $processname;
$messageprefix = $api_uc . "LIB_" unless defined $messageprefix;
$moduleoutput = $api . "Lib.module" unless defined $moduleoutput;
$headeroutput = $api . "Lib.h" unless defined $headeroutput;
$codeoutput = $api . "Lib.c" unless defined $codeoutput;
$htmloutput = $api . "Lib.html" unless defined $htmloutput;
$codeoutput_basename = $codeoutput;
$codeoutput_basename =~ s/\.([^.]*)$//;

print "\n";
print "Generating API for    : $api\n";
print "Module output file    : $moduleoutput\n";
print "Header output file    : $headeroutput\n";
print "C code output file    : $codeoutput\n";
print "HTML output file      : $htmloutput\n";
print "Message prefix        : $messageprefix\n";
print "Generate LibInit code : ", ($nolibinit) ? "no" : "yes", "\n";
print "\n";

if ($nolibinit and ($codeoutput ne '-'))
{
  print STDERR "Warning: generating C code without LibInit function!\n\n";
}

#------------------------------------------------------------------------------
#  Define header and footer for .module file
#------------------------------------------------------------------------------

$module_header = <<"EOH"
% ############################################################################
% (c) Copyright Virata Limited 1999
%
% Virata Limited Confidential and Proprietary
%
% The following software source code ("Software") is strictly confidential and
% is proprietary to Virata Limited ("Virata").  It may only be read, used,
% copied, adapted, modified or otherwise dealt with by you if you have
% entered into a confidentiality agreement with Virata and then subject to the
% terms of that confidentiality agreement and any other applicable agreement
% between you and Virata.  If you are in any doubt as to whether you are
% entitled to access, read, use, copy, adapt, modify or otherwise deal with
% the Software or whether you are entitled to disclose the Software to any
% other person you should contact Virata.  If you have not entered into a
% confidentiality agreement with Virata granting access to this Software you
% should forthwith return all media, copies and printed listings containing
% the Software to Virata.
%
% Virata reserves the right to take legal action against you should you breach
% the above provisions.
%
% If you are unsure, or to report violations, please contact
% support\@virata.com
% ############################################################################

%
%  Module file for $api API library
%

Export Header $headeroutput

Make.cc $codeoutput_basename
Export SLibrary $codeoutput_basename.o

EOH
  ;

$module_footer = "";

#------------------------------------------------------------------------------
#  Define header and footer for .h file
#------------------------------------------------------------------------------

$header_header = <<"EOH"
/* ###########################################################################
# (c) Copyright Virata Limited 1999
#
# Virata Limited Confidential and Proprietary
#
# The following software source code ("Software") is strictly confidential and
# is proprietary to Virata Limited ("Virata").  It may only be read, used,
# copied, adapted, modified or otherwise dealt with by you if you have
# entered into a confidentiality agreement with Virata and then subject to the
# terms of that confidentiality agreement and any other applicable agreement
# between you and Virata.  If you are in any doubt as to whether you are
# entitled to access, read, use, copy, adapt, modify or otherwise deal with
# the Software or whether you are entitled to disclose the Software to any
# other person you should contact Virata.  If you have not entered into a
# confidentiality agreement with Virata granting access to this Software you
# should forthwith return all media, copies and printed listings containing
# the Software to Virata.
#
# Virata reserves the right to take legal action against you should you breach
# the above provisions.
#
# If you are unsure, or to report violations, please contact
# support\@virata.com
# ##########################################################################*/

/*
 *  $api API
 *
 */

#ifndef ${messageprefix}H
#define ${messageprefix}H

#ifdef __cplusplus
extern \"C\" {
#endif

EOH
  ;

$header_footer = <<"EOH"

#ifdef __cplusplus
}
#endif

#endif

EOH
  ;

#------------------------------------------------------------------------------
#  Define header for .c file
#------------------------------------------------------------------------------

$code_header = <<"EOH"
/* ###########################################################################
# (c) Copyright Virata Limited 1999
#
# Virata Limited Confidential and Proprietary
#
# The following software source code ("Software") is strictly confidential and
# is proprietary to Virata Limited ("Virata").  It may only be read, used,
# copied, adapted, modified or otherwise dealt with by you if you have
# entered into a confidentiality agreement with Virata and then subject to the
# terms of that confidentiality agreement and any other applicable agreement
# between you and Virata.  If you are in any doubt as to whether you are
# entitled to access, read, use, copy, adapt, modify or otherwise deal with
# the Software or whether you are entitled to disclose the Software to any
# other person you should contact Virata.  If you have not entered into a
# confidentiality agreement with Virata granting access to this Software you
# should forthwith return all media, copies and printed listings containing
# the Software to Virata.
#
# Virata reserves the right to take legal action against you should you breach
# the above provisions.
#
# If you are unsure, or to report violations, please contact
# support\@virata.com
# ##########################################################################*/

/*
 *  $api API -> message interface library
 *
 */

#include \"config.h\"
#include \"$headeroutput\"
#include \"atypes.h\"
#include \"kernel.h\"
#include \"kernel_if.h\"
#include \"messages.h\"

EOH
  ;

$code_footer = "";

#------------------------------------------------------------------------------
#  Define header for .html file
#------------------------------------------------------------------------------

$html_header = <<"EOH"
<HTML>
<HEAD>
<TITLE>${api}Lib documentation</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF">
<TABLE WIDTH="100%" CELLSPACING="16">
EOH
  ;

$html_footer = <<"EOH"
</TABLE>
</BODY>
</HTML>
EOH
  ;

#------------------------------------------------------------------------------
#  Add the headers
#------------------------------------------------------------------------------

$module_out = $module_header;
$header_out = $header_header;
$code_out = $code_header;
$html_out = $html_header;

if (defined $messageid)
{
  $module_out .= "MessageId $messageid\n\n";
}

$html_out .= &html_library_heading("${api}Lib");
$html_out .= &html_library_name("${api}Lib", $shortdesc{'.header'});
$html_out .= &html_library_desc($longdesc{'.header'});

#------------------------------------------------------------------------------
#  Add LibInit function, unless suppression was requested
#------------------------------------------------------------------------------

unless ($nolibinit)
{
  $header_out .= "extern int ${api}LibInit(void);\n\n";

  $code_out .= <<"EOI"
static ATMOS_MQID ${processname}_qid = 0;

int ${api}LibInit(void)
{
    if (${processname}_qid == 0)
    {
        ${processname}_qid = atmos_findqueue(\"$processname\");
        if (${processname}_qid == 0)
        {
            return -1;
        }
    }

    return 0;
}

EOI
    ;
}

#------------------------------------------------------------------------------
#  Sort the functions into alphabetical order
#------------------------------------------------------------------------------

@sorted_functions = sort {
  my ($aa, $bb) = ($a, $b);
  $aa =~ s/\s*\(.*$//;
  $bb =~ s/\s*\(.*$//;
  $aa =~ s/^(.*)\s+(\S+)$/$2/;
  $bb =~ s/^(.*)\s+(\S+)$/$2/;
  $aa =~ s/^\*+//;
  $bb =~ s/^\*+//;
  $aa cmp $bb;
} @functions;

#------------------------------------------------------------------------------
#  Do the hard work
#------------------------------------------------------------------------------

$html_out_fn_index = "";
$html_out_fns = "";

for $function (@sorted_functions)
{
  if ($function =~ /^(.+)\s+(\S+)\s*\((.*)\)\;?$/)
  {
    ($type, $fn, $args) = ($1, $2, $3);
    if ($fn =~ /^(\*+)(.+)$/)
    {
      $type .= " " . $1;
      $fn = $2;
    }
    @argtypes = ();
    @argnames = ();
    @arginfo = ();

    $html_out_fn_index .= &html_function_for_index($fn, $shortdesc{$function});

    $html_out_fns .= &html_function_heading($fn);
    $html_out_fns .= &html_function_name($fn, $shortdesc{$function});
    $synopsis = "$type $fn";
    
    if ($args =~ /^\s*(void)?\s*$/)
    {
      $synopsis .= " (void)";
    }
    else
    {
      # Get type and name of each argument:

      $maxt = 0;
      $maxn = 0;
      for $arg (split(/\s*\,\s*/, $args))
      {
        if ($arg =~ /^\s*(\S.*\S)\s+(\S+)\s*$/)
        {
          ($argtype, $argname) = ($1, $2);
	  if ($argname =~ /^(\*+)(.+)$/)
          {
	    $argtype .= " " . $1;
	    $argname = $2;
	  }
	  if ($argdesc{$function,$argname})
          {
	    push @arginfo;
	  }
	  else
          {
	    push @arginfo, "";
	  }
	  push @argtypes, $argtype;
	  push @argnames, $argname;
	  if (length($argtype) > $maxt) { $maxt = length($argtype); }
	  if (length($argname) > $maxn) { $maxn = length($argname); }
	}
	else
        {
          die "$prog: Error in $spec: bad argument syntax: '$arg' in '$function'\n";
	}
      }

      # Generate tidy HTML:

      $maxn++;
      $format = "    %-${maxt}.${maxt}s %-${maxn}.${maxn}s%s\n";
      $synopsis .= "\n    (\n";
      $i = 0;
      for $an (@argnames)
      {
	$comma = ($i == $#argnames) ? "" : ",";
        my $argdesc = $argdesc{$function,$an};
        $argdesc = "" unless defined $argdesc;
        $synopsis .= sprintf $format, $argtypes[$i++], $an . $comma, $argdesc;
      }
      $synopsis .= "    )";
    }

    $html_out_fns .= &html_function_synopsis($synopsis);
    
    # Code and message generation is skipped for <api>LibInit!
    
    if ($function !~ /${api}LibInit/)
    {
      # Add headers for function:
    
      $header_out .= "extern $type $fn($args);\n\n";
      $code_out .= "$type $fn($args)\n{\n";
    
      # Work out a sensible message name:
    
      $msgname = $fn;
      $msgname =~ s/^${api}_?(LIB)?_?//i;
      $msgname =~ y/a-z/A-Z/;
      $msgname = $messageprefix . $msgname;
  
      # Add prologue for message and C code:
  
      $module_out .= "Message $msgname\n{\n";
      $code_out .= "    ATMOS_MESSAGE m;\n";
      if ($type eq 'void' and $#argtypes < 0)
      {
          $code_out .= "\n";
      }
      else
      {
          $code_out .= "    MSG_D_$msgname(msg, &m);\n\n";
      }

      # Add message fields and corresponding code for input arguments:
  
      for $at (@argtypes)
      {
          $an = shift @argnames;
          $ai = shift @arginfo;
          $ai = "" unless defined $ai;
          $code_out .= "    msg->$an = $an;\n";
          $module_out .= "    $at $an;$ai\n";
      }

      # Add message sending code:
  
      $code_out .= "    sendwaitmessage(&m, MSG_N_$msgname, ${processname}_qid);\n";

      # Add code (and special "result" message field if needed) for output
      #  arguments:
  
      $code_out .= "    ATMOS_SETERR(m.errno);\n";
      if ($type eq 'void')
      {
        $code_out .= "    return;\n";
      }
      else
      {
        $code_out .= "    return msg->result;\n";
        $module_out .= "    $type result;\n";
      }

      # Say what we've done:
  
      $desc = "$type $fn($args)";
      if (length($desc) <= 40)
      {
        printf "%-40.40s -> %s\n", $desc, $msgname;
      }
      else
      {
        printf "$desc\n%-40.40s -> %s\n", "", $msgname;
      }

      # Add epilogue for message and C code:
  
      $module_out .= "}\n\n";
      $code_out .= "}\n\n";

    }
  
    # Add long description for HTML:

    if ($longdesc{$function})
    {
      $html_out_fns .= &html_function_desc($longdesc{$function});
    }

    if ($returns{$function})
    {
      $html_out_fns .= &html_function_returns($returns{$function});
    }

    if ($seealso{$function})
    {
      $html_out_fns .= &html_function_see_also($seealso{$function});
    }
  }
  else
  {
    die "$prog: Error in $spec: bad function syntax '$function'\n";
  }
}

#------------------------------------------------------------------------------
#  Add documentation for individual functions
#------------------------------------------------------------------------------

$html_out .= &html_function_index($html_out_fn_index);
$html_out .= $html_out_fns;
$html_out = &html_hyperlinkify($html_out);

#------------------------------------------------------------------------------
#  Add trailing stuff
#------------------------------------------------------------------------------

$module_out .= $module_footer;
$header_out .= $header_footer;
$code_out .= $code_footer;
$html_out .= $html_footer;

#------------------------------------------------------------------------------
#  Write the output
#------------------------------------------------------------------------------

if ($path)
{
    mkpath $path;
    chdir $path or die "$prog: Couldn't change directory to '$path': $!\n";
}

if ($moduleoutput ne '-')
{
  open (MODOUT, ">$moduleoutput")
    or die "$prog: Couldn't open '$moduleoutput': $!\n";
  print MODOUT $module_out;
  close MODOUT;
}

if ($headeroutput ne '-')
{
  open (HEADOUT, ">$headeroutput")
    or die "$prog: Couldn't open '$headeroutput': $!\n";
  print HEADOUT $header_out;
  close HEADOUT;
}

if ($codeoutput ne '-')
{
  open (CODEOUT, ">$codeoutput")
    or die "$prog: Couldn't open '$codeoutput': $!\n";
  print CODEOUT $code_out;
  close CODEOUT;
}

if ($htmloutput ne '-')
{
  open (HTMLOUT, ">$htmloutput")
    or die "$prog: Couldn't open '$htmloutput': $!\n";
  print HTMLOUT $html_out;
  close HTMLOUT;
}

print "\n";

#------------------------------------------------------------------------------
#  Done
#------------------------------------------------------------------------------

exit;

  
###############################################################################

#------------------------------------------------------------------------------
#  HTML output elements
#------------------------------------------------------------------------------

sub html_hyperlinkify
{
  # Turn any function names we know about into hyperlinks
  my ($in) = @_;
  my $fn;
  for $fn (@html_function_list)
  {
    $in =~ s/(<[^>]+>)*$fn\(\)(<[^>]+>)*/&html_function_hyperlink($fn)/eg;
  }
  $in =~ s/\377//g;
  return $in;
}

sub html_function_hyperlink
{
  # Function name -> individual hyperlink
  my ($name) = @_;
  return "<B><I><A HREF=\"#$name\">$name\(\)</A></I></B>";
}
      
sub html_table_row
{
  # Two columns -> table row
  my ($col1, $col2) = @_;
  if ($col1 eq "") { $col1 = '&nbsp;'; } else { $col1 = "<B>$col1</B>"; }
  return "<TR ALIGN=\"LEFT\" VALIGN=\"TOP\">\n<TD>\n" . $col1 . "\n</TD>\n"
    . "<TD>\n" . $col2 . "\n</TD>\n</TR>\n";
}

sub html_library_heading
{
  # Library name -> heading
  my ($lib) = @_;
  return &html_table_row("", "<H1>$lib</H1>");
}

sub html_library_name
{
  # Library name and short description -> library NAME row
  my ($lib, $desc) = @_;
  chomp $desc;
  return &html_table_row("NAME", "<B>$lib</B> $desc");
}

sub html_library_desc
{
  # Library long description -> library DESCRIPTION row
  my ($desc) = @_;
  chomp $desc;
  return &html_table_row("DESCRIPTION", $desc);
}

sub html_function_for_index
{
  # Function name and short description -> function index entry
  my ($fn, $desc) = @_;
  push @html_function_list, $fn;
  return "$fn() $desc<BR>\n";
}

sub html_function_index
{
  # Fully built function index -> library ROUTINES row
  my ($index) = @_;
  chomp $index;
  return &html_table_row("ROUTINES", $index);
}

sub html_function_heading
{
  # Function name -> function heading
  my ($fn) = @_;
  return &html_table_row("", "<HR NOSHADE SIZE=\"1\">\n<A NAME=\"$fn\"><H2><I>$fn\377()</I></H2></A>");
}

sub html_function_name
{
  # Function name and short description -> function NAME row
  my ($fn, $desc) = @_;
  chomp $desc;
  return &html_table_row("NAME", "<B><I>$fn\377()</I></B> $desc");
}

sub html_function_synopsis
{
  # Generated function synopsis -> function SYNOPSIS row
  my ($syn) = @_;
  chomp $syn;
  return &html_table_row("SYNOPSIS", "<PRE><B>$syn</B></PRE>");
}

sub html_function_desc
{
  # Function long description -> function DESCRIPTION row
  my ($desc) = @_;
  chomp $desc;
  return &html_table_row("DESCRIPTION", $desc);
}

sub html_function_returns
{
  # Function returns description -> function RETURNS row
  my ($desc) = @_;
  chomp $desc;
  return &html_table_row("RETURNS", $desc);
}

sub html_function_see_also
{
  # Function see also description -> function SEE ALSO row
  my ($desc) = @_;
  chomp $desc;
  return &html_table_row("SEE ALSO", $desc);
}

