#!/usr/bin/env perl
#***************************************************************************
#                                  _   _ ____  _
#  Project                     ___| | | |  _ \| |
#                             / __| | | | |_) | |
#                            | (__| |_| |  _ <| |___
#                             \___|\___/|_| \_\_____|
#
# Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
# SPDX-License-Identifier: curl
#
###########################################################################

use strict;
use warnings;

my $srcdir = $ARGV[0] || ".";
my $builddir = $ARGV[1] || ".";

my @all;

my %tagged;
my %taggedunit;
my %unit;
my %unitnum;
my $error = 0;

sub check {
    my ($file) = @_;

    #print "scan $file\n";
    my $unit = "";
    my $func;
    my $level = 0;
    my $line = 0;

    open(D, "<$file");
    while(<D>) {
        $line++;

        if(/\@unittest (\d+)/ && !$level) {
            $unit .= "$1,";
        }

        if(/\b([a-z0-9_]*)\([^;]*/i && !$level && $unit) {
            $func = $1;
        }

        if(/^{/ && !$level) {
            # start of a function
            if($unit && $func) {
                #print "- $func tested in test $unit ($file:$line)\n";
                $tagged{$func} = "$file:$line";
                $taggedunit{$func} = "$unit";
                $func = "";
                $unit = "";
            }
            $level++;
        }
        elsif(/^\}/ && $level) {
            # end of a function declaration
            $level = 0;
        }
    }
    close(D);
}

#
# Find all Curl_ and curlx_ functions used in unit tests
my %seen;
open(F, "grep -E '(Curl|curlx)_[A-Za-z_0-9]*[(,]' \"$srcdir\"/tests/unit/unit[0-9]*.c /dev/null |");
while(<F>) {
    if(/^([^:]+):(.*)$/) {
        my ($file, $text) = ($1, $2);
        while($text =~ /\b((?:Curl|curlx)_[A-Za-z_0-9]*[(,])/g) {
            my $f = $1;
            next if($seen{"$file:$f"}++);
            if($f =~ s/\(\z//) {
                $unit{$f} = "func";
            }
            elsif($f =~ s/,\z//) {
                # this may not be a function, can be a variable
                $unit{$f} = "comma" unless($unit{$f});
            }
            my $num = 0;
            if($file =~ /unit(\d+)/) {
                $num = $1;
            }
            $unitnum{$f} .= "$num,";
        }
    }
}
close(F);

# Find all UNITTEST functions used in unit tests
open(U, "<$builddir/lib/unitprotos.h") ||
    die "missing $builddir/lib/unitprotos.h";
while(<U>) {
    if(/^UNITTEST.*[ *!]([a-z_0-9]*)\(/i) {
        $unit{$1} = "unitproto";
        $unitnum{$1} = "0"; # unknown still
    }
}
close(U);

#
# Find all function declarations with @unittest tags
my @cfiles = `find "$srcdir/lib" -type f -name '*.c'`;
for my $f (@cfiles) {
    chomp $f;
    check($f);
}

# Scan all tags, check if they were found in unit tests
for my $k (sort keys %tagged) {
    #printf "%s at %s\n", $k, $tagged{$k};
    if(!$unit{$k}) {
        print " - no $k in unit tests?\n";
        $error++;
    }
}

# Scan all functions found in unit tests, verify their tags
for my $u (sort keys %unit) {
    #printf "%s in %s\n", $u, $unitnum{$u};

    if($tagged{$u} && ($unitnum{$u} ne "0")) {
        # verify that the mentioned tags only mention unit tests where the
        # symbol is used
        my %usedunits;
        for(split(/,/, $unitnum{$u})) {
            $usedunits{$_}++;
        }
        my @tunits = sort split(/,/, $taggedunit{$u});

        for my $t (@tunits) {
            if(!$usedunits{$t}) {
                print "$u is tagged for test $t but not used there\n";
            }
        }
    }

    if(!$tagged{$u} && ($unit{$u} eq "func")) {

        # check if the name is a define
        my $declared = system("find \"$srcdir/lib\" -type f \\( -name '*.c' -o -name '*.h' \\) -exec grep -l '#define *$u' {} + | grep -q .");
        if(!$declared) {
            # we don't count macros
            next;
        }

        print " - $u was not tagged \@unittest\n";
        system("grep '$u' \"$srcdir\"/tests/unit/unit[0-9]*.c /dev/null");
        $error++;
    }
}

exit $error;
