#!/bin/sh

# Copyright (c) 2015, Electric Cloud, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
#   - Redistributions of source code must retain the above copyright
#     notice, this list of conditions and the following disclaimer.
#
#   - Redistributions in binary form must reproduce the above copyright
#     notice, this list of conditions and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# (As an historical note, the above license instantiates
# the "BSD 2-Clause License" template that was presented
# by the Open Source Initiative at
#
#   http://www.opensource.org/licenses/bsd-license.php
#
# on 2012-02-23.)

# Summary:
#
# Generates the set of interfaces extended by each implemented
# interface, along with a map from each supported interface to
# an implemented interface that extends it.
#
# Also generates a map from each function interface that the loader
# is able to call to the extension of that interface that the loader
# will use to actually satisfy that request.  Typically the loader
# will provide the most-extended interface that is not significantly
# more costly than the one requested.
#
# Note that typically our terminology categorizes the loader as the
# implementation and the dynamically loaded function as the client.
# See "vrpsx_identified_function.h" for a discussion of this point.
#
# Compatibility:
#
# This "sh" script should work on a POSIX system.  We use
# the "cat", "sort", and "mv" programs specified by POSIX.

set -e

if test $# -lt 2
then
    echo "Usage: $argv0 <impl-out> <load-out> <interface-outdir>" >&2
    exit 2
fi

impl_out="$1"
shift

load_out="$1"
shift

interface_outdir="$1"
shift

sup_tmp="sup_$$.tmp"

impl_tmp="$impl_out.tmp1"

load_tmp="$load_out.tmp1"
load_sup="$load_out.tmp2"

clean() {
    rm -f "$sup_tmp" "$impl_tmp" "$load_tmp" "$load_sup"
}

clean

trap 'clean' EXIT HUP INT QUIT TERM


# Given a list of the interfaces that some object implements,
# prints the map from supported interface identifier to the identifier for
# the extension interface through which we will provides that support.

support_map() {
    function_style="$1"
    object="$2"
    interfaces="$3"

    # For each most-extended interface that we implement with that object:

    rm -f "$sup_tmp"

    for name in $interfaces
    do
        # The extension relationship can be expressed as a tree whose leaves
        # are the interfaces for which we do not support any extensions.

        leaf="`cat $interface_outdir/vrpsx_$name.id`"

        sort -k 1,1 $interface_outdir/vrpsx_$name.ext | (
            while read narrowing member
            do
                # Add to precursor for the map from supported interfaces
                # to the extensions that we use to provide that support.

                echo "$narrowing $leaf $name $member" >> "$sup_tmp"
            done
        )
    done

    # Print the map from supported interface identifier
    # to the identifier for the extension interface through
    # which we will provides that support:

    if test "$function_style" -ne 0
    then
        binding_type=function_binding_t
    else
        binding_type=object_binding_t
    fi

    echo "static $binding_type const ${object}_support_map[] ="
    sort -u -k 1,1 "$sup_tmp" | (
        delimiter="{ "
        while read narrowing leaf name member
        do
            if test -z "$member"
            then
                if test "$function_style" -ne 0
                then
                    member=""
                else
                    member=", 0"
                fi
            else
                if test "$function_style" -ne 0
                then
                    echo "function $narrowing cannot be in member $member" >&2
                    exit 1
                else
                    member=", offsetof(vrpsx_${name}_t, $member)"
                fi
            fi

            echo "    $delimiter{ 0x$narrowing, 0x$leaf$member }"

            delimiter=", "
        done
    )
    echo "    };"
    echo ""

    echo "static vrpsx_interface_identifier_t const *${object}_supports("
    echo "    vrpsx_interface_identifier_t interface_identifier"
    if test "$function_style" -ne 0
    then
        echo "    )"
    else
        echo "    , size_t *offset)"
    fi
    echo "{"
    if test "$function_style" -ne 0
    then
        echo "    return caller_supports("
    else
        echo "    return object_supports("
    fi
    echo "            ${object}_support_map,"
    echo "            VRPSX_ARRAY_DIMENSION(${object}_support_map),"
    echo "            interface_identifier"
    if test "$function_style" -eq 0
    then
        echo "            , offset"
    fi
    echo "            );"
    echo "}"
    echo ""
    echo ""
}


support_map 0 direct_embedding embedding >> "$impl_tmp"

support_map 0 direct_system_error system_error >> "$impl_tmp"


support_map 0 loader_system_initial system_initial >> "$load_tmp"

support_map 0 loader_embedding_initial embedding_initial >> "$load_tmp"


# We list system_main first because we prefer to skip computation
# of the outer environment if it will not be used.

support_map 1 loader_main "system_main embedding_main" >> "$load_tmp"


# Success; rename the output files to their final names.

mv -f "$impl_tmp" "$impl_out"
mv -f "$load_tmp" "$load_out"
