#!/bin/bash

# ================================================================
# Reads the Miller DSL grammar file and generates Go code.
#
# This is not run on every build / commit / etc.
#
# It's intended to be run manually by the developer, as needed when mlr.bnf
# changes for example.
#
# Resulting auto-generated .go files should then be checked into source control.
# ================================================================

set -euo pipefail

verbose="false"
if [ $# -eq 1 ]; then
  if [ "$1" == "-v" ]; then
    verbose="true"
  fi
fi

# Build the bin/gocc executable:
#go get github.com/goccmack/gocc
go get github.com/johnkerl/gocc
bingocc="$GOPATH/bin/gocc"
if [ ! -x "$bingocc" ]; then
  exit 1
fi

rm -f src/parsing/*.txt
if [ "$verbose" = "true" ]; then
  lr1="src/parsing/LR1_conflicts.txt"
  $bingocc -v -o ./src/parsing -p miller/src/parsing src/parsing/mlr.bnf || expand -2 $lr1
else
  $bingocc -o ./src/parsing -p miller/src/parsing src/parsing/mlr.bnf
fi

# Code-gen directories:
#   src/parsing/errors/
#   src/parsing/lexer/
#   src/parsing/parser/
#   src/parsing/token/
#   src/parsing/util/

# Override GOCC codegen with customized error handling
cp src/parsing/errors.go.template src/parsing/errors/errors.go

for x in src/parsing/*/*.go; do gofmt -w $x; done
