#!/usr/bin/perl -w
######################################################################
#
# Copyright 2007-2019 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: Debugging of bison output

use strict;

my $Debug;

my %declared;
my %used;

my $body = 0;
my $rule = "";
my $lineno = 0;
foreach my $line (<STDIN>) {
    $lineno++;
    chomp $line;
    $line =~ s!//.*$!!g;
    $line =~ s!\s+! !g;
    next if $line eq '';
    if ($line =~ m!^\%\%!) {
        $body++;
    } elsif ($body == 1) {
        $rule .= $line;
        if ($line =~ m!^\s*;\s*$!) {
            #print "Rule: $rule\n";
            ($rule =~ /^([a-zA-Z0-9_]+)(<\S+>)?:(.*)$/) or die "%Error: No rule name: $1\n";
            my $rulename = $1; my $preaction = $3;
            $declared{$rulename} = $lineno;
            $preaction =~ s/\{[^\}]*\}/ /g;
            #print "RULEN $rulename PA $preaction\n" if $Debug;
            $rule = '';
            foreach my $ref (split /\s+/, $preaction) {
                next if $ref !~ /^[a-zA-Z]/;
                next if $ref eq $rulename;
                if (!$used{$ref} && $declared{$ref}) {
                    print "   %Warning: $lineno: $ref used by $rulename after declaration\n";
                }
                $used{$ref} = $lineno;
                print "  ref $ref\n" if $Debug;
            }
        }
    }
}

# Local Variables:
# compile-command: "./bisonreader < ../src/verilog.y"
# End: