#!/usr/bin/env perl
######################################################################
#
# Copyright 2007-2020 by Wilson Snyder.  This package is free software; you
# can redistribute it and/or modify it under the terms of either the GNU
# Lesser General Public License Version 3 or the Perl Artistic License
# Version 2.0.
#
# 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.
#
######################################################################

# DESCRIPTION: Diff bison files

use warnings;
use Getopt::Long;
use IO::File;
use strict;

our $Debug;
our $Opt_Unsup;

if (! GetOptions (
          #"help"       => \&usage,
          "debug"       => sub { $Debug = 1; },
          "unsup!"      => \$Opt_Unsup,  # Ignore unsupported
    )) {
    die "usage();"
}

diff($ARGV[0],$ARGV[1]);

sub diff {
    my $a=shift;
    my $b=shift;

    my $ta = "/tmp/bisondiff.$$.a";
    my $tb = "/tmp/bisondiff.$$.b";

    prep($a,$ta);
    prep($b,$tb);

    system("diff -u -w $ta $tb");
}

sub prep {
    my $filename = shift;
    my $wfilename = shift;

    my $fh = IO::File->new("<$filename") or die "%Error: $! $filename";
    my $fho = IO::File->new(">$wfilename") or die "%Error: $! writing $wfilename";

    my %declared;
    my %used;

    my $body = 0;
    my $rule = "";
    my $skip = 1;
    while (defined(my $line = $fh->getline)) {
        if ($skip == 1) {
            next if $line !~ /%token/;
            $skip = 2;
        }

        if ($Opt_Unsup) {
            $line =~ s!//UNSUP!|!g;
            $line =~ s!(\s+)\|(\s+)!$1$2!g;  # As "UNSUP" often replaces "|"
        }

        # %type<foo>
        $line =~ s/^(%\S+)<(\S+)>/$1/;
        # rule<foo>
        $line =~ s/^([a-zA-Z0-9_]+)<\S+>:/$1:/;
        # Productions
        $line =~ s/[ \t]{[^}]*?}/\t{}/g;

        $fho->print($line);
    }
}

# Local Variables:
# compile-command: "./bisondiff --unsup $VP/Parser/VParseBison.y ../src/verilog.y"
# End: