#!/usr/bin/perl -w

#
# Little quick and dirty script used to extract functions/keywords/properties
# from CMake help (cmake --help-command-list and many cmake --help-command)
#
# Since I maintain a language higlighting definition for the NEdit text editor
# I was bored by checking the keywords each time a new version is comming, so
# as usual, a script became welcome :)
#
# This is quite approximative but at now it works...
#
# The output produced is for my definition of CMake for nedit but anything
# else can be printed from the data structures.
#

use strict;


use Carp;

my %commands;	# Keys			Values
		# Command names		hash
		#				subkey		sub value
		#			 	KEYWORDS	List of keywords used
		#				DEPRECATED	True/False: function is deprecated
		#				HELP		Text of --help-command

my %keywords;	# Keys			Values
		# Keyword names		hash
		#				subkey		sub value
		#			 	OWNER		List of functions/commands using the keyword

my %properties;	# Keys			Values
		# Property names	List of commands using it

# Function/Commands to ignore every time
my %excluded_command		= ( map { $_ => 1 } qw(
	PROJECT
	) );

# Function/Commands to ignore when getting property names
# because there is words which can be interpreted as property names and are not
my %excluded_from_properties	= ( map { $_ => 1 } qw(
	INSTALL
	SET
	) );

# List of words to ignore in all cases (command defs and properties).
my %word_to_skip		= ( map { $_ => 1 } qw(
	DOCSTRING
	ENV
	TYPE
	VALUE
	VALUE1
	VALUEN
	VAR
	) );


#
# Function used to get a command definition and analyse its signature(s)
#
sub check_command
{
  my $command	= shift;

  return if $command =~ m/cmake\s+version\s+/i; # garbage produced by cmake

  croak "Program error: spaces in '$command', incredible!!!" if index($command, ' ') != -1;

  # Ignore unwanted functions
  return if $excluded_command{$command};

  my $command_help	= qx/ cmake --help-command $command /;
  croak "Error launching command 'cmake --help-command $command': $?" if $?;
  
  $command_help		=~ s/\n+/ . /g; # Force word separation
  $command_help		=~ s/\s+/ /g;	# Only one space at a time

  my @Signatures	= $command_help =~ m/$command(\(.*?\))/g;
  my %Unique;

  foreach my $Signature (@Signatures)
  {
    next if $Signature =~ m/^\([A-Z_\s]*(?:\.\.\.)?\)$/;	# Yes, only words are no word at all...

    my @words;
    while ($Signature =~ m/(?<!\w)
			   ([-]?[A-Z][A-Z_ ]+)
			   (?!\w)
			   [\s\W]/gx)
    {
      my $word	= $1;
      next if substr($word, 0, 1) eq '-';	# because of -D in ADD_DEFINITION
      $word	=~ s/\s+$//;			# Remove trailing blanks
      push @words, $word;
    }
    WORD_TO_CHECK:
    while (@words)
    {
      my $word	= shift @words;
      # List of blank separated word contain unwanted word ?
      if (index($word, ' ') != -1)
      {
	foreach my $word_in_list (split m/\s+/, $word)
	{
	  if ($word_to_skip{$word_in_list})
	  {
	    # Yes, so treat each word separately.
	    push @words, split(m/\s+/, $word);
	    next WORD_TO_CHECK;
	  }
	}
      }
      next WORD_TO_CHECK if $word_to_skip{$word};
        
      push @{ $keywords{$word}{OWNER} }, $command;
      $Unique{$word}	= 1;
    }
  }
  $commands{$command}{KEYWORDS}		= [ sort keys %Unique ];
  $commands{$command}{DEPRECATED}	= $command_help =~ m/Deprecated|Obsolete/m;
  $commands{$command}{HELP}		= $command_help;
}



#
# As all commands and keywords are now known this function parse the command definition
# (but not the command signatures) to guess property names.
#
sub check_properties
{
  my $command	= shift;

  return if $excluded_from_properties{$command};

  # Configuration modes (not all possible since there can be user defined ones)
  my @config_names	= (qw(DEBUG RELEASE MINSIZEREL RELWITHDEBINFO) );

  # List of exactly known words
  my %known	= map ( { $_ => 1 }
			    keys(%commands),
			    keys(%keywords),
			    @config_names,
			    keys(%word_to_skip),
			    # empiric
			    qw(
				IDE
				QT
				OSX
				NOTFOUND
				ERROR
				DLL
				RPATH
				VS
				),
		);

  # List of words known by format
  my $known_by_RE	= '(?:'.
				join(')|(?:', qw(
					CMAKE_.*
						)
				    ) .
			  ')';

  my $command_help	= $commands{$command}{HELP};

  # Empiric:
  # The command define property names if there is the word "property" in the
  # help of the command
  return if $command_help !~ m/propert(?:y|ies)/;

  my %Unique;
  # Suppress signatures
  $command_help	= join(" ",
			split m/$command\(.*?\)/, $command_help);


  foreach my $word ($command_help =~ m/(?<!\w)
				    (
					(?: [A-Z] | \<CONFIG\> )
					(?: [A-Z_]| \<CONFIG\> )+
				    )
				    (?!\w)
				  /gx
		  )
  {
    # Property name is not an already known word (empiric)
    next if $known{$word};
    next if $word =~ m/^$known_by_RE$/m;

    # Property names may contain the <CONFIG> wildcard so there
    # si as many property as config possibilities (contained in
    # @config)
    if (index($word, '<CONFIG>') != -1)
    {
      foreach ( @config_names )
      {
        my $Variant	= $word;
	$Variant =~ s/\<CONFIG\>/$_/g;

        push @{ $properties{$Variant} }, $command;
      }
    }
    else
    {
      push @{ $properties{$word} }, $command;
    }
  }
}










# Preset keywords ON/OFF which are boolean values for OPTION but
# are not in any signature.
%keywords	= (
	ON	=> { OWNER => [] },
	OFF	=> { OWNER => [] },
		);

my @cmake_command_list	= qx/ cmake --help-command-list /;
croak "Error launching command 'cmake --help-command-list': $?" if $?;

chomp @cmake_command_list;
foreach my $command (@cmake_command_list)
{
  check_command $command;
}

foreach my $command (keys %commands)
{
  check_properties $command;
}

#
# Output for nedit RE patterns used to recognise commands/functions
# Keywords (in functions) and properties.
#
print "Nedit definitions:\n\n";
print "known functions:\n";
print "(<(?:",join("|", sort keys %commands),")>)\\s*\\(\n";

print "\nkeywords\n";
print "(?:<(?:",join("|", sort(keys %keywords),"debug","optimized"), ")>)|\@ONLY\n";

print "\nproperties\n";
print "<(?:",join("|", sort keys %properties), ")>\n";

# And one special for PROJECT command which is treated separately
# in order to have this function highlighted in another way.
# If you dont want to treat PROJECT differently, just remove it
# from 

print "\nProjectDecl\n";
print 'PROJECT\s*\((\w+)((?:\s+(?iC|C\+\+|Java|None))*)\s*\)',"\n";

#print "$_: ", join(", ", @{$keywords{$_}{OWNER}}),"\n" foreach sort(keys %keywords);

