

# ---------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------

parseBin=$RAC/bin/parse
translateBook=$RAC/lisp/translate
acl2Bin=$ACL2

# ---------------------------------------------------------------------
# options parsing
# ---------------------------------------------------------------------

usage() {
    cat <<USAGEEOF
Usage:

  rac [options] srcfile

rac parses the given srcfile, checks that it satisfies the RAC
subset restrictions, and optionally generates various outputs.

Options are:

  -a                 Generate lisp output for ACL2.

  -r                 Extract only the RAC code.

  -I dir             Look for include files in directory 'dir'

  -h                 Print this message.
USAGEEOF
}

srcfile=
acl2=
rac=
incdirs="-I $RAC/include"

OPTS=`getopt hacrI: $@`
if [ $? != 0 ]
then
    usage;
    exit 1
fi

eval set -- "$OPTS"
while true; do
    case $1 in
    -a | --acl2)
        acl2=1;
        shift 1;
        ;;
    -r | --rac)
        rac=1;
        shift 1;
        ;;
    -I)
        incdirs="$incdirs -I $2";
        shift 2;
        ;;
    --)
        shift 1;
        break
        ;;
    esac
done

# Extract the source filename and
# make sure only one of ctos, acl2, rac is specified

if [[ -z "$1" ]]
then
    usage;
    exit 1
else
    srcfile=$1;
    shift 1;
    # extra input left over?
    if [[ -n "$1" ]]
    then
        usage;
        exit 1
    fi
fi

if [[ "$acl2" && "$rac" ]]
then
    usage;
    exit 1
fi

# ---------------------------------------------------------------------
# Call the rac parser in the appropriate mode
# ---------------------------------------------------------------------

# Die immediately on any error
set -e

basename=${srcfile%.*}
cppopts="-D__RAC__ -C -std=c++14"

g++ $cppopts $incdirs $basename.cpp -E -o $basename.i;

if [[ -z "$acl2" && -z "$rac" ]]
then
    $parseBin $basename
fi

if [[ "$rac" ]]
then
    $parseBin $basename -rac
fi

if [[ "$acl2" ]]
then

     # Use suffix ".ast.lsp" instead of ".ast.lisp" so that ACL2's 
     # cert.pl program won't try to certify it.

    $parseBin $basename -acl2 $basename.ast.lsp

    $acl2Bin > $basename.acl2.log <<EOF
      (include-book "$translateBook")
      (set-inhibit-output-lst '(prove event proof-tree))
      (translate-program "$basename.ast.lsp" "$basename.lisp" state)
      (pretty-print "$basename.ast.lsp" "$basename.ast.pp" state)
      :u
      (include-book "rtl/rel11/lib/rac" :dir :system)
      (certify-book "$basename" 1)
EOF

fi
