%% Oh Emacs, this is a -*- sh -*- script, despite appearance.
\documentclass[12pt]{article}
\usepackage{axiom}
\usepackage[latin1]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{fancyvrb}
\usepackage{pslatex}
\usepackage{url}

\newcommand{\email}[1]{\url{#1}}
\CustomVerbatimEnvironment{chunk}{Verbatim}{frame=none,fontsize=\small}

\def\nwendcode{\endtrivlist \endgroup}
\let\nwdocspar=\par
\let\nowebsize=\small


\title{The Toplevel \File{configure.ac} Pamphlet}
\author{Gabriel Dos~Reis}

\begin{document}
\maketitle

\begin{abstract}
  This pamphlet details the configuration process of setting up
  \Tool{FriCAS} for build from source codes.
  It also explains general dependencies on external tools.
  The configuration process scrutinizes the build, host,  and target
  environments, and finally instantiates \File{Makefile}s for building
  \Tool{FriCAS} interpreter, compiler, libraries, and auxiliary tools
  where appropriate.
\end{abstract}

\section{Introduction}
\label{sec:intro}

This is the top-level \Tool{Autoconf} description that sets up the
minimum environment for building \Tool{FriCAS}.  This effort
strives for describing the build machinery at a sufficiently abstract
level that
enables interoperability with existing conventional frameworks, \eg{}
the GNU build framework.
The task is compounded by the fact that the existing \Tool{FriCAS} system
is complex and very poorly documented, with blatantly conflicting or
questionable codes.

The \Tool{FriCAS} system is written for the most part in Lisp, or
thereof.  That in itself is a great source of portability
problems\footnote{even after half a century of existence},
let alone issues related to insulation from mainstream
development tools, dependence on particular Lisp implementation details, etc.
A tiny part of it, mainly the interface with host operating system, is
written in the C programming language.  That does not improve on the
portability problems.  Fortunately, there are well-supported,
widely used, widely available, well tested tools supporting
C-derived development environments across platforms.  The GNU
\Tool{Autotools} being one of them.  For the moment, we only make use of
the \Tool{Autoconf} component.  This build machinery does not
use \Tool{Automake} and \Tool{Libtool}.  People intending to modify
this part of the build machinery are expected to be familiar with
\Tool{Autotconf}.

The \File{Makefile} pamphlets that compose the build machinery are
written in a way that abstracts platform idiosyncrasies into
parameters.  The purpose of the \File{configure.ac} script is to
find values for those parameters, on a given platform, necessary to
instantiate the \File{Makefile}s, and therefore to set up a concrete
build machinery.  And that task must be accomplished portably.

\section{Generalities on build instantiations}

\subsection{Two actors}

The instantiation of the abstract build machinery description requires
that we gather information from two platforms:
\begin{enumerate}
\item the \emph{build platform}, and
\item the \emph{host platform}.
\end{enumerate}

The build platform is where we build the system, \eg{} where
the \File{configure} script is executed.  The host platform
is where \Tool{FriCAS} will run.  Note that in full generality, there is
a third platform: the \emph{target platform}.  It is the platform for which
we are building the system.

For typical build instantiations, those  three  platforms are the same: we
call that a \emph{native build instantiation} or just \emph{native build}.
The FriCAS system only support native build at the moment.

To facilitate the porting of programs across platforms, the GNU build
system has standardized on designation of platforms, called
\emph{configuration names}.  A configuration name used to be
made of three parts\footnote{hence the term \emph{canonical triplet} in
    earlier versions of \Tool{Autoconf}}:
\textsl{cpu--vendor--os}.  Examples are
[[i686-pc-linux-gnu]], or [[sparc-sun-solaris2.8]].

The \textsl{cpu}
part usually designates the type of processor used on the platform.
Examples are [[i686]], or [[sparc]], or [[x86_64]].

The \textsl{vendor} part formally designates the manufacturer of
the platform.  In many cases it is simply [[unknown]].  However,
in specific cases, you can see the name of a workstation vendor such
as [[sun]], or [[pc]] for an IBM PC compatible system.

The \textsl{os} part can be either \textsl{system} (such as [[solaris2.8]])
or \textsl{kernel--system} (such as [[linux-gnu]]).

Here is how we get the canonical names for the above three platforms:
<<host build target platforms>>=
AC_CANONICAL_SYSTEM

@

After that call, the configuration names of the three platforms
are available in the shell variables [[build]], [[host]], and [[target]].

\subsubsection{Cross build}

As we said earlier, a native build instantiation is one where all
[[build]], [[host]], and [[target]] have the same value.  However,
when porting programs to other platforms, it is not always possible
to do a native build --- either because all the tools are not
available on that machine, or because it is much more convenient to
build the software on a faster machine. Both situations are quite
common.

Those considerations bring us to the notion of cross build
instantiation (also called cross compilation).
We say that the build instantiation is a \emph{cross build} when
the build platform is different from the target platform; \eg{}, when
[[build]] $\neq$ [[target]].

For the moment, the \Tool{FriCAS} base source code is written
in a way that does not support cross build.  However, we do
want to make cross build possible; consequently we issue
a warning when we detect attempt at cross build:
<<host build target platforms>>=
if test $build != $target; then
   AC_MSG_WARN([Cross build is not supported.])
   AC_MSG_WARN([Please notify fricas-devel@googlegroups.com if you succeed.])
fi
@
Note that we do not stop the configuration process because we do seek
contributions for cross build support.

Note that the shell variable [[cross_compiling]],
set by the \Tool{Autoconf} macro [[AC_PROG_CC]], indicates whether
the C compiler used is a cross compiler.

\subsubsection{Canadian cross}

As we said previously, most software don't care about the target
platform.  But compilers do.  And \Tool{FriCAS} does because, among
other things, it uses Lisp and C compilers, and it provides a Spad compiler.
Another type of build instantiation arises when the host platform
is different from the target platform.  The resulting compiler
is called a \emph{cross compiler}.  Please note the distinction here:
a compiler that is cross compiled with [[host]] $=$ [[target]] is
not a cross compiler; it is a \emph{native compiler}.
A cross compiler is one with [[host]] $\neq$ [[target]].

The type of the compiler should not be confused with the type of the
build instantiation.  It perfectly makes sense to have a build
instantiation that cross builds a cross-compiler, \ie{} all three
platforms are different: This is called \emph{Canadian cross}.
The \Tool{FriCAS} system does not that support that level of
sophistication yet.  Although we could test for Canadian cross build
at this point, we delay that check for when we look for a C compiler.

\subsection{Directories for the build instantiation}

Although \Tool{FriCAS} does not support cross build yet, let
alone Canadian cross, we want to make sure that we do not write
the build machinery in a way that actively unsupports
cross build.  Consequently, in the build tree, we sequester
tools that we build and use on the build platform,
in  sub-directories different from others.

\section{Host characteristics}

As mentioned in the introduction, a small part of \Tool{FriCAS} is
written in the C programming language.  That C runtime support
can be decomposed in three components:
\begin{enumerate}
\item core runtime support,
\item graphics (including HyperDoc), and
\item terminal I/O.
\end{enumerate}

\subsection{Core runtime}

\subsubsection{Signals}

The host platform must be able to handle signals.  Although, this is
not strictly necessary, that is the way \Tool{FriCAS} source code
is currently written.  We ask for a POSIX or ISO C semantics, though
we have a strong preference for POSIX-conformant semantics.

<<C headers and libraries>>=
AC_CHECK_HEADERS([signal.h],
                 [],
                 [AC_MSG_ERROR([FriCAS needs signal support.])])
AC_CHECK_DECLS([sigaction], [], [],
               [#include <signal.h>])
@


\subsubsection{Files and directories}

Some parts of \Tool{FriCAS} manipulate files and directories.  They
more or less directly reflect the underlying platform semantics.
For the moment, we require POSIX semantics, though that does not
seem necessary.  That restriction should be removed as soon as possible.

<<C headers and libraries>>=
AC_CHECK_HEADERS([sys/stat.h],
                 [],
		 [AC_MSG_ERROR([FriCAS needs <sys/stat.h>.])])
AC_CHECK_HEADERS([unistd.h], [],
                 [AC_MSG_ERROR([FriCAS needs <unistd.h>])])
AC_CHECK_DECLS([getuid, geteuid, getgid, getegid], [], [],
               [#include <unistd.h>])

AC_CHECK_DECLS([kill], [], [],
               [#include <signal.h>])
@

\subsubsection{Sockets}

The host environment must be capable of handling communication through
sockets.  This is required for interfacing \Tool{FRICASsys}
and \Tool{Superman}.  Notice that ideally, we should decouple
that interface in such a way that we can still build \Tool{FriCAS}
when \Tool{Superman} is not needed or a socket library is not
available.

<<C headers and libraries>>=
case $host in
    *mingw*)
	AC_CHECK_HEADERS([winsock2.h],
	                [fricas_host_has_socket=yes],
			[])
	fricas_c_runtime_extra="-lwsock32"
	;;
    *)
        AC_CHECK_HEADERS([sys/socket.h],
                         [fricas_host_has_socket=yes],
		         [])
	;;
esac

## solaris-based systems tend to hide the socket library.
case $host in
    *solaris*)
	AC_SEARCH_LIBS([accept], [socket],
	    [fricas_c_runtime_extra="-lsocket"],
	    [AC_MSG_ERROR([socket library not found])])
	;;
    *) ;;
esac

AC_EGREP_HEADER([has_af_local],
                [#if HAVE_SYS_SOCKET_H
                 #  include <sys/socket.h>
                 #else
                 #  include <winsock2.h>
                 #endif
                 #ifdef AF_LOCAL
                   has_af_local
                 #endif],
                 [AC_DEFINE([HAVE_AF_LOCAL], [1], [Host has AF_LOCAL])])


AC_EGREP_HEADER([has_af_unix],
                [#if HAVE_SYS_SOCKET_H
                 #  include <sys/socket.h>
                 #else
                 #  include <winsock2.h>
                 #endif
                 #ifdef AF_UNIX
                   has_af_unix
                 #endif],
                 [AC_DEFINE([HAVE_AF_UNIX], [1], [Host has AF_UNIX])])

@

\subsection{Pty support}

[[clef]] and [[sman]] use ptys to communicate with [[FRICASsys]]. The
legacy pty code doesn't work on MacOS X (it also have problem on some
Linux installations). We will try to build with the Unix98 standard
[[openpty]] function. We need to detect two headers and a library.
Linux has openpty defined in [[pty.h]], MacOS X define it in [[util.h]].
FreeBSD is supposed to have a definition in [[libutil.h]].

Linux and (probably) Mac OSX have openpty in libutil.

<<C headers and libraries>>=

AC_CHECK_HEADERS([util.h],
                   [],
                   [AC_CHECK_HEADERS([pty.h], [], [])
                   ]) # HAVE_UTIL_H or HAVE_PTY_H

AC_CHECK_DECL([openpty],
                 [AC_DEFINE([HAVE_OPENPTY_DECL], [1],
		              [openpty is declared])], [],
                 [#if defined(HAVE_UTIL_H)
                  # include <util.h>
                  #elif defined(HAVE_PTY_H)
                  # include <pty.h>
                  #endif
                 ]) # HAVE_OPENPTY_DECL

AC_CHECK_LIB([util], [openpty],
                 [AC_DEFINE([HAVE_OPENPTY], [1],
		            [openpty is available])
                   fricas_c_runtime_extra="${fricas_c_runtime_extra} -lutil"
                 ]) # HAVE_OPENPTY

AC_SUBST(fricas_c_runtime_extra)

@
\subsection{Terminal I/O}

<<C headers and libraries>>=
AC_CHECK_HEADERS([sys/wait.h])

if test x"$ac_cv_header_sys_wait_h" = xyes; then \
    AC_CHECK_DECLS([wait],
                   [],
                   [],
                   [#include <sys/wait.h>])
fi

AC_CHECK_DECLS([fork],
               [],
               [],
               [#include <unistd.h>])

if test x"$ac_cv_have_decl_fork" = xyes \
     -a x"$ac_cv_have_decl_wait" = xyes; then \
    fricas_c_runtime="$fricas_c_runtime terminal_io"
    fricas_src_all="$fricas_src_all all-sman all-clef"
    fricas_src_subdirs="$fricas_src_subdirs clef sman"
    FRICAS_MAKEFILE([src/clef/Makefile])
    FRICAS_MAKEFILE([src/sman/Makefile])
else
    AC_MSG_NOTICE([Superman component is disabled.])
fi

fricas_src_all="all-fricassys $fricas_src_all"
@


\subsection{Graphics}

\subsubsection{Where is X11?}

One of the thorniest issues with programs that use the X Window System
is portability.  There exist many implementations of the X11
specification, each with its own variations, extensions, and what
not.  Designing hand-written makefiles for such programs can be a
daunting task, fraut with all kinds of traps.  Fortunately, \Tool{Autoconf}
provides us with some help, namely the macro [[AC_PATH_X]] and
[[AC_PATH_XTRA]].  The former searches the directories where the
X11 include files and the library files reside.  The latter is an
enhanced version that
\begin{itemize}
\item computes the C compiler flags required by X11;
\item computes the linker flags required by X11;
\item checks for special libraries that some systems need in order to
   compile X11 programs;
\item checks for special X11R6 libraries that need to be linked before
  the flag [[-lX11]].
\end{itemize}

<<C headers and libraries>>=
AC_PATH_XTRA
## Output directives for the C compiler
AC_SUBST(X_CLFAGS)
## Output directives for the linker
AC_SUBST(X_LIBS)
## Output any extra libraries required by X11
AC_SUBST(X_EXTRA_LIBS)

## Finally, output the list of libraries that need to appear before -lX11
## Some part of FriCAS depends on Xpm.  That library has kind uncertain
## future.  At some point in the past, it was deprecated, to be
## replaced by xpm-nox; then came back again.  So, its support may
## vary from system to system.  For the moment, we do a quick sanity
## check and disable X11 if Xpm is not present.  Long term, FriCAS should
## get rid of dependence on Xpm.  Another possibility is to (optionally)
## bundle Xpm source tarball and build Xpm if needed.

if test -z $no_x; then
  AC_CHECK_LIB([Xpm], [XpmReadFileToImage],
              [fricas_has_xpm=yes],
	      [fricas_has_xpm=no],
	      [$X_LIBS -lX11])
else
  fricas_has_xpm=no
fi

X_PRE_LIBS="-lXpm $X_PRE_LIBS"
AC_SUBST(X_PRE_LIBS)

## If the system supports X11, then build graphics and hyperdoc
if test x"$fricas_has_xpm" = xyes; then
    fricas_c_runtime="$fricas_c_runtime graphics"
    fricas_src_all="$fricas_src_all all-graph"
    fricas_src_subdirs="$fricas_src_subdirs graph"
    FRICAS_MAKEFILE([src/graph/Makefile])
    FRICAS_MAKEFILE([src/graph/Gdraws/Makefile])
    FRICAS_MAKEFILE([src/graph/view2D/Makefile])
    FRICAS_MAKEFILE([src/graph/view3D/Makefile])
    FRICAS_MAKEFILE([src/graph/viewAlone/Makefile])
    FRICAS_MAKEFILE([src/graph/viewman/Makefile])
else
    AC_MSG_NOTICE([The Graphics and HyperDoc components are disabled.])
fi
AC_SUBST(fricas_src_all)
@

\subsubsection{HyperDoc}

The HyperDoc component needs string pattern matching.
We require [[<regex.h>]], with POSIX-conformant definition.
Note this test makes sense only if X11 is available, for otherwise
we certainly are not going to build HyperDoc.
<<C headers and libraries>>=
if test x"$fricas_has_xpm" = xyes; then
   AC_CHECK_HEADER([regex.h],
                   [fricas_src_all="$fricas_src_all all-hyper all-paste"
		    fricas_src_subdirs="$fricas_src_subdirs hyper paste"
		    FRICAS_MAKEFILE([src/paste/Makefile])],
                   [AC_MSG_NOTICE([HyperDoc is disabled.])])
fi
# We need the Makefile (for util.ht) even if we do not build HyperDoc.
FRICAS_MAKEFILE([src/hyper/Makefile])
@

\subsection{Lisp runtime}

<<platform specific bits>>=

case $target in
    *bsd*)
        AC_DEFINE([BSDplatform], [], [BSD flavour])
	CCF="-O2 -pipe -fno-strength-reduce -Wall -D_GNU_SOURCE -I/usr/local/include"
	LDF="-L/usr/local/lib"
	;;
    *darwin*)
        AC_DEFINE([MACOSXplatform], [], [MACOX flavour])
	CCF="-O2 -fno-strength-reduce -Wall -D_GNU_SOURCE \
	    -I/usr/include -I/usr/include/sys"
        fricas_gcl_bfd_option="--disable-statsysbfd \
                                --enable-machine=powerpc-macosx"
        fricas_gcl_mm_option="--enable-vssize=65536*2"
	;;
esac

GCLOPTS="$fricas_gcl_bfd_option $fricas_gcl_mm_option $fricas_gcl_x_option"

AC_SUBST(PLF)
AC_SUBST(CCF)
AC_SUBST(LDF)
AC_SUBST(LISP)
AC_SUBST(GCLOPTS)
@

The C preprocessor symbols [[BSDplatform]], [[LINUXplatform]], etc. are being
used as ``catch all'' for unstructured codes.  They should be
removed from the source base.  Any source file using those should be
properly documented as its needs are, and a narrowed, specific configure
test should be added.


\section{The build platform}

\subsection{Build utilities}
Most of the tools we're testing for are with respect to the build
environment.  However, notice that since we only support \emph{native}
build at the moment, the tests are also for the host and target
platforms.
<<build utils>>=
## Accumulate list of utils needed for the build platform
## It is vital that noweb is present in the build environment.
fricas_all_prerequisites=

<<find make>>

<<find C compiler>>

<<file utils>>

<<awk and tar program>>

<<binary utils>>

<<doc utils>>

<<find lisp>>
<<lisp options>>
<<compiled lisp extension>>

AC_SUBST(fricas_all_prerequisites)
@

The next paragraphs detail each of the cluster of build utilities
[[configure]] looks for.

\paragraph{The \Tool{Make} program.}

Of course, no build can proceed with \File{Tool} inexisting from
the build-environment.  We insist on GNU \Tool{Make} program as there
are way too many variations, way too many incompatible implementations
and extensions.  Please, note that this requirement just reflects
\Tool{FriCAS}'s dependencies on external tools:  \Tool{FriCAS} relies on
\Tool{GCL}, which in turn uses \Tool{GCC}.  Building \Tool{GCC} requires
\Tool{GNU Make}, and \Tool{GCL} itself requires \Tool{GNU Make}.
<<find make>>=
case $build in
    *linux*)
	# GNU/Linux systems come equipped with GNU Make, called `make'
        AC_CHECK_PROGS([MAKE], [make],
                       [AC_MSG_ERROR([Make utility missing.])])
	;;
    *)
        # Other systems tend to spell it `gmake' and such
        AC_CHECK_PROGS([MAKE], [gmake make],
                       [AC_MSG_ERROR([Make utility missing.])])
	if ! $MAKE --version | grep 'GNU' 2>/dev/null; then
	    AC_MSG_ERROR([FriCAS build system needs GNU Make.])
	fi
	;;
esac
@

\paragraph{C compiler}
First of all, check for a C compiler.  As written, this test is OK
because currently we support only native builds.  However,
 it needs to be more carefully written when we move to cross-compilation.
FriCAS, in its current form, cannot be compiled with a C compiler
other than from GNU.  We take that as a requirement.
<<find C compiler>>=
## Make sure the C compiler is from GCC
AC_PROG_CC
if test x$GCC != xyes; then
    AC_MSG_ERROR([We need a C compiler from GCC])
fi
fricas_cflags="-O2 -fno-strength-reduce -Wall -D_GNU_SOURCE"
AC_SUBST(fricas_cflags)

## What is the extension of object files on this platform?
AC_OBJEXT
@

\paragraph{File utils}
Then, check for a usable [[install]] program.  Also, find out
way to hard- or soft-link files.
<<file utils>>=
AC_PROG_INSTALL
# AC_PROG_LN_S
AC_CHECK_PROG([TOUCH], [touch],
              [touch], [AC_MSG_ERROR(['touch' program is missing.])])
AC_CHECK_PROGS([MKTEMP], [mktemp])
@

\paragraph{The [[awk]] program}
The old build machinery needs 'awk'.  Currently, it checks for
'gawk', 'nawk', and 'awk'.  Autoconf has a predefined test for that
task.  It checks for 'gawk', 'mawk', 'nawk', and 'awk' in that order.
That should be OK and match FriCAS's need.

The old build system claims that on solaris9, gawk, gtar
and gpatch are required (with no much explanation of why).  Notice
that these programs are needed only to build FriCAS; so we do
check based on the value of [[build]].
<<awk and tar program>>=
case $build in
     *-solaris9)
        AC_CHECK_PROG([AWK], [gawk],
                      [gawk], [AC_MSG_ERROR([FriCAS needs gawk])])

        AC_CHECK_PROG([TAR], [gtar],
                      [gtar], [AC_MSG_ERROR([FriCAS needs gtar])])

        AC_CHECK_PROG([PATCH], [gpatch],
                      [gptach], [AC_MSG_ERROR([FriCAS needs gpatch])])
        ;;

      *)
        AC_PROG_AWK

        AC_CHECK_PROGS([TAR], [gtar tar],
                       [AC_MSG_ERROR([FriCAS needs a tar program])])

        AC_CHECK_PROGS([PATCH], [gpatch patch],
                       [AC_MSG_ERROR([FriCAS needs a patch program])])
        ;;
esac
@

\paragraph{Binary utils.}

We need to know how to put object files into archives.
<<binary utils>>=
AC_PROG_RANLIB
AC_CHECK_PROG([AR], [ar], [ar], [AC_MSG_ERROR([program 'ar' is missing])])
@

\paragraph{Doc utils.}

FriCAS sources is literate, and it uses the \Tool{noweb} technology.
\Tool{noweb} is used to extract both the actual source code from the
pamphlet files, and the documentation as \LaTeX{} source files.
There are many platforms on which \Tool{noweb} is inexistent.  FriCAS source
repository used to cache a copy of \Tool{noweb}.  We now require
that an external [[noweb]] executable.
%
<<doc utils>>=
AC_PATH_PROG([LATEX], [latex])
AC_CHECK_PROG([MAKEINDEX], [makeindex])

## -------------------------
## -- Which noweb to use? --
## -------------------------
##

fricas_build_noweb=
AC_ARG_WITH([included-noweb],
            [  --with-included-noweb    build noweb from included sources],
            [case $withval in
                yes) if test -f $fricas_top_srcdir/zips/noweb-2.10a.tgz ; then
		         fricas_build_noweb=yes
                     else
                         AC_MSG_ERROR([--with-included-noweb specified, but no noweb sources is present])
                     fi  ;;
                no) fricas_build_noweb=no ;;
                *) AC_MSG_ERROR([erroneous value for --with-included-noweb]) ;;
             esac])
## Check for notangle and noweb if we are not explicitly told
## to build noweb from FriCAS sources.
if test x$fricas_build_noweb != xyes ; then
    AC_CHECK_PROGS([NOTANGLE], [notangle])
    AC_CHECK_PROGS([NOWEAVE], [noweave])

    ## In case noweb is missing we need to build our own.
    if test -z $NOTANGLE -o -z $NOWEAVE ; then
        if test x$fricas_build_noweb = xno ; then
	   AC_MSG_ERROR([noweb utils are missing but --without-included-noweb is specified])
        elif test -f $fricas_top_srcdir/zips/noweb-2.10a.tgz ; then
           fricas_build_noweb=yes
        else
           AC_MSG_ERROR([noweb utils and noweb sources missing])
	fi
    fi
fi

if test x$fricas_build_noweb = xyes ; then
    fricas_all_prerequisites="$fricas_all_prerequisites all-noweb"
    echo "fricas_build_bindir = $fricas_build_bindir"
    NOTANGLE=$fricas_build_bindir/notangle
    NOWEAVE=$fricas_build_bindir/noweave
fi
AC_SUBST(NOTANGLE)
AC_SUBST(NOWEAVE)

@

\paragraph{The Lisp platform.}

\Tool{FriCAS} uses Lisp as its main platform.  If no Lisp implementation
is available in the build environment (or if \Tool{FriCAS} is told not
to look for one) then \Tool{FriCAS} must build its own version from the
copy of \Tool{GCL} sources it keeps in the \File{gcl/} directory.
<<find lisp>>=
## ------------------------
## -- Which Lisp to use? --
## ------------------------
##
## We will default to GCL later, if no lisp implementation is specified.
fricas_lisp=
fricas_lisp_flavor=unknown
AC_ARG_WITH([lisp], [ --with-lisp=L         use L as Lisp platform],
              [fricas_lisp=$withval])
@

The [[configure]] option \verb!--with-lisp=L! specifies which
Lisp implementation flavor to use for building FriCAS.  For all values
of [[L]], except \Tool{GCL}, the assumption is that the Lisp
image [[L]] is available in the build environment.  For \Tool{GCL},
we make an exception: if no GCL image is available, or if
the option \verb!--enable-gcl! is specified then \Tool{FriCAS}
builds its own version from the source tree.
<<find lisp>>=
## If --enable-gcl is specified, we need to check for consistency
fricas_include_gcl=
if test -z $fricas_lisp; then
    AC_ARG_ENABLE([gcl], [  --enable-gcl   build GCL from FriCAS source],
                  [case $withval in
                       yes|no) fricas_include_gcl=$withval ;;
                       *) AC_MSG_ERROR([erroneous value for --enable-gcl]) ;;
                   esac])
fi
@

Do we need to build our own version of \Tool{GCL}?  The answer is yes, if
\begin{itemize}
\item the option \verb!--with-lisp! is not specified, and
\item no \Tool{GCL} image is available in the build environment.
\end{itemize}
Consequently, we need to check for \Tool{GCL}:
<<find lisp>>=
## We need to build our own GCL is none is available
if test -z $fricas_lisp; then
    AC_PATH_PROG([FRICAS_LISP], [gcl])
    fricas_lisp=$FRICAS_LISP
else
    ## Honor use of Lisp image specified on command line
    FRICAS_LISP=$fricas_lisp
    AC_SUBST(FRICAS_LISP)
    :
fi
@

We may be presented with incoherent options if
\begin{itemize}
\item \verb!--disable-gcl! is used without specifying a Lisp image, or
\item \verb!--with-lisp! is used but we are also told to build \Tool{GCL}.
\end{itemize}
<<find lisp>>=
## Coherence check for GCL inclusion.
case $fricas_include_gcl,$fricas_lisp in
    ,|no,|yes*)
       ## It doesn't make sense not to include GCL when no Lisp image
       ## is available.  Give up.
       if test $fricas_include_gcl,$FRICAS_LISP = no,; then
	   AC_MSG_ERROR([--disable-gcl specified but no GCL image found])
       fi

       ## No Lisp image was specified and none was available from
       ## the build environment; build GCL from FriCAS source.
       if test -f $fricas_top_srcdir/gcl/configure.in ; then
         FRICAS_LISP='$(fricas_build_bindir)/gcl'
         fricas_all_prerequisites="$fricas_all_prerequisites all-gcl"
         fricas_include_gcl=yes
         fricas_lisp_flavor=gcl
         fricas_fasl_type=o
       else
          AC_MSG_ERROR([GCL and GCL sources missing, see README.wh])
       fi
       ;;
    yes,*)
       AC_MSG_ERROR([--with-lisp=$fricas_lisp conflicts with --enable-gcl])
       ;;
esac

AC_ARG_WITH([lisp-flavor],
            [  --with-lisp-flavor=F  your Lisp is brand F
	           where F if one F gcl clisp sbcl ecl openmcl
		   gcl clisp sbcl ecl can be autodetected],
            [case $withval in
	    gcl|clisp|sbcl|ecl|openmcl)
	           fricas_lisp_flavor=$withval
		   ;;
	    *)
	      AC_MSG_ERROR([--with-lisp-flavor requires one of gcl clisp sbcl ecl openmcl]);;
	    esac])


if test x$fricas_lisp_flavor = xunknown ; then

       ## As of this writing, the Lisp systems ECL, GCL, and SBCL all
       ## understands the command line option --help, though they do
       ## behave very differently.  Some of them just print out the
       ## help information and exits.  Others, such as GCL, think they
       ## must enter a read-eval-print loop (which isn't very helpful).
       AC_MSG_CHECKING([which flavor of Lisp])
       what=`echo '(quit)' | $fricas_lisp --help`
       case $what in
	   *GCL*)
	       fricas_lisp_flavor=gcl
	       ;;
	   *ecl*)
	       fricas_lisp_flavor=ecl
	       ;;
	   *sbcl*)
	       fricas_lisp_flavor=sbcl
	       ;;
	   *CLISP*)
	       fricas_lisp_flavor=clisp
	       ;;
       esac
       AC_MSG_RESULT([$fricas_lisp_flavor])
fi
AC_SUBST(fricas_include_gcl)
AC_SUBST(fricas_lisp_flavor)

## The following is a horrible to arrange for GCL to successfully
## rebuild symbol tables with "rsym" on Windows platform.  It should
## go away as soon as GCL upstream is fixed.
case $fricas_lisp_flavor,$target in
    gcl,*mingw*)
        fricas_gcl_rsym_hack='d=`echo "(format nil \"~a\" si::*system-directory*)" | $(FRICAS_LISP) | grep "/gcl.*/" | sed -e "s,\",,g"`; cp $$d/rsym$(EXEEXT) .'
	;;
    *)
        fricas_gcl_rsym_hack=':'
	;;
esac
AC_SUBST(fricas_gcl_rsym_hack)
@

\paragraph{Lisp system options.}  Lisp implementations greatly vary in
the command line options they support.  Here we attempt to abstract
over those variations of Lisp systems we plan to support.  In particular,
we need to know how to invoke a Lisp compiler with a set of
files to process in batch mode.
<<lisp options>>=
## How are we supposed to tell the Lisp system to eval an expression
## in batch mode?  What is the extension of a compiled Lisp file?
case $fricas_lisp_flavor in
    gcl)
       fricas_quiet_flags='-batch'
       fricas_eval_flags='-eval'
       ;;
    ecl)
       fricas_quiet_flags=
       fricas_eval_flags='-eval'
       ;;
    sbcl)
       fricas_quiet_flags='--noinform --noprint'
       fricas_eval_flags='--eval'
       ;;
    clisp)
       fricas_quiet_flags='--quiet'
       fricas_eval_flags='-x'
       ;;
    openmcl)
       fricas_quiet_flags=
       fricas_eval_flags='--eval'
       ;;
    *) AC_MSG_ERROR([We do not know how to build FriCAS this $fricas_lisp]) ;;
esac
AC_SUBST(fricas_quiet_flags)
AC_SUBST(fricas_eval_flags)
@

\paragraph{Compiled Lisp file extensions.}
The file extension for compiled Lisp files is implementation defined.
There does not seem to have an established existing practice as would
be found in the majority of Unix world.  Consequently we need to
determine that by looking at the Lisp type of the pathname that
Lisp's [[compile-file]] would produce.
<<compiled lisp extension>>=
if test -z $fricas_fasl_type; then
    AC_MSG_CHECKING([compiled Lisp file extension])
    ## We set the IFS to <space> as we don't want automatic
    ## replacement of <newline> by <space>.
    fricas_save_IFS=$IFS
    IFS=' '
    fricas_fasl_type=`$fricas_lisp $fricas_quiet_flags $fricas_eval_flags '(progn (format t "fricas_fasl_type=~a" (pathname-type (compile-file-pathname "foo.lisp"))) (quit))'`

    ## Now pull out the fasl type.  ECL has the habit of spitting noise
    ## about internal loading.  Therefore, we must look only for a line that
    ## begins with fricas_fasl_type.
    fricas_fasl_type=`echo $fricas_fasl_type | grep '^fricas_fasl_type'`
    IFS=$fricas_save_IFS
    fricas_fasl_type=`echo $fricas_fasl_type | sed -e 's/fricas_fasl_type=//'`
    if test -z $fricas_fasl_type; then
	AC_MSG_ERROR([Could not determine extension for compiled Lisp files])
    fi
    AC_MSG_RESULT([$fricas_fasl_type])
fi
AC_SUBST(fricas_fasl_type)
@

\section{The [[FRICAS]] variable}

The FriCAS source files (especially the source files for the
interpreter) use the environment variable [[FRICAS]] in a very
pervasive way.   That variable needs to be set before the
build start --- or else, it will fail.

BASE contains the operating system root of the build environment.
In the case of MSYS/MinGW build environment on Windows it is
necessary that the FRICAS variable be a Windows absolute path.
Therefore BASE is set to the MSYS root or otherwise empty.

<<define FRICAS>>=
case $host in
    *mingw*)
        BASE=`(cd /;pwd -W)`
        ;;
    *)
        BASE=""
        ;;
esac
AC_SUBST(BASE)
FRICAS=${BASE}${fricas_targetdir}
AC_SUBST(FRICAS)
@


\section{Configuration options}
\label{sec:config-options}

We strive for making \Tool{FriCAS}'s build system integrate as seamlessly as
possibly into the standard GNU build framework.

\subsection{Standard options}
\label{sec:config-options:std}

At the moment, we honor the following options:
\begin{description}
\item \verb!--prefix!:
  By default, \Tool{FriCAS}'s build system will install files
  in ``\File{/usr/local}''.  However, you
  can select a different location prefix using this option.

\item \verb!--with-x!:

\item \verb!--x-includes=DIR!

\item \verb!--x-libraries=DIR!

\item \verb!--help!

\item \verb!--version!
\end{description}


\subsection{\Tool{FriCAS}-specific options}
\label{sec:config-options:fricas-specific}

\begin{description}
\item \verb!--enable-gcl!:
  \Tool{FriCAS} needs an implementation of Lisp to support its
  runtime system.  At the moment, GNU Common Lisp (\Tool{GCL} for short)
  is used.  This options instructs \Tool{FriCAS} to build its own copy
  of \Tool{GCL}.  Use \verb!--disable-gcl! to prevent FriCAS
  from building \Tool{GCL}.
\end{description}

\section{Basic Setup}
\label{sec:basic-setup}

\subsection{\Tool{Autoconf} Initialization}
\label{sec:basic-setup:init}

The \Tool{Autoconf} machinery needs to be initialized with several pieces of
information:
\begin{itemize}
\item the \emph{name} of the system --- ``FriCAS wh-sandbox branch''
\item its \emph{version}.  I choose to use the date of last checkin.
  It should probably include the revision number so as to
  unambiguously identify which FriCAS flavour du jour is being
  built;
\item and where to send feedback, \emph{e.g.} bug reports.  At the moment,
  we use
  the \email{fricas-devel} list.  That could change in the future if
  we reach a high volume traffic.  For the moment, we don't seem to
  suffer from traffic...
\end{itemize}
<<Autoconf init>>=
sinclude(config/fricas.m4)
AC_INIT([FriCAS], [2007-09-05],
        [fricas-devel@googlegroups.com])
fricas_top_srcdir=`cd $srcdir && pwd`
AC_SUBST(fricas_top_srcdir)
@

\Tool{Autoconf} needs some auxiliary files that are present in the
sub-directory \File{config}:
<<Autoconf init>>=
AC_CONFIG_AUX_DIR(config)
AC_CONFIG_MACRO_DIR(config)
@

Not all platforms present the same operating system API to applications.
For the part of \Tool{FriCAS} written in the C programming language, we
can collect, in a single file, variabilities in operating system
API in form of C preprocessor macros.  That file is for the most part
automatically generated by \Tool{Autoheader}.
<<Autoconf init>>=
AC_CONFIG_HEADERS([config/fricas-c-macros.h])
@

Note that at configuration time, \Tool{configure} will instantiate a
file \File{config/fricas-c-macros.h} in the directory [[$(top_builddir)]],
appropriate for all C sub-parts of \Tool{FriCAS} to include.


Notice that since we don't use Automake (yet), we don't initialize
the Automake subsystem.
<<Autoconf init>>=
# AM_INIT_AUTOMAKE([foreign])
@

We require Autoconf $2.60$ or higher from the developer part. Please,
note that this is no requirement on the user build environment.  All,
it means is that if someone makes changes to the current \File{configure.ac}
file, that someone needs to have Autoconf $2.60$ or higher to process this
file in order to regenerate \File{configure}.
<<Autoconf init>>=
AC_PREREQ([2.59])
@


\subsection{Source tree sanity check}
\label{sec:basic-setup:sanity-check}

The \Tool{Autoconf} system implements a very basic, simple-minded,
sanity check
whereby it will refuse to run \File{configure} if the source tree does
not contain a specified file, that serves a witness for a bona fide source
tree.  Here, we use \File{Makefile.pamphlet} from the \File{src}
subdirectory.
<<sanity check>>=
AC_CONFIG_SRCDIR(src/Makefile.pamphlet)
@



\subsubsection{The [[FRICAS]] variable}

The FriCAS source files (especially the source files for the
interpreter) use the environment variable [[FRICAS]] in a very
pervasive way.   That variable needs to be set before the
build start --- or else, it will fail.

\subsubsection{Instantiating configuration files}

<<instantiate config files>>=

FRICAS_MAKEFILE([Makefile])
FRICAS_MAKEFILE([src/Makefile])
FRICAS_MAKEFILE([src/lib/Makefile])
FRICAS_MAKEFILE([src/lisp/Makefile])
FRICAS_MAKEFILE([src/boot/Makefile])
FRICAS_MAKEFILE([src/interp/Makefile])
FRICAS_MAKEFILE([src/share/Makefile])
FRICAS_MAKEFILE([src/algebra/Makefile])
FRICAS_MAKEFILE([src/input/Makefile])
FRICAS_MAKEFILE([src/etc/Makefile])


AC_OUTPUT

## Generate rules to extract SPAD type definitions from pamphlets.
echo "extracting list of SPAD type definitions"
(cd $srcdir/src/algebra;
   . ../scripts/find-algebra-files) > src/algebra/tmp-extract-spad.mk
$srcdir/config/move-if-change \
    src/algebra/tmp-extract-spad.mk src/algebra/extract-spad.mk

## Configure the use of cached files.
if test -f $srcdir/src/algebra/use_lisp ; then
    # Sanity check
    if test -f $srcdir/src/algebra/A1AGG.lsp ; then
        touch src/algebra/use_lisp
    else
        AC_MSG_ERROR([Sources look corrupted])
    fi
fi

if test -f $srcdir/src/paste/copy_gphts ; then
    # Sanity check
    if test -d $srcdir/src/paste/mobius.VIEW ; then
        touch src/paste/copy_gphts
    else
        AC_MSG_ERROR([Sources look corrupted])
    fi
fi

@


\section{configure.ac}

<<*>>=
<<Autoconf init>>

<<sanity check>>

fricas_src_subdirs="lib lisp boot interp share algebra input etc doc"
AC_SUBST(fricas_src_subdirs)

<<host build target platforms>>

<<build utils>>

# FIXME: Move this out of here.
# The core runtime is always built.
fricas_c_runtime=core
AC_SUBST(fricas_c_runtime)

<<C headers and libraries>>

<<define FRICAS>>

<<platform specific bits>>
<<instantiate config files>>
echo "Type '${MAKE}' (without quotes) to build FriCAS"
@


\section{A note about comments}
\label{sec:comment}

This is a pamphlet file.  That means the source code embedded here
are first extracted into a form (\File{configure.ac}) digestible by
\Tool{Autoconf}, which in turn produces the end-user \File{configure}
script run for setting up the build.

\Tool{Autoconf} supports two kinds of comments:
\begin{enumerate}
\item [[dnl]] style, and
\item [[#]] style.
\end{enumerate}
Comments introduced with [[dnl]] are copied verbatim to the generated
\File{configure.ac}; however, do not appear in the \File{configure}
output file.  They are for \Tool{Autoconf} consumption only --- and that
of the humans reading \File{configure.ac} (ideally, there should be none).
Comments starting with [[#]] appear verbatim in both \File{configure.ac}
and \File{configure} files.  Because this is a pamphlet file, there almost
never is a need to use the [[dnl]]-style comment.
Consequently, \Tool{Autoconf} comments in this file should be
of [[#]]-style form.  Such comments can be of value to the occasional
poor masochist who will be debugging the generated \File{configure}.


\end{document}
