<title> The Hugs </title>
<body bgcolor="#ffffff">
<h2>Using Hugs as a "Haskell Server"</h2>
<font size=4> <blockquote>
Alastair Reid<br>
Reid Consulting (UK) Limited<br>
alastair@reid-consulting-uk.ltd.uk<br>
<a href="http://www.reid-consulting-uk.ltd.uk/alastair/">http://www.reid-consulting-uk.ltd.uk/alastair/</a><br>
</blockquote></font>
<a name="introduction"></a><p>
<a name="sect1"></a>
<h2>1<tt> </tt>Introduction</h2><p>
[Warning: the Haskell server is still under development - you should
expect to see changes in the server API from one release of <B>Hugs </B> to
the next.]<p>
<B>Hugs </B> is normally used as an interactive program. However, there are
situations in which you want to use <B>Hugs </B> as a non-interactive system.
Examples include:<p>
<UL><LI>
writing shell scripts in Haskell
<LI>
writing cgi scripts in Haskell
<LI>
writing Netscape plugins to let you embed Haskell code in HTML documents
(the same way that you might use Javascript or Java)
</UL><p>
For these purposes, we provide a "<B>Hugs </B> Server API" which provides
access to some of <B>Hugs </B>' innards:<p>
<UL><LI>
loading/compiling files
<LI>
compiling expressions
<LI>
constructing and evaluating "Graphs"
</UL><p>
This is not enough to implement the <B>Hugs </B> user interface, but it's good
enough for all the applications listed above. (We've done all three.)<a name="example"></a><p>
<a name="sect2"></a>
<h2>2<tt> </tt>Example</h2><p>
Here's a complete example of how to use the <B>Hugs </B> server. This
is a simplified version of the "runhugs" program which loads a
file, executes <tt>Main.main</tt> and returns the resulting exit code.
(We've left out all error handling to keep things simple in this
version.)<p>
<tt><br>
1> #include "server.h"<br>
2> extern HugsServerAPI* initHugsServer Args((int,char**));<br>
3> <br>
4> static char* hugs_argv[] = {<br>
5> "runhugs", /* program name */<br>
6> "+l" /* literate scripts as default */<br>
7> };<br>
8> static int hugs_argc = sizeof hugs_argv / sizeof hugs_argv[0];<br>
9> <br>
10> main( int argc, char** argv) <br>
11> { <br>
12> HugsServerAPI* hugs = initHugsServer(hugs_argc,hugs_argv); <br>
13> hugs->setOutputEnable(0); <br>
14> argc--; argv++; <br>
15> hugs->setHugsArgs(argc,argv); <br>
16> hugs->loadFile(argv[0]); <br>
17> hugs->lookupName("Main","main"); <br>
18> exit(hugs->doIO());<br>
19> } <br>
</tt> <p>
Here's what each line does:<p>
<DL><DT>
1-2
</DT>
<DD>
Include the server API (included in appendix <a href="server.html#server.c">A</a>)
</DD><DT>
4-8
</DT>
<DD>
Declare command line arguments used when initialising the server.
These should consist of the program name (<tt>argv[0]</tt>) and
a list of flags. Unlike <B>Hugs </B> you should not include files
to load.
</DD><DT>
12
</DT>
<DD>
Initialise the server. This returns a "virtual function table"
which is used to access all other functions in the server API.
(This is described in section <a href="server.html#initHugs">3</a>.)
</DD><DT>
13
</DT>
<DD>
Turn off output from the compiler. This does not affect output
produced by running Haskell code.
</DD><DT>
14
</DT>
<DD>
Forget the first argument on the command line. On a Unix system,
this will be the name of the above C program.
</DD><DT>
15
</DT>
<DD>
Set the values seen by the Haskell functions <tt>System.getProgName
</tt> and <tt>System.getArgs</tt>.
</DD><DT>
16
</DT>
<DD>
Load and compile the file named on the command line.
</DD><DT>
17-18
</DT>
<DD>
Lookup the Haskell function <tt>Main.main</tt> (which should be defined
in the file we just loaded and should have type <tt>IO ()</tt>).
The value returned is used as an exit code.
</DD></DL><a name="initHugs"></a><p>
<a name="sect3"></a>
<h2>3<tt> </tt>Initialising the server</h2><p>
The "Hugs server" is initialised by calling <tt>initHugsServer<p>
<br>
> HugsServerAPI* initHugsServer(<br>
> Int argc,<br>
> String argv[] /* command line flags (-P, etc) */<br>
> );<br>
<p>
</tt>This loads the standard Prelude and the dynamic typing library (see
section <a href="server.html#dynamic">8</a>) and processes any command line flags in argv.<p>
If initialisation succeeds, it returns a "virtual function table"
containing all the other server functions you can call. That is it
returns a non-null pointer to a struct of type <tt>HugsServerAPI</tt>.
We'll go through these in detail in the rest of the document --- but
here's the complete list:<p>
<tt><br>
> typedef struct _HugsServerAPI {<br>
> char* (*clearError ) (void);<br>
> void (*setHugsArgs ) (int, char**);<br>
> int (*getNumScripts ) (void);<br>
> void (*reset ) (int);<br>
> void (*setOutputEnable) (unsigned);<br>
> void (*changeDir ) (char*);<br>
> void (*loadProject ) (char*); /* obsolete */<br>
> void (*loadFile ) (char*);<br>
> HVal (*compileExpr ) (char*,char*);<br>
> <br>
> void (*lookupName ) (char*,char*); /* push values onto stack*/<br>
> void (*mkInt ) (int);<br>
> void (*mkString ) (char*);<br>
> <br>
> void (*apply ) (void); /* manipulate top of stack */<br>
> <br>
> int (*evalInt ) (void); /* evaluate top of stack */<br>
> char* (*evalString ) (void);<br>
> int (*doIO ) (void);<br>
> <br>
> HVal (*popHVal ) (void); /* pop stack */<br>
> void (*pushHVal ) (HVal); /* push back onto stack */<br>
> void (*freeHVal ) (HVal); <br>
> } HugsServerAPI;<br>
<p>
</tt>In the rest of this document, we'll assume that you've put a pointer
to the "virtual function table" in a variable called <tt>hugs</tt> and
we'll write things like this<p>
<tt><br>
> void hugs->loadFile (char*);<br>
<p>
</tt>to indicate the type of <tt>hugs->loadFile</tt>.<a name="loading files"></a><p>
<a name="sect4"></a>
<h2>4<tt> </tt>Loading files</h2><p>
Loading files is easy enough. Simply call
<tt>hugs->loadFile(<name>)</tt>.<p>
<tt><br>
> void hugs->loadFile (char*);<br>
<p>
</tt>Some programs need to be able to "unload" (or "forget") some of
the Haskell files that have been loaded. <B>Hugs </B> maintains a
"stack" of all files it has loaded. To unload some files, it pops
files off the stack. The server API provides two functions for
modifying the stack of files: <tt>getNumScripts</tt> tells you how large
the stack is; and <tt>reset</tt> sets the stack to the required size.<p>
<tt><br>
> int hugs->getNumScripts (void);<br>
> void hugs->reset (int);<br>
<p>
</tt>Typically, one writes code like this to load and execute functions
from a sequence of files. Note that the standard Prelude and
the module <tt>MyLibraries</tt> is only loaded once.<p>
<tt><br>
> HugsServerAPI* hugs = initHugsServer(hugs_argc,hugs_argv);<br>
> hugs->loadFile("MyLibraries");<br>
> int baseLevel = hugs->getNumScripts();<br>
> for(int i = 1; i < argc; ++i) {<br>
> hugs->reset(baseLevel);<br>
> hugs->loadFile(argv[i]); <br>
> hugs->lookupName("Main","main"); <br>
> hugs->doIO();<br>
> }<br>
<a name="evaluating"></a><p>
</tt><a name="sect5"></a>
<h2>5<tt> </tt>Executing Expressions</h2><p>
In section <a href="server.html#example">2</a> we used <tt>lookupName</tt> to lookup
<tt>"Main.main"</tt> and <tt>doIO</tt> to execute it. As you've probably
guessed, <tt>lookupName</tt> leaves a "pointer" to <tt>Main.main</tt> on
the stack and <tt>doIO</tt> evaluates the object found on top of the stack.
Here are some of the other operations which operate on the stack:<p>
<tt><br>
> void hugs->mkInt (int);<br>
> int hugs->evalInt (void); <br>
> <br>
> void hugs->mkString (char*);<br>
> char* hugs->evalString (void); <br>
> <br>
> void hugs->apply (void); <br>
> <br>
> void hugs->lookupName (char*,char*);<br>
> int hugs->doIO (void); <br>
<p>
</tt>The new functions are as follows:<p>
<UL><LI>
<tt>mkInt</tt> pushes (a representation of) an <tt>int</tt> onto
the stack.
<tt>evalInt</tt> evaluates the <tt>Int</tt> on top of the stack.<p>
<LI>
Similarily, <tt>mkString</tt> pushes (a representation of) a
C string onto the stack and
<tt>evalString</tt> evaluates the <tt>String</tt> on top of the stack.<p>
<LI>
<tt>apply</tt> pops an argument and a function off the stack (in that
order) and applies the function to the argument. A typical usage
is
<tt><br>
> hugs->lookupName("Foo","ackerman");<br>
> hugs->mkInt(4);<br>
> hugs->apply();<br>
> hugs->mkInt(2);<br>
> hugs->apply();<br>
<p>
</tt> Alternatively, you might define this macro
<tt><br>
> #define ap(f,x) f; x; hugs->apply();<br>
</tt> and write this
<tt><br>
> ap(ap( hugs->lookupName("Foo","factorial")<br>
> , hugs->mkInt(4))<br>
> , hugs->mkInt(2));<br>
<p>
</tt></UL><p>
<p>
<font color=red>ToDo: </font><font color=red><I> The server API currently provides no way to push floats, chars, etc onto
the stack. There's no real problem in adding this, but we haven't
needed it yet.<p>
<p>
</I></font><a name="sect6"></a>
<h2>6<tt> </tt>Haskell Values</h2><p>
It's sometimes useful to be able to store the result of a calculation
for later use. These operations allow you to pop Haskell Values
off the stack, store them and later push them back onto the stack.<p>
<tt><br>
> HVal hugs->popHVal (void); <br>
> void hugs->pushHVal (HVal); <br>
> void hugs->freeHVal (HVal); <br>
<p>
</tt>"Haskell Values" remain valid if you load additional Haskell files
and if you evaluate expressions but are invalidated by calling
<tt>reset</tt>. <p>
<I>Warning: No check is performed to detect the use of invalid values; the
result is likely to be messy.<p>
</I><a name="sect7"></a>
<h2>7<tt> </tt>Compiling Expressions</h2><p>
The functions described in section <a href="server.html#evaluating">5</a> let you evaluate
almost any Haskell expression but are rather painful to use. This
version of the server provides a much more convenient function which
lets you compile arbitrary Haskell expressions.<p>
<tt><br>
> HVal hugs->compileExpr (char*,char*);<br>
<p>
</tt>The function <tt>compileExpr</tt> takes two arguments. The first
argument is the name of the module in which to evaluate the
expression. The choice of module determines which functions are in
scope. The second argument is the expression itself.<p>
<I>Portability: The current version of the server includes the full </I><B>Hugs </B><I> compiler
so that we can load the Prelude and other libraries. Since the
compiler is included in the server, it is both cheap and easy to
provide </I><tt>compileExpr</tt><I>. In future versions of the server, we'd
like to be able to load precompiled versions of the Prelude and
libraries and omit most of the </I><B>Hugs </B><I> compiler. In such a system,
we would also omit </I><tt>compileExpr</tt><I> since it is possible to do
most of what </I><tt>compileExpr</tt><I> does using </I><tt>lookupName</tt><I> and
</I><tt>apply</tt><I>.<p>
<p>
</I><font color=red>ToDo: </font><font color=red><I> </I></font><font color=red><tt>compileExpr</tt></font><font color=red><I> really ought to leave its result on the stack.<p>
<a name="dynamic"></a><p>
</I></font><a name="sect8"></a>
<h2>8<tt> </tt>Dynamic Types</h2> <p>
The evaluation mechanisms described above make it very easy to
construct and attempt to evaluate ill-typed objects. To avert
catastrophe, the server typechecks very function application.
The mechanisms used to perform this typecheck are not as flexible
as the Haskell type system for two reasons:<p>
<UL><LI>
Typechecking is restricted to a small set of base types and
type constructors. If you need to use other types, you'll need
to define new instances of the <tt>Typeable</tt> class. Use the
instances in appendix <a href="server.html#dynamic-defn">B</a> as examples of how to write
your own instances.
<LI>
Typechecking is restricted to <I>monomorphic</I> values. Looking
up a polymorphic function will always result in an error. There
are two solutions:
<UL><LI>
Add monomorphic instances of the functions to your code. For example,
if you need to use <tt>Prelude.length</tt> at 3 different types, you
might write a module containing these definitions
<tt><br>
> length_Int :: [Int] -> Int<br>
> length_Int = length<br>
> <br>
> length_Ints :: [[Int]] -> Int<br>
> length_Ints = length<br>
<p>
</tt><LI>
Use <tt>compileExpr</tt> to lookup the values at different types
<tt><br>
> HVal length_Int = hugs->compileExpr("Prelude","length :: [Int] -> Int");<br>
> HVal length_Ints = hugs->compileExpr("Prelude","length :: [[Int]] -> Int");<br>
<p>
</tt></UL>
In practice, both are equally irritating.<p>
</UL><p>
<p>
<font color=red>ToDo: </font><font color=red><I> If we remove </I></font><font color=red><tt>compileExpr</tt></font><font color=red><I> we should probably improve the dynamic
typing.<p>
<a name="errors"></a><p>
</I></font><a name="sect9"></a>
<h2>9<tt> </tt>Handling Errors</h2><p>
So far, we have assumed that errors almost never occur. In practice
error-free execution is the norm: the standard prelude can't be found;
filenames are wrong; programs contain syntax and type errors; modules
don't define what they're supposed to; people look up polymorphic
functions; Haskell code returns errors; etc.<p>
The <B>Hugs </B> server is fairly robust: it tries to catch any errors and
will not perform any further actions until the error is resolved.
The function <tt>clearError</tt> is used to detect whether an error
has occurred (since the last time <tt>clearError</tt> was called); to
obtain any compiler output associated with the error; and to reset
an "error flag". <p>
<tt><br>
> char* hugs->clearError (void);<br>
<p>
</tt>All other functions in the server API return immediately if the error
flag is set --- this encourages programmers to call <tt>clearError
</tt>frequently and prevents the server from being totally corrupted if
<tt>clearError</tt> is not used.<p>
The output returned by <tt>clearError</tt> depends on whether or not
compiler output has been redirected to a buffer using the function
<tt>setOutputEnable<p>
<br>
> void hugs->setOutputEnable (unsigned);<br>
<p>
</tt>If compiler output has not been redirected, <tt>clearError</tt> produces
a brief error message. If compiler output has not been redirected,
then <tt>clearError</tt> produces an error message followed by all the
output that has been collected since the last time <tt>clearError
</tt>was called.<p>
Using these features, it's possible to write a more robust version of
the runhugs program given in section <a href="server.html#example">2</a>.<p>
<tt><br>
> static void check() {<br>
> char* err = hugs->clearError();<br>
> if (err) {<br>
> fprintf(stderr,"Hugs Error:\n%s\n",err);<br>
> fflush(stderr);<br>
> exit(1);<br>
> }<br>
> }<br>
> <br>
> main( int argc, char** argv) <br>
> { <br>
> int exitCode;<br>
> HugsServerAPI* hugs = initHugsServer(hugs_argc,hugs_argv); <br>
> if (NULL == hugs) {<br>
> fprintf(stderr,"Unable to initialise Hugs\n");<br>
> fflush(stderr);<br>
> exit(1);<br>
> }<br>
> hugs->setOutputEnable(0); <br>
> check();<br>
> argc--; argv++; <br>
> hugs->setHugsArgs(argc,argv); <br>
> if (argc < 1) {<br>
> fprintf(stderr,"hugs standalone requires at least one argument\n");<br>
> fflush(stderr);<br>
> exit(1);<br>
> }<br>
> hugs->loadFile(argv[0]); <br>
> check();<br>
> hugs->lookupName("Main","main"); <br>
> exitCode = hugs->doIO();<br>
> check();<br>
> exit(exitCode);<br>
> } <br>
<a name="server.c"></a><p>
</tt><a name="sectA"></a>
<h2>A<tt> server.h</tt></h2><p>
This is the current contents of the file <tt>server.h</tt>. This is
the only file you need to include into programs that use the server.<p>
<tt><br>
/* --------------------------------------------------------------------------<br>
* Definition of the Hugs server API<br>
*<br>
* Copyright (c) The University of Nottingham and Yale University, 1994-1997.<br>
* All rights reserved. See NOTICE for details and conditions of use etc...<br>
* Hugs version 1.4, April 1997<br>
* ------------------------------------------------------------------------*/<br>
<br>
#ifndef Args<br>
# if HAVE_PROTOTYPES<br>
# define Args(x) x<br>
# else<br>
# define Args(x) ()<br>
# endif<br>
#endif /* !defined Args */<br>
<br>
typedef int HVal; /* Haskell values are represented by stable pointers */<br>
<br>
typedef struct _HugsServerAPI {<br>
char* (*clearError ) Args((void));<br>
void (*setHugsArgs ) Args((int, char**));<br>
int (*getNumScripts ) Args((void));<br>
void (*reset ) Args((int));<br>
void (*setOutputEnable) Args((unsigned));<br>
void (*changeDir ) Args((char*));<br>
void (*loadProject ) Args((char*)); /* obsolete */<br>
void (*loadFile ) Args((char*));<br>
HVal (*compileExpr ) Args((char*,char*));<br>
<br>
void (*lookupName ) Args((char*,char*)); /* push values onto stack*/<br>
void (*mkInt ) Args((int));<br>
void (*mkString ) Args((char*));<br>
<br>
void (*apply ) Args((void)); /* manipulate top of stack */<br>
<br>
int (*evalInt ) Args((void)); /* evaluate top of stack */<br>
char* (*evalString ) Args((void));<br>
int (*doIO ) Args((void));<br>
<br>
HVal (*popHVal ) Args((void)); /* pop stack */<br>
void (*pushHVal ) Args((HVal)); /* push back onto stack */<br>
void (*freeHVal ) Args((HVal)); <br>
} HugsServerAPI;<br>
<br>
/* type of "initHugsServer" function */<br>
typedef HugsServerAPI *(*HugsServerInitFun) Args((int, char**));<br>
<br>
/* ------------------------------------------------------------------------*/<br>
<br>
<a name="dynamic-defn"></a><p>
</tt><a name="sectB"></a>
<h2>B<tt> </tt>The <tt>Dynamic</tt> module</h2><p>
<tt><br>
module Dynamic<br>
( Typeable(typeOf),<br>
, Dynamic, toDynamic, fromDynamic, dynApply,<br>
, fromDyn, dynApp, <br>
, intToDyn, fromDynInt, strToDyn, fromDynStr,<br>
, Tycon(..), Type(..)<br>
) where<br>
<br>
----------------------------------------------------------------<br>
-- Dynamics<br>
----------------------------------------------------------------<br>
<br>
data Dynamic = ...<br>
<br>
-- The core functions<br>
toDynamic :: Typeable a => a -> Dynamic<br>
fromDynamic :: Typeable a => Dynamic -> Maybe a<br>
dynApply :: Dynamic -> Dynamic -> Maybe Dynamic<br>
<br>
-- special cases<br>
fromDyn :: Typeable a => Dynamic -> a<br>
intToDyn :: Int -> Dynamic<br>
strToDyn :: String -> Dynamic<br>
fromDynInt :: Dynamic -> Int<br>
fromDynStr :: Dynamic -> String<br>
runDyn :: Dynamic -> IO ()<br>
dynApp :: Dynamic -> Dynamic -> Dynamic<br>
<br>
----------------------------------------------------------------<br>
-- Types<br>
----------------------------------------------------------------<br>
<br>
data Tycon = Tycon String deriving Eq<br>
data Type = App Tycon [Type] deriving Eq<br>
<br>
unitTC = Tycon "()"<br>
intTC = Tycon "Int"<br>
integerTC = Tycon "Integer"<br>
floatTC = Tycon "Float"<br>
doubleTC = Tycon "Double"<br>
charTC = Tycon "Char"<br>
ioTC = Tycon "IO"<br>
funTC = Tycon "->"<br>
listTC = Tycon "[]"<br>
tup2TC = Tycon "(,)"<br>
<br>
class Typeable a where typeOf :: a -> Type<br>
<br>
-- Constant Tycons are easy<br>
<br>
instance Typeable () where typeOf x = App unitTC []<br>
instance Typeable Int where typeOf x = App intTC []<br>
instance Typeable Integer where typeOf x = App integerTC []<br>
instance Typeable Float where typeOf x = App floatTC []<br>
instance Typeable Double where typeOf x = App doubleTC []<br>
instance Typeable Char where typeOf x = App charTC []<br>
<br>
-- Non-constant Tycons require sneakiness<br>
<br>
instance Typeable a => Typeable (IO a) where <br>
typeOf m = <br>
case unsafePerformIO m of { r -><br>
App ioTC [typeOf r]<br>
}<br>
<br>
instance (Typeable a, Typeable b) => Typeable (a -> b) where<br>
typeOf f = <br>
-- We use case to bind arg and result to avoid excess polymorphism<br>
case undefined of { arg -><br>
case f arg of { result -><br>
App funTC [typeOf arg, typeOf result]<br>
}}<br>
<br>
instance Typeable a => Typeable [a] where<br>
typeOf xs = App listTC [typeOf (head xs)]<br>
<br>
instance (Typeable a, Typeable b) => Typeable (a,b) where<br>
typeOf p = App tup2TC [typeOf (fst p), typeOf (snd p)]<br>
<p>
</tt>