#!/bin/bash
## Licensed to the Apache Software Foundation (ASF) under one
## or more contributor license agreements.  See the NOTICE file
## distributed with this work for additional information
## regarding copyright ownership.  The ASF licenses this file
## to you under the Apache License, Version 2.0 (the
## "License"); you may not use this file except in compliance
## with the License.  You may obtain a copy of the License at
##
##     http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.

# Parser builder

GRAMMAR="${GRAMMAR:-"json.jj"}"
ROOT="../.."
PKG=org/apache/jena/atlas/json/io/parserjavacc/javacc

# --------------------------------------------------------

function grammar
{
    local FILE="$1"
    local PKG="$2"
    local CLASS="$3"
    echo "JavaCC: $1 $2 $3"

    DIR="$ROOT/src/main/java/$PKG"
    ( cd $DIR ; rm -f TokenMgrError.java ParseException.java Token.java JavaCharStream.java SimpleCharStream.java )

    echo "---- Process grammar -- $1"
    javacc -OUTPUT_DIRECTORY=$DIR -JDK_VERSION=1.5 "${FILE}"
    RC=$?

    [ "$RC" = 0 ] || return $RC

##     echo "---- Create HTML"
##     jjdoc -OUTPUT_FILE=${FILE%%.jj}.html "${FILE}"
##     echo "---- Create text form"
##     jjdoc -TEXT=true -OUTPUT_FILE=${FILE%%.jj}.txt "${FILE}"
    
    echo "---- Fixing Java warnings in JavaCharStream..."
    F="$DIR/JavaCharStream.java"
    if [ -e "$F" ]
    then
	sed -e 's/public/\n@SuppressWarnings("all")\npublic/' < $F > F 
	mv F $F
    fi
    
    echo "---- Fixing Java warnings in TokenMgrError"
    F="$DIR/TokenMgrError.java"
    if [ -e "$F" ]
    then
	sed -e 's/public class TokenMgrError/\n@SuppressWarnings("all")\npublic class TokenMgrError/' < $F > F 
	mv F $F
    fi
    
    echo "---- Fixing Java warnings in ${CLASS} ..."
    F="$DIR/${CLASS}.java"
    sed -e 's/public class /\n@SuppressWarnings("all")\npublic class /' < $F > F
    mv F $F

    echo "---- Done"
}

## if [ $# == 0 ]
## then
##     set -- json
##     ## echo "Usage: grammar [json]" 1>&2
##     ## exit 1
##     fi

if [ $# == 0 ]
then
    set -- json
    fi


for G in "$@"
  do
  case "$G" in
  json)
    cpp -P -C "$GRAMMAR" > parser.jj
    grammar parser.jj $PKG JSON_Parser
    [ "$RC" = 0 ] && rm -f parser.jj
    ;;
  *)    echo "**** Unknown grammar: $G" 1>&2
    ;;
    esac
done
