#!/usr/local/bin/perl
#
#  Turn the output from 'yacc-n3 -p' into several queries about
#  the database which had been input, based on the idea of genid
#  symbols as existentially quantified.
#
#  $Id: genid-to-query,v 1.1 2001/05/22 10:00:59 sandro Exp $
#
use strict;

my @tot=();
my %var=();

while(<>) {
    chomp;
    s/'genid:([^']*)'/cleanvar($1)/gie;
    s/.$//;
    push @tot, $_;
}

my $args=join(", ", values(%var));
my $clauses=join(",\n  ", @tot);
print "match :- match($args).\n";
print "match($args) :- \n  $clauses.\n";

my $sm="";
while (my ($in, $out) = each %var) {
  $sm .= "  write('$in'), write(' => '), writeln($out),\n";
}

print "showmatch :- match($args), $sm true.\n";

# print "guided_match :- showmatch.\n";
print "guided_match :- match, writeln('MATCH SUCCEEDS').\n";
print "guided_match :- writeln('MATCH FAILS.  To try to find the difference, lets run a trace.\nType S to let it free-run; the highest numbered Fail is probably the problem.\n'), trace, match.\n";

sub cleanvar {
  my $in = shift;
  $in =~ s/[^A-Za-z0-9]/sprintf("_%02x", ord($1))/eg;
  my $out = "_" . $in;
  $var{$in} = $out;
  return $out;
}
