#!/usr/bin/env bash

# This script calls MLton.

set -e

lib='lib unset'
gcc='gcc'
mlton="$lib/mlton-compile"
world="$lib/world.mlton"
nj='sml'
eval `$lib/platform`
njHeap="$lib/mlton.$HOST_ARCH-$HOST_OS"

rargs=""
case "$1" in
@MLton)
	shift
	while [ "$#" -gt 0 -a "$1" != "--" ]; do
		rargs="$rargs $1"
		shift
	done
	if [ "$#" -gt 0 -a "$1" == "--" ]; then
		shift
	else	
		echo '@MLton missing --'
		exit 1
	fi
	;;
esac

# If $mlton is executable and $world exists and is not older than
# $njHeap (which exists), then use MLton, otherwise use SML/NJ.
doit () {
	if [ -x "$mlton" -a -s "$world" -a ! "$njHeap" -nt "$world" ]; then
		exec "$mlton" @MLton load-world "$world" ram-slop 0.5 $rargs -- "$@"
	elif [ -s "$njHeap" ]; then
		exec "$nj" @SMLload="$njHeap" "$@"
	fi
	echo 'Unable to run MLton.  Check that lib is set properly.' >&2
	exit 1
}

# For align-{functions,jumps,loops, we use -m for now instead of
# -f because old gcc's will barf on -f, while newer ones only warn
# about -m.  Someday, when we think we won't run into older gcc's,
# these should be changed to -f.

# You may need to add a line with -link-opt '-L/path/to/libgmp' so
# that the linker can find the gmp.

doit "$lib" \
	-cc "$gcc"						\
	-cc-opt "-I$lib/include"				\
	-cc-opt '-O1'						\
	-cc-opt '-fno-strict-aliasing -fomit-frame-pointer -w'	\
	-target-cc-opt x86					\
		'-fno-strength-reduce
		-fschedule-insns
		-fschedule-insns2
		-malign-functions=5
		-malign-jumps=2
		-malign-loops=2
		-mcpu=pentiumpro'				\
	-target-cc-opt sparc 					\
		'-Wa,-xarch=v8plusa
		-fcall-used-g5
		-fcall-used-g7
		-m32
		-mv8
		-mcpu=ultrasparc'				\
	-target-link-opt solaris '-ldl -lnsl -lsocket'		\
	-link-opt '-lgdtoa -lm'					\
	"$@"
