#!/bin/bash
#
# Copyright (C) 2017 The Android Open Source Project
#
# Licensed 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.

JAVAC_SOURCE=1.8
JAVAC_TARGET=1.8

JAVAC_FLAGS="-source ${JAVAC_SOURCE} -target ${JAVAC_TARGET}"

# Suppress warning over bootclass path from Java 9 compiler (if used).
JAVAC_FLAGS="${JAVAC_FLAGS} -Xlint:-options"

# Check interface method defintions cause warnings and {default,static}
# interface method invocations fail hard.
declare -A SUPPORT_THRESHOLD
SUPPORT_THRESHOLD["DefaultDefinition.class"]=0
SUPPORT_THRESHOLD["InvokeStatic.class"]=24
SUPPORT_THRESHOLD["InvokeDefault.class"]=24
SUPPORT_THRESHOLD["StaticDefinition.class"]=0

CLASS_FILES=${!SUPPORT_THRESHOLD[@]}
SOURCE_FILES=${CLASS_FILES//class/java}

${JAVAC} ${JAVAC_FLAGS} ${SOURCE_FILES}

for API_LEVEL in 19 20 21 22 23 24 25; do
  echo --------------------- Testing $API_LEVEL ------------------------
  for c in $CLASS_FILES; do
    echo $c
    dx --dex --dump-width=500 --dump-to=$c.log --min-sdk-version=$API_LEVEL $c
    if [ $? = 0 ]; then
      if [[ $API_LEVEL -lt ${SUPPORT_THRESHOLD[$c]} ]]; then
        echo Unexpected success for $c at API level $API_LEVEL 1>&2
        cat $c.log
        exit 0
      fi
    else
      if [[ $API_LEVEL -ge ${SUPPORT_THRESHOLD[$c]} ]]; then
        echo Unexpected failure for $c at API level $API_LEVEL 1>&2
        exit 0
      fi
    fi
  done
done

# Now repeat with --allowAllInterfaceMethodInvokes which turns hard
# failures for {default,static} interface invokes to warnings.
EXTRA_DX_FLAG=--allow-all-interface-method-invokes

SUPPORT_THRESHOLD["DefaultDefinition.class"]=0
SUPPORT_THRESHOLD["InvokeStatic.class"]=21
SUPPORT_THRESHOLD["InvokeDefault.class"]=0
SUPPORT_THRESHOLD["StaticDefinition.class"]=0

CLASS_FILES=${!SUPPORT_THRESHOLD[@]}
SOURCE_FILES=${CLASS_FILES//class/java}

${JAVAC} ${JAVAC_FLAGS} ${SOURCE_FILES}

for API_LEVEL in 19 20 21 22 23 24 25; do
  echo --------------------- Testing $API_LEVEL ------------------------
  for c in $CLASS_FILES; do
    echo $c
    dx --dex --dump-width=500 --dump-to=$c.log --min-sdk-version=$API_LEVEL $EXTRA_DX_FLAG $c
    if [ $? = 0 ]; then
      if [[ $API_LEVEL -lt ${SUPPORT_THRESHOLD[$c]} ]]; then
        echo Unexpected success for $c at API level $API_LEVEL 1>&2
        cat $c.log
        exit 0
      fi
    else
      if [[ $API_LEVEL -ge ${SUPPORT_THRESHOLD[$c]} ]]; then
        echo Unexpected failure for $c at API level $API_LEVEL 1>&2
        exit 0
      fi
    fi
  done
done