#!/usr/bin/perl -w

eval 'exec /usr/bin/perl -w -S $0 ${1+"$@"}'
    if 0; # not running under some shell
###############################################################################
# Sanity check plugin for the Krazy project.                                  #
# Copyright (C) 2007-2008 by Allen Winter <winter@kde.org>                    #
#                                                                             #
# This program is free software; you can redistribute it and/or modify        #
# it under the terms of the GNU General Public License as published by        #
# the Free Software Foundation; either version 2 of the License, or           #
# (at your option) any later version.                                         #
#                                                                             #
# This program is distributed in the hope that it will be useful,             #
# but WITHOUT ANY WARRANTY; without even the implied warranty of              #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the                #
# GNU General Public License for more details.                                #
#                                                                             #
# You should have received a copy of the GNU General Public License along     #
# with this program; if not, write to the Free Software Foundation, Inc.,     #
# 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.               #
#                                                                             #
###############################################################################

# Tests KDE source for incorrect use of cpp macros

# Program options:
#   --help:          print one-line help message and exit
#   --version:       print one-line version information and exit
#   --priority:      report issues of the specified priority only
#   --strict:        report issues with the specified strictness level only
#   --explain:       print an explanation with solving instructions
#   --installed      file is to be installed
#   --quiet:         suppress all output messages
#   --verbose:       print the offending content

# Exits with status=0 if test condition is not present in the source;
# else exits with the number of failures encountered.

use strict;
use FindBin qw($Bin);
use lib "$Bin/../../../../lib";
use Krazy::PreProcess;
use Krazy::Utils;

my($Prog) = "cpp";
my($Version) = "1.4";

&parseArgs();

&Help() if &helpArg();
&Version() if &versionArg();
&Explain() if &explainArg();
if ($#ARGV != 0){ &Help(); exit 0; }

my($f) = $ARGV[0];

#open file and slurp it in
if (&installedArg()) {
  print "okay\n" if (!&quietArg());
  exit 0;
} else {
  open(F, "$f") || die "Couldn't open $f";
}
my(@data_lines) = <F>;
close(F);

# Remove C-style comments and #if 0 blocks from the file input
my(@lines) = RemoveIfZeroBlockC( RemoveCommentsC( @data_lines ) );

my($cnt) = 0;
my($wcnt) = 0;
my($linecnt) = 0;
my($line);
my($lstr) = "";
my($wstr) = "";
foreach $line (@lines) {
  if ($line =~ m+//.*[Kk]razy:excludeall=.*$Prog+ ||
      $line =~ m+//.*[Kk]razy:skip+) {
    $cnt = 0;
    last;
  }

  $linecnt++;
  next if ($line =~ m+//.*[Kk]razy:exclude=.*$Prog+);
  $line =~ s+//.*++;  #skip C++ comments

  if ($line =~ m/^[[:space:]]*#[[:space:]]*if[[:space:]][_[:alnum:]]/ ||
      $line =~ m/^[[:space:]]*#[[:space:]]*ifdef[[:space:]][_[:alnum:]]/ ||
      $line =~ m/^[[:space:]]*#[[:space:]]*ifndef[[:space:]][_[:alnum:]]/ ||
      $line =~ m/^[[:space:]]*#[[:space:]]*elif[[:space:]][_[:alnum:]]/) {
    next if ($line =~ m/if[[:space:]][01]$/);
    next if ($line =~ m/ifndef[[:space:]].*_H/);
    next if ($line =~ m/DEBUG/ || $line =~ m/VERBOSE/);
    next if ($line =~ m/QT/);
    next if ($line =~ m/KDE/);
    next if ($line =~ m/EXPORT/);
    if (&osMacros($line,$lines[$linecnt]) || &compilerMacros($line,$lines[$linecnt])) {
      my($res) = &haves($line);
      $cnt++;
      if ($cnt == 1) {
        $lstr = "O/S or Compiler specific macro line\#" . $linecnt . "[$res]";
      } else {
        $lstr = $lstr . "," . $linecnt . "[$res]";
      }
      print "=> $line\n" if (&verboseArg());
    }
    next;
  }

  if ($line =~ m/^[[:space:]]*#[[:space:]]*warning/) {
    if (!&searchBack('\s*#\s*ifdef\s__GNUC__',$linecnt-1,2)) {
      $wcnt++;
      if ($wcnt == 1) {
        $wstr = "Guard #warning with '#ifdef __GNUC__' line\#" . $linecnt;
      } else {
        $wstr = $wstr . "," . $linecnt;
      }
      print "=> $line\n" if (&verboseArg());
    }
    next;
  }
}

if (!$cnt && !$wcnt) {
  print "okay\n" if (!&quietArg());
  exit 0;
} else {
  print "$lstr ($cnt)\n" if (!&quietArg() && $cnt);
  print "$wstr ($wcnt)\n" if (!&quietArg() && $wcnt);
  exit $cnt+$wcnt;
}

# search the previous $n lines for a pattern $p
sub searchBack {
  my($p,$l,$n) = @_;
  my($i);
  $n = $#lines if ($#lines < $n);
  for($i=1; $i<=$n; $i++) {
    if ($lines[$l-$i] =~ $p) {
      return 1;
    }
  }
  return 0;
}

sub Help {
  print "Check for cpp macros and usage\n";
  exit 0 if &helpArg();
}

sub Version {
  print "$Prog, version $Version\n";
  exit 0 if &versionArg();
}

sub Explain {
  print "C++ source files and non-installed headers should NOT use cpp conditionals that check for a certain O/S or compiler; instead use CMake HAVE_foo macros. We want to check for features discovered during CMake time rather than for a specific O/S.\n";
  exit 0 if &explainArg();
}

sub osMacros() {
  my($l,$lp1) = @_;
  return 1
      if (
        $l =~ m/Q_OS_/ ||
        $l =~ m/USE_SOLARIS/ ||
        $l =~ m/USE_NETBSD/ ||
        $l =~ m/USE_FREEBSD/ ||
        $l =~ m/_WIN32/ ||
        $l =~ m/_WIN64/ ||
        $l =~ m/__APPLE__/ ||
        $l =~ m/__svr4__/ ||
        $l =~ m/__linux__/ ||
        $l =~ m/__bsdi__/ ||
        $l =~ m/__FreeBSD__/ ||
        $l =~ m/__NetBSD__/ ||
        $l =~ m/__OpenBSD__/ ||
        $l =~ m/__DragonFly__/ ||
        $l =~ m/__GNU__/ ||
        $l =~ m/__osf__/ ||
        $l =~ m/__hpux/ ||
        $l =~ m/__sun/ ||
        $l =~ m/__sgi/ ||
        $l =~ m/_AIX/ ||
        $l =~ m/__CYGWIN__/
      );
  return 0;
}

sub compilerMacros() {
  my($l,$lp1) = @_;
  return 1
      if (
        $l =~ m/__BORLANDC__/ ||
        $l =~ m/__INTEL_COMPILER/ ||
        $l =~ m/Q_CC_/
      );
  return 1 if ($l =~ m/__GNUC__/ && $lp1 !~ /warning/);
  return 0;
}

sub haves() {
  my($l) = @_;
  my(@a) = split(' ',$l);
  my($guy);
  my($res)="";
  foreach $guy (@a) {
    next unless ($guy =~ m/_/);
    next if ($guy =~ m/HAVE_/);
    $guy =~ s/.*defined\(//;
    $guy =~ s/.*\(//;
    $guy =~ s/\).*//;
    $res .= $guy . ",";
  }
  $res =~ s/,$//;
  return $res;
}
